// First-time intro overlay. 4 slides, Skip from anywhere, finish marks
// BFOnboarding flag so it never shows again unless user hits "Show intro
// again" in Settings (which calls BFOnboarding.reset()).
//
// Visual style: matches app theme (dark surface, serif hero, accent-tinted
// action button). No external deps — uses BFIcon from src/ui.jsx.

function BFOnboardingOverlay({ accentH = 200, theme, onFinish }) {
  const [step, setStep] = React.useState(0);
  const [leaving, setLeaving] = React.useState(false);
  // Final optional step: pick the starting breath (when the flavor/admin
  // lists 2+ starterChoices and the user hasn't practiced yet).
  const [choosing, setChoosing] = React.useState(false);
  // Re-resolve strings on language change so the overlay reacts if the
  // user flips locale before tapping Continue.
  const [, forceRender] = React.useState(0);
  React.useEffect(() => {
    if (!window.BFI18n) return;
    return window.BFI18n.onChange(() => forceRender((n) => n + 1));
  }, []);
  const t = (k, p) => (window.BFI18n ? window.BFI18n.t(k, p) : k);

  const slides = [
    {
      title: t('onboarding.slide1_title'),
      body:  t('onboarding.slide1_body'),
      cta:   t('onboarding.continue'),
    },
    {
      title: t('onboarding.slide2_title'),
      body:  t('onboarding.slide2_body'),
      cta:   t('onboarding.continue'),
    },
    {
      title: t('onboarding.slide3_title'),
      body:  t('onboarding.slide3_body'),
      cta:   t('onboarding.continue'),
    },
    {
      title: t('onboarding.slide4_title'),
      body:  t('onboarding.slide4_body'),
      cta:   t('onboarding.start'),
    },
  ];
  const s = slides[step];
  const last = step === slides.length - 1;

  const finish = async (_viaSkip) => {
    setLeaving(true);
    await BFOnboarding.markCompleted();
    if (typeof BFToast !== 'undefined') {
      BFToast.info(t('onboarding.welcome_title'), t('onboarding.welcome_body'));
    }
    setTimeout(() => { onFinish && onFinish(); }, 220);
  };

  const canChoose = !!(window.BFUnlock && window.BFUnlock.canChooseStarter && window.BFUnlock.canChooseStarter());
  const next = () => {
    if (!last) { setStep(step + 1); return; }
    if (canChoose) setChoosing(true);
    else finish(false);
  };
  const back = () => setStep(Math.max(0, step - 1));
  const skip = () => finish(true);
  const choose = async (id) => {
    try { await window.BFUnlock.setStarter(id); } catch (e) {}
    finish(false);
  };

  const accentBg = bfAccentSolid(accentH);
  const fg = theme.fg, bg = theme.bg, line = theme.line, fgMuted = theme.fgMuted, fgFaint = theme.fgFaint;
  const halo = bfIsLightTheme(theme)
    ? `oklch(0.92 0.06 ${accentH} / 0.55)`
    : `oklch(0.28 0.05 ${accentH} / 0.55)`;

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Welcome to One Breath"
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: `radial-gradient(ellipse at 50% 30%, ${halo} 0%, ${bg} 60%)`,
        color: fg, fontFamily: BF_FONTS.sans,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
        opacity: leaving ? 0 : 1,
        transition: 'opacity .22s ease',
      }}
    >
      {/* Skip in the top-right */}
      <button
        onClick={skip}
        aria-label={t('onboarding.skip')}
        style={{
          position: 'absolute', top: 18, right: 18,
          background: 'rgba(255,255,255,0.05)', color: fgMuted,
          border: 'none', borderRadius: 999, padding: '8px 14px',
          fontFamily: BF_FONTS.sans, fontSize: 12, letterSpacing: 0.3,
          cursor: 'pointer',
        }}
      >
        {t('onboarding.skip')}
      </button>

      <div style={{
        maxWidth: 420, width: '100%',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        textAlign: 'center',
      }}>
        {choosing ? (
          <>
            {/* Choose your breath — the pick becomes unlocked[0]. */}
            <div style={{
              fontFamily: BF_FONTS.serif, fontStyle: 'italic',
              fontSize: 36, lineHeight: 1.05, letterSpacing: -0.6,
              marginBottom: 14, textWrap: 'balance',
            }}>
              {t('onboarding.choose_title')}
            </div>
            <div style={{
              fontSize: 14, lineHeight: 1.5, color: fgMuted,
              maxWidth: 340, marginBottom: 28, textWrap: 'pretty',
            }}>
              {t('onboarding.choose_sub')}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, width: '100%', maxWidth: 360 }}>
              {(window.BFUnlock ? window.BFUnlock.starterChoices() : []).map((id) => {
                const p = (typeof BF_PATTERNS !== 'undefined' ? BF_PATTERNS : []).find((x) => x.id === id);
                if (!p) return null;
                return (
                  <button
                    key={id}
                    onClick={() => choose(id)}
                    style={{
                      textAlign: 'left', cursor: 'pointer',
                      background: 'rgba(255,255,255,0.05)', color: fg,
                      border: `1px solid ${line}`, borderRadius: 18,
                      padding: '16px 18px', fontFamily: BF_FONTS.sans,
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                      <span style={{ fontSize: 16, fontWeight: 600 }}>{bfPatternName(p)}</span>
                      <span style={{ fontFamily: BF_FONTS.mono, fontSize: 11, color: fgFaint }}>
                        {p.inhale}·{p.holdIn}·{p.exhale}·{p.holdOut}
                      </span>
                    </div>
                    <div style={{ fontSize: 12.5, color: fgMuted, marginTop: 6, lineHeight: 1.45, textWrap: 'pretty' }}>
                      {bfPatternDesc(p)}
                    </div>
                  </button>
                );
              })}
            </div>
          </>
        ) : (
          <>
            {/* Dots */}
            <div style={{ display: 'flex', gap: 6, marginBottom: 40 }}>
              {slides.map((_, i) => (
                <div key={i} style={{
                  width: i === step ? 22 : 6, height: 6, borderRadius: 999,
                  background: i === step ? accentBg : 'rgba(255,255,255,0.18)',
                  transition: 'width .22s ease, background .22s ease',
                }}/>
              ))}
            </div>

            {/* Headline */}
            <div style={{
              fontFamily: BF_FONTS.serif, fontStyle: 'italic',
              fontSize: 40, lineHeight: 1.05, letterSpacing: -0.6,
              marginBottom: 18, textWrap: 'balance',
            }}>
              {s.title}
            </div>

            {/* Body */}
            <div style={{
              fontSize: 15, lineHeight: 1.5, color: fgMuted,
              maxWidth: 360, marginBottom: 36, textWrap: 'pretty',
            }}>
              {s.body}
            </div>

            {/* CTA row */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', justifyContent: 'center' }}>
              {step > 0 && (
                <button
                  onClick={back}
                  style={{
                    background: 'transparent', border: `1px solid ${line}`,
                    color: fgMuted, padding: '12px 22px', borderRadius: 999,
                    fontFamily: BF_FONTS.sans, fontSize: 14, cursor: 'pointer',
                  }}
                >
                  {t('common.back')}
                </button>
              )}
              <button
                onClick={next}
                style={{
                  background: accentBg, color: bg,
                  border: 'none', padding: '14px 28px', borderRadius: 999,
                  fontFamily: BF_FONTS.sans, fontSize: 15, fontWeight: 500,
                  cursor: 'pointer',
                  boxShadow: `0 8px 28px oklch(0.78 0.1 ${accentH} / 0.35)`,
                  minWidth: 180,
                }}
              >
                {s.cta}
              </button>
            </div>

            {/* Step counter (subtle) */}
            <div style={{
              marginTop: 26, fontFamily: BF_FONTS.mono, fontSize: 11,
              color: fgFaint, letterSpacing: 0.5,
            }}>
              {step + 1} / {slides.length}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { BFOnboardingOverlay });
