/* ============================================================
   SVLM — first-run greeting: Language select -> Onboarding carousel
   -> Login. Ported behavior from public/index.html's
   maybeShowLanguageScreen()/maybeShowOnboarding() — same localStorage
   gates (svlm_language_selected / svlm_onboarding_seen) so a
   returning visitor skips straight to login/home like the real app,
   and the same real GET /api/onboarding-slides content.
   ============================================================ */
const Pob = window.PALETTE;
const LANG_OPTIONS = [
  ['en', 'English'], ['th', 'ไทย'], ['ru', 'Русский'], ['fr', 'Français'],
  ['es', 'Español'], ['ja', '日本語'], ['zh', '中文'], ['ar', 'العربية'],
];

function LanguageScreen({ onDone }) {
  const [choice, setChoice] = React.useState(getLang('customer'));
  const confirm = () => {
    localStorage.setItem('svlm_language_selected', '1');
    setLanguage('customer', choice); // persists to localStorage; does NOT reload here (no full page in a SPA)
    onDone();
  };
  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: 24, background: Pob.bg }}>
      <div style={{ maxWidth: 380, margin: '0 auto', width: '100%', textAlign: 'center' }}>
        <Logo h={56} style={{ margin: '0 auto 20px' }} />
        <h2 style={{ fontSize: 22, fontWeight: 800, color: Pob.ink, margin: '0 0 8px' }}>{t('customer', 'select_language_title')}</h2>
        <p style={{ fontSize: 14, color: Pob.muted, margin: '0 0 24px' }}>{t('customer', 'select_language_subtitle')}</p>
        <select value={choice} onChange={e => setChoice(e.target.value)}
          style={{ width: '100%', height: 52, borderRadius: 14, border: `1.5px solid ${Pob.line}`, padding: '0 14px', fontFamily: 'inherit', fontSize: 15, color: Pob.ink, background: '#fff', marginBottom: 18 }}>
          {LANG_OPTIONS.map(([code, label]) => <option key={code} value={code}>{label}</option>)}
        </select>
        <Btn onClick={confirm}>{t('customer', 'continue_button')}</Btn>
      </div>
    </div>
  );
}

function OnboardingScreen({ onDone }) {
  const [slides, setSlides] = React.useState(null);
  const [index, setIndex] = React.useState(0);

  React.useEffect(() => {
    api('/onboarding-slides').then(setSlides).catch(() => setSlides([])); // fail-open, same as the vanilla app
  }, []);

  if (slides === null) return null; // brief loading gap — no spinner needed, this resolves fast
  if (slides.length === 0) { onDone(); return null; }

  const slide = slides[index];
  const isLast = index === slides.length - 1;
  const lang = getLang('customer');
  const title = lang === 'th' ? (slide.title_th || slide.title_en) : slide.title_en;
  const subtitle = lang === 'th' ? (slide.subtitle_th || slide.subtitle_en) : slide.subtitle_en;

  const next = () => {
    if (index < slides.length - 1) setIndex(index + 1);
    else { localStorage.setItem('svlm_onboarding_seen', '1'); onDone(); }
  };

  return (
    <div style={{ minHeight: '100vh', background: Pob.bg, maxWidth: 480, margin: '0 auto' }}>
      {slide.image_url
        ? <img src={slide.image_url} alt="" style={{ width: '100%', height: '52vh', maxHeight: 460, objectFit: 'cover', display: 'block', borderRadius: '0 0 28px 28px' }} />
        : <div style={{ width: '100%', height: '52vh', maxHeight: 460, background: `linear-gradient(135deg, ${Pob.primaryDk}, ${Pob.primary})`, borderRadius: '0 0 28px 28px' }} />}
      <div style={{ padding: '24px 20px 30px' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
          {slides.map((_, i) => (
            <span key={i} onClick={() => setIndex(i)} style={{
              width: i === index ? 22 : 8, height: 8, borderRadius: i === index ? 4 : 99,
              background: i === index ? Pob.primary : Pob.line, cursor: 'pointer', transition: 'all .15s',
            }} />
          ))}
        </div>
        <h2 style={{ fontSize: 22, fontWeight: 800, color: Pob.ink, margin: '0 0 8px' }}>{title}</h2>
        {subtitle && <p style={{ fontSize: 14, color: Pob.muted, margin: '0 0 22px' }}>{subtitle}</p>}
        <Btn onClick={next}>{isLast ? t('customer', 'get_started') : t('customer', 'continue_button')}</Btn>
      </div>
    </div>
  );
}

/* Wraps Language -> Onboarding -> children (AuthScreen), gated by the same localStorage flags
   the real app uses, and skipped outright for OAuth-callback / already-signed-in visits — matches
   public/index.html's `skipPreLoginScreens` logic exactly. */
function GreetingGate({ skip, children }) {
  const [phase, setPhase] = React.useState(() => {
    if (skip) return 'done';
    if (!localStorage.getItem('svlm_language_selected')) return 'language';
    if (!localStorage.getItem('svlm_onboarding_seen')) return 'onboarding';
    return 'done';
  });

  if (phase === 'language') return <LanguageScreen onDone={() => setPhase(localStorage.getItem('svlm_onboarding_seen') ? 'done' : 'onboarding')} />;
  if (phase === 'onboarding') return <OnboardingScreen onDone={() => setPhase('done')} />;
  return children;
}

Object.assign(window, { LanguageScreen, OnboardingScreen, GreetingGate });
