/* Flow.jsx — Muna Health onboarding flow
   Splash → 3 value props → Sign up ↔ Sign in → confirmation.
   Transitions: 220ms horizontal slide (12% travel) + crossfade, --ease-out.
   Uses MunaComponents (Button, Icon, ProgressDots) + AuthKit (TextField, SocialButton…) */

// ─── Screen order — drives slide direction ──────────────────────────────
const ORDER = { splash: 0, v0: 1, v1: 2, v2: 3, signup: 4, signin: 5, done: 6 };

// ─── Value-prop content ─────────────────────────────────────────────────
const VALUE_PROPS = [
  {
    eyebrow: 'Welcome to Muna',
    title: 'Your mouth tells a story about your whole body.',
    body: 'Bleeding gums, plaque patterns, even the colour of your tongue hint at what\u2019s happening beneath the surface. Muna learns to read those signs.',
    glyph: 'sprout', tint: 'var(--amber-50)', ring: 'var(--amber-100)', accent: 'var(--amber-700)',
  },
  {
    eyebrow: 'How it works',
    title: 'Four photos and a few short questions.',
    body: 'A guided five-minute screening, read by an AI trained on millions of patterns. No clinic visit, no waiting room \u2014 just your phone.',
    glyph: 'camera', tint: 'var(--amber-50)', ring: 'var(--amber-100)', accent: 'var(--amber-700)',
  },
  {
    eyebrow: 'What comes next',
    title: 'A clear score, and people who can help.',
    body: 'You\u2019ll get one honest risk score and a plan that fits it \u2014 a wellness check, a 30-day reversal, or care from a clinician. Always with real people.',
    glyph: 'heart', tint: 'var(--amber-50)', ring: 'var(--amber-100)', accent: 'var(--amber-700)',
  },
];

// ─── Hero block (value props) ───────────────────────────────────────────
function Hero({ vp, heroStyle, grain }) {
  return (
    <div style={{
      background: vp.tint, borderRadius: 'var(--radius-xl)', height: 296,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative', overflow: 'hidden',
    }}>
      <PaperGrain on={grain} opacity={0.05}/>
      {heroStyle === 'photo' ? (
        <div style={{
          position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', gap: 10, color: vp.accent,
          background: 'linear-gradient(165deg, rgba(255,255,255,0.35), rgba(255,255,255,0))',
        }}>
          <div style={{
            width: 64, height: 64, borderRadius: '50%', background: 'rgba(255,255,255,0.7)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="camera" size={30} strokeWidth={1.5}/>
          </div>
          <div style={{ font: 'var(--type-caption)', color: vp.accent, opacity: 0.85 }}>Photograph goes here</div>
        </div>
      ) : (
        <div style={{
          width: 150, height: 150, borderRadius: '50%', background: '#fff',
          boxShadow: 'var(--shadow-m)', display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: vp.accent, position: 'relative',
        }}>
          <div style={{
            position: 'absolute', inset: -14, borderRadius: '50%',
            border: `1.5px solid ${vp.ring}`,
          }}/>
          <Icon name={vp.glyph} size={66} strokeWidth={1.4}/>
        </div>
      )}
    </div>
  );
}

// ─── Splash ─────────────────────────────────────────────────────────────
function Splash({ onContinue, grain, auto, onLongPressMark }) {
  const [shown, setShown] = React.useState(false);
  const pressTimer = React.useRef(null);
  React.useEffect(() => {
    const r = setTimeout(() => setShown(true), 30);
    let t;
    if (auto) t = setTimeout(onContinue, 2100);
    return () => { clearTimeout(r); if (t) clearTimeout(t); };
  }, []);
  const startPress = (e) => {
    if (!onLongPressMark) return;
    e.stopPropagation();
    pressTimer.current = setTimeout(() => { pressTimer.current = 'fired'; onLongPressMark(); }, 600);
  };
  const endPress = (e) => {
    if (pressTimer.current && pressTimer.current !== 'fired') clearTimeout(pressTimer.current);
    const fired = pressTimer.current === 'fired';
    pressTimer.current = null;
    if (fired) { e.stopPropagation(); e.preventDefault(); }
  };
  return (
    <div onClick={onContinue} style={{
      position: 'absolute', inset: 0, background: 'var(--bg)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      cursor: 'pointer', overflow: 'hidden',
    }}>
      <PaperGrain on={grain} opacity={0.045}/>
      <div style={{
        opacity: shown ? 1 : 0, transform: shown ? 'translateY(0)' : 'translateY(8px)',
        transition: 'opacity 900ms var(--ease-out), transform 900ms var(--ease-out)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 26, padding: '0 40px',
      }}>
        <img src="assets/muna-wordmark.png" alt="Muna Health"
          onPointerDown={startPress} onPointerUp={endPress} onPointerLeave={endPress}
          style={{ width: 232, height: 'auto', display: 'block', WebkitUserSelect: 'none', userSelect: 'none', WebkitTouchCallout: 'none' }}/>
        <div style={{
          font: 'var(--type-body)', color: 'var(--fg-3)', textAlign: 'center', maxWidth: 280,
          textWrap: 'pretty', letterSpacing: 'var(--tracking-snug)',
        }}>
          Whole-body health, read from your smile.
        </div>
      </div>
      <div style={{
        position: 'absolute', bottom: 58, left: 0, right: 0, textAlign: 'center',
        opacity: shown ? (auto ? 0 : 0.9) : 0, transition: 'opacity 1200ms var(--ease-out)',
        font: 'var(--type-caption)', color: 'var(--fg-4)', letterSpacing: 'var(--tracking-wide)',
      }}>
        Tap to begin
      </div>
    </div>
  );
}

// ─── DemoSheet — DEV-only result-path selector (long-press the mark) ────
//   ⚠ PROTOTYPE ONLY — remove for production.
function DemoSheet({ open, onClose, onPick }) {
  const opts = [
    { tier: 'healthy', label: 'Demo healthy result', sub: 'Lands a 70–100 score', dot: 'var(--sage-500)' },
    { tier: 'moderate', label: 'Demo moderate result', sub: 'Lands a 41–69 score', dot: 'var(--amber-500)' },
    { tier: 'high', label: 'Demo high-risk result', sub: 'Lands a 0–40 score', dot: 'var(--clay-500)' },
  ];
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 50, pointerEvents: open ? 'auto' : 'none' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'var(--bg-overlay)', opacity: open ? 1 : 0, transition: 'opacity var(--dur-slow) var(--ease-out)' }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        background: '#fff', borderRadius: 'var(--radius-l) var(--radius-l) 0 0',
        padding: '10px 20px 38px', boxShadow: 'var(--shadow-l)',
        transform: open ? 'translateY(0)' : 'translateY(100%)',
        transition: 'transform var(--dur-slow) var(--ease-out)',
      }}>
        <div style={{ width: 38, height: 4, borderRadius: 2, background: 'var(--stone-300)', margin: '0 auto 18px' }}/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <div style={{ font: 'var(--type-overline)', letterSpacing: 'var(--tracking-loose)', textTransform: 'uppercase', color: 'var(--stone-400)', border: '1px dashed var(--stone-400)', borderRadius: 'var(--radius-pill)', padding: '2px 8px' }}>DEV</div>
          <div style={{ font: 'var(--type-h3)', color: 'var(--fg-1)' }}>Demo a result path</div>
        </div>
        <p style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)', marginBottom: 16 }}>Fills the questionnaire to land any tier — skips straight to the result.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {opts.map(o => (
            <button key={o.tier} onClick={() => onPick(o.tier)} style={{
              display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', cursor: 'pointer',
              background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-m)', padding: '14px 16px',
            }}>
              <div style={{ width: 10, height: 10, borderRadius: '50%', background: o.dot, flexShrink: 0 }}/>
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--type-body)', color: 'var(--fg-1)' }}>{o.label}</div>
                <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)', marginTop: 1 }}>{o.sub}</div>
              </div>
              <Icon name="chevron-right" size={18} color="var(--fg-4)"/>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

// ─── Value prop screen ──────────────────────────────────────────────────
function ValueProp({ index, onNext, onBack, onSkip, heroStyle, grain }) {
  const vp = VALUE_PROPS[index];
  const last = index === VALUE_PROPS.length - 1;
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
      {/* top bar */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '0 12px 0 16px', paddingTop: 56, height: 44, boxSizing: 'content-box', flexShrink: 0,
      }}>
        {index === 0 ? (
          <img src="assets/muna-mark.png" alt="Muna" style={{ width: 30, height: 30, borderRadius: 8, display: 'block' }}/>
        ) : (
          <button onClick={onBack} aria-label="Back" style={{
            background: 'transparent', border: 0, cursor: 'pointer', color: 'var(--fg-1)',
            width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', marginLeft: -8,
          }}>
            <Icon name="chevron-left" size={26}/>
          </button>
        )}
        <Button variant="tertiary" onClick={onSkip} style={{ color: 'var(--fg-2)' }}>Skip</Button>
      </div>

      {/* hero */}
      <div style={{ padding: '8px var(--gutter-screen) 0' }}>
        <Hero vp={vp} heroStyle={heroStyle} grain={grain}/>
      </div>

      {/* copy */}
      <div style={{ padding: '34px var(--gutter-screen) 0', flex: 1 }}>
        <div className="overline" style={{ color: vp.accent, marginBottom: 14 }}>{vp.eyebrow}</div>
        <h1 style={{
          font: 'var(--type-display-l)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)',
          marginBottom: 16, textWrap: 'pretty',
        }}>{vp.title}</h1>
        <p style={{ font: 'var(--type-body-l)', color: 'var(--fg-2)', textWrap: 'pretty' }}>{vp.body}</p>
      </div>

      {/* dots + CTA pinned in safe area */}
      <div style={{ padding: '20px var(--gutter-screen) 40px', display: 'flex', flexDirection: 'column', gap: 22, flexShrink: 0 }}>
        <ProgressDots count={VALUE_PROPS.length} index={index}/>
        <Button full variant="primary" onClick={onNext} glow={last}>
          {last ? 'Create your account' : 'Continue'}
        </Button>
      </div>
    </div>
  );
}

// ─── Auth shell — back nav + scroll body + pinned footer ────────────────
function AuthShell({ onBack, children, footer }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ height: 44, flexShrink: 0, display: 'flex', alignItems: 'center', paddingLeft: 12, paddingRight: 12, paddingTop: 52 }}>
        <button onClick={onBack} aria-label="Back" style={{
          background: 'transparent', border: 0, cursor: 'pointer', color: 'var(--fg-1)',
          width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="chevron-left" size={26}/>
        </button>
      </div>
      <div style={{ flex: 1, overflowY: 'auto', WebkitOverflowScrolling: 'touch', padding: '4px var(--gutter-screen) 8px' }}>
        {children}
      </div>
      <div style={{ flexShrink: 0, padding: '12px var(--gutter-screen) 38px' }}>
        {footer}
      </div>
    </div>
  );
}

// ─── Sign up ────────────────────────────────────────────────────────────
function SignUp({ onBack, onSwitch, onDone }) {
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState({});

  const submit = () => {
    const e = {};
    if (!name.trim()) e.name = 'Please enter your name.';
    if (!validateEmail(email)) e.email = 'That email looks off \u2014 let\u2019s try again.';
    if (pw.length < 8) e.pw = 'Passwords need at least 8 characters.';
    setErr(e);
    if (Object.keys(e).length === 0) onDone();
  };

  return (
    <AuthShell onBack={onBack} footer={
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'center' }}>
        <Button full variant="primary" onClick={submit}>Create account</Button>
        <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)' }}>
          Already have an account?{' '}
          <button onClick={onSwitch} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', font: 'var(--type-button)', fontSize: 13, color: 'var(--amber-600)' }}>Sign in</button>
        </div>
      </div>
    }>
      <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 8 }}>Create your account</h1>
      <p style={{ font: 'var(--type-body)', color: 'var(--fg-2)', marginBottom: 24, textWrap: 'pretty' }}>
        One account keeps your screenings, scores, and care in one place.
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
        <SocialButton provider="apple" label="Continue with Apple" onClick={onDone}/>
        <SocialButton provider="google" label="Continue with Google" onClick={onDone}/>
      </div>
      <div style={{ marginBottom: 20 }}><OrDivider label="or"/></div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <TextField label="Full name" name="name" autoComplete="name" placeholder="Chioma Okonkwo"
          value={name} onChange={v => { setName(v); if (err.name) setErr({ ...err, name: undefined }); }} error={err.name}/>
        <TextField label="Email" type="email" name="email" autoComplete="email" placeholder="you@example.com"
          value={email} onChange={v => { setEmail(v); if (err.email) setErr({ ...err, email: undefined }); }} error={err.email}/>
        <TextField label="Password" type="password" name="new-password" autoComplete="new-password" placeholder="At least 8 characters"
          value={pw} onChange={v => { setPw(v); if (err.pw) setErr({ ...err, pw: undefined }); }}
          error={err.pw} hint={!err.pw ? 'Use 8 or more characters.' : undefined} onEnter={submit}/>
      </div>

      <p style={{ font: 'var(--type-caption)', color: 'var(--fg-3)', marginTop: 18, textWrap: 'pretty' }}>
        By continuing you agree to Muna’s{' '}
        <span style={{ color: 'var(--amber-600)', textDecoration: 'underline' }}>Terms</span> and{' '}
        <span style={{ color: 'var(--amber-600)', textDecoration: 'underline' }}>Privacy Policy</span>.
      </p>
    </AuthShell>
  );
}

// ─── Sign in ────────────────────────────────────────────────────────────
function SignIn({ onBack, onSwitch, onDone }) {
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState({});

  const submit = () => {
    const e = {};
    if (!validateEmail(email)) e.email = 'That email looks off \u2014 let\u2019s try again.';
    if (!pw) e.pw = 'Enter your password to continue.';
    setErr(e);
    if (Object.keys(e).length === 0) onDone();
  };

  return (
    <AuthShell onBack={onBack} footer={
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'center' }}>
        <Button full variant="primary" onClick={submit}>Sign in</Button>
        <div style={{ font: 'var(--type-body-s)', color: 'var(--fg-3)' }}>
          New to Muna?{' '}
          <button onClick={onSwitch} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', font: 'var(--type-button)', fontSize: 13, color: 'var(--amber-600)' }}>Create an account</button>
        </div>
      </div>
    }>
      <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 8 }}>Welcome back</h1>
      <p style={{ font: 'var(--type-body)', color: 'var(--fg-2)', marginBottom: 24, textWrap: 'pretty' }}>
        Pick up where you left off.
      </p>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 18 }}>
        <SocialButton provider="apple" label="Continue with Apple" onClick={onDone}/>
        <SocialButton provider="google" label="Continue with Google" onClick={onDone}/>
      </div>
      <div style={{ marginBottom: 20 }}><OrDivider label="or"/></div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <TextField label="Email" type="email" name="email" autoComplete="email" placeholder="you@example.com"
          value={email} onChange={v => { setEmail(v); if (err.email) setErr({ ...err, email: undefined }); }} error={err.email}/>
        <TextField label="Password" type="password" name="current-password" autoComplete="current-password" placeholder="Your password"
          value={pw} onChange={v => { setPw(v); if (err.pw) setErr({ ...err, pw: undefined }); }} error={err.pw} onEnter={submit}
          trailing={
            <button onClick={() => {}} style={{ background: 'none', border: 0, padding: 0, cursor: 'pointer', font: 'var(--type-label)', color: 'var(--amber-600)' }}>Forgot password?</button>
          }/>
      </div>
    </AuthShell>
  );
}

// ─── Confirmation ───────────────────────────────────────────────────────
function Done({ onRestart }) {
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => { const r = setTimeout(() => setShown(true), 30); return () => clearTimeout(r); }, []);
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 var(--gutter-screen)', textAlign: 'center' }}>
        <div style={{
          width: 96, height: 96, borderRadius: '50%', background: 'var(--sage-50)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--sage-600)',
          marginBottom: 28, transform: shown ? 'scale(1)' : 'scale(0.9)', opacity: shown ? 1 : 0,
          transition: 'transform var(--dur-reveal) var(--ease-out), opacity var(--dur-reveal) var(--ease-out)',
        }}>
          <Icon name="check" size={44} strokeWidth={2.25}/>
        </div>
        <h1 style={{ font: 'var(--type-display-m)', color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', marginBottom: 12 }}>You’re all set</h1>
        <p style={{ font: 'var(--type-body-l)', color: 'var(--fg-2)', maxWidth: 300, textWrap: 'pretty' }}>
          Your account is ready. Next comes your five-minute screening — four photos and a few short questions.
        </p>
      </div>
      <div style={{ padding: '12px var(--gutter-screen) 40px', flexShrink: 0 }}>
        <Button full variant="primary" glow rightIcon="arrow-right" onClick={onRestart}>Start screening</Button>
      </div>
    </div>
  );
}

// ─── Transition stage ───────────────────────────────────────────────────
function Stage({ activeKey, direction, render }) {
  const [items, setItems] = React.useState([{ key: activeKey, phase: 'idle' }]);
  const prev = React.useRef(activeKey);
  React.useEffect(() => {
    if (activeKey === prev.current) return;
    const from = prev.current;
    prev.current = activeKey;
    setItems([{ key: from, phase: 'leaving' }, { key: activeKey, phase: 'entering' }]);
    const t = setTimeout(() => setItems([{ key: activeKey, phase: 'idle' }]), 240);
    return () => clearTimeout(t);
  }, [activeKey]);

  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      {items.map((it) => {
        const fwd = direction >= 0;
        let animation = 'none';
        if (it.phase === 'entering') animation = `${fwd ? 'mh-enter-fwd' : 'mh-enter-back'} var(--dur-base) var(--ease-out) both`;
        if (it.phase === 'leaving') animation = `${fwd ? 'mh-leave-fwd' : 'mh-leave-back'} var(--dur-base) var(--ease-out) both`;
        return (
          <div key={it.key} style={{
            position: 'absolute', inset: 0, animation,
            zIndex: it.phase === 'leaving' ? 1 : 2,
          }}>
            {render(it.key)}
          </div>
        );
      })}
    </div>
  );
}

window.MunaFlow = { ORDER, VALUE_PROPS, Splash, ValueProp, SignUp, SignIn, Done, Stage, DemoSheet };
