// Loop — Onboarding screens. 5 steps that resolve into Home.
// Exports (window): Onboarding

const { useEffect: oEffect, useState: oState, useRef: oRef } = React;

function OnbDot({ T, on }) {
  return <span style={{
    width: 6, height: 6, borderRadius: 6,
    background: on ? T.accent : T.hairline,
    transition: 'background 200ms',
  }} />;
}

function OnbButton({ T, onClick, children, primary = true, style }) {
  return (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer', textAlign: 'center',
      padding: '15px 20px', borderRadius: 16, width: '100%', boxSizing: 'border-box',
      background: primary ? T.accent : 'transparent',
      color: primary ? '#fff' : T.accent,
      fontFamily: T.fontSans, fontSize: 17, fontWeight: 590, letterSpacing: -0.2,
      boxShadow: primary ? `0 6px 18px ${T.accent}38` : 'none',
      ...style,
    }}>{children}</button>
  );
}

// Step 0 — Welcome with breathing logo
function Step0({ T, next }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '40px 28px 40px' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start' }}>
        <div style={{ marginBottom: 36, position: 'relative', width: 96, height: 96 }}>
          <div style={{
            position: 'absolute', inset: 0, borderRadius: '50%',
            background: `radial-gradient(circle, ${T.accent}30 0%, transparent 70%)`,
            animation: 'loop-breathe 5s ease-in-out infinite',
          }}/>
          <svg width="96" height="96" viewBox="0 0 96 96" style={{ position: 'relative' }}>
            <circle cx="48" cy="48" r="34" fill="none" stroke={T.accent} strokeWidth="1.6" opacity="0.35"/>
            <circle cx="48" cy="48" r="22" fill="none" stroke={T.accent} strokeWidth="1.6" opacity="0.7"/>
            <circle cx="48" cy="48" r="8"  fill={T.accent}/>
          </svg>
        </div>
        <div style={{ fontFamily: T.fontSerif, fontSize: 44, lineHeight: 1.05, color: T.text, letterSpacing: -1.2, fontWeight: 400, marginBottom: 16 }}>
          Welcome to Loop.
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 18, lineHeight: 1.4, color: T.textSub, maxWidth: 300 }}>
          A calm assistant for the small communication loops that quietly drain your day.
        </div>
      </div>
      <OnbButton T={T} onClick={next}>Begin</OnbButton>
      <div style={{ textAlign: 'center', marginTop: 14, fontFamily: T.fontSans, fontSize: 13, color: T.textMuted }}>
        Takes about 90 seconds
      </div>
    </div>
  );
}

// Step 1 — The idea
function Step1({ T, next, back }) {
  const bullets = [
    { n: '01', t: 'Find the small loops', s: 'Replies, thanks, scheduling, quick acknowledgements.' },
    { n: '02', t: 'Suggest a calm response', s: 'Drafted in your voice. You approve before anything sends.' },
    { n: '03', t: 'Clear them in minutes',   s: 'Most take less than two minutes each.' },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '8px 28px 40px' }}>
      <BackHeader T={T} title="" onBack={back} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={{ fontFamily: T.fontSerif, fontSize: 34, lineHeight: 1.1, color: T.text, letterSpacing: -0.8, marginBottom: 8 }}>
          The two-minute rule, automated.
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 16, color: T.textSub, marginBottom: 30 }}>
          Here's what Loop does, three ways.
        </div>
        {bullets.map((b, i) => (
          <div key={i} style={{ display: 'flex', gap: 16, marginBottom: 22 }}>
            <div style={{ fontFamily: T.fontSerif, fontSize: 13, color: T.accent, paddingTop: 4, letterSpacing: 1, fontWeight: 500 }}>
              {b.n}
            </div>
            <div>
              <div style={{ fontFamily: T.fontSans, fontSize: 17, fontWeight: 570, color: T.text, marginBottom: 3 }}>{b.t}</div>
              <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textSub, lineHeight: 1.45 }}>{b.s}</div>
            </div>
          </div>
        ))}
      </div>
      <OnbButton T={T} onClick={next}>Continue</OnbButton>
    </div>
  );
}

// Step 2 — Connect
function Step2({ T, next, back }) {
  const [picked, setPicked] = oState(null);
  const provs = [
    { id: 'google', name: 'Google Workspace', sub: 'Gmail · Calendar · Contacts', glyph: <svg viewBox="0 0 24 24" width="22" height="22"><path d="M12 5v6h7c-0.5 3-3 5-7 5a6 6 0 1 1 4-10.5l3-3A11 11 0 1 0 23 11h-11z" fill={T.text}/></svg> },
    { id: 'ms',     name: 'Microsoft 365',    sub: 'Outlook · Calendar · Teams',   glyph: <svg viewBox="0 0 24 24" width="22" height="22"><rect x="3" y="3" width="8" height="8" fill={T.accent}/><rect x="13" y="3" width="8" height="8" fill={T.text} opacity="0.7"/><rect x="3" y="13" width="8" height="8" fill={T.text} opacity="0.5"/><rect x="13" y="13" width="8" height="8" fill={T.text} opacity="0.3"/></svg> },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '8px 28px 40px' }}>
      <BackHeader T={T} title="" onBack={back} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={{ fontFamily: T.fontSerif, fontSize: 34, lineHeight: 1.1, color: T.text, letterSpacing: -0.8, marginBottom: 8 }}>
          Connect a mailbox.
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 16, color: T.textSub, marginBottom: 28, lineHeight: 1.45 }}>
          Loop reads message metadata to identify clearable loops. Your mail never leaves Apple's servers.
        </div>
        {provs.map(p => (
          <button key={p.id} onClick={() => setPicked(p.id)} style={{
            all: 'unset', cursor: 'pointer', marginBottom: 12,
            background: T.card, border: `1px solid ${picked === p.id ? T.accent : T.cardEdge}`,
            borderRadius: 18, padding: '16px 18px',
            display: 'flex', alignItems: 'center', gap: 14,
            boxShadow: picked === p.id ? `0 0 0 3px ${T.accent}22` : 'none',
            transition: 'all 180ms',
          }}>
            <div style={{ width: 40, height: 40, borderRadius: 10, background: T.bg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{p.glyph}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: T.fontSans, fontSize: 16, fontWeight: 570, color: T.text }}>{p.name}</div>
              <div style={{ fontFamily: T.fontSans, fontSize: 13, color: T.textSub }}>{p.sub}</div>
            </div>
            {picked === p.id && <KindGlyph kind="approve" color={T.accent} size={18} />}
          </button>
        ))}
      </div>
      <OnbButton T={T} onClick={next}>{picked ? 'Continue' : 'Skip for now'}</OnbButton>
    </div>
  );
}

// Step 3 — Trust settings
function Step3({ T, next, back }) {
  const [autoSend, setAutoSend] = oState(false);
  const [scanCal, setScanCal] = oState(true);
  const [tone, setTone] = oState('match');

  const Toggle = ({ on, onClick }) => (
    <button onClick={onClick} style={{
      all: 'unset', cursor: 'pointer', width: 50, height: 30, borderRadius: 30,
      background: on ? T.accent : T.hairline, position: 'relative',
      transition: 'background 200ms', flexShrink: 0,
    }}>
      <div style={{
        position: 'absolute', top: 2, left: on ? 22 : 2,
        width: 26, height: 26, borderRadius: 26, background: '#fff',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
        transition: 'left 220ms cubic-bezier(.2,.8,.2,1)',
      }}/>
    </button>
  );

  const Row = ({ title, sub, right }) => (
    <div style={{ display: 'flex', alignItems: 'center', padding: '14px 0', gap: 14 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: T.fontSans, fontSize: 16, fontWeight: 540, color: T.text, marginBottom: 2 }}>{title}</div>
        <div style={{ fontFamily: T.fontSans, fontSize: 13, color: T.textSub, lineHeight: 1.4 }}>{sub}</div>
      </div>
      {right}
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '8px 28px 40px' }}>
      <BackHeader T={T} title="" onBack={back} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={{ fontFamily: T.fontSerif, fontSize: 32, lineHeight: 1.1, color: T.text, letterSpacing: -0.7, marginBottom: 6 }}>
          You're in charge.
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 15, color: T.textSub, marginBottom: 18, lineHeight: 1.45 }}>
          These can be changed any time in Settings.
        </div>
        <div style={{
          background: T.card, border: `0.5px solid ${T.cardEdge}`, borderRadius: 18,
          padding: '4px 18px', boxShadow: T.cardShadow,
        }}>
          <Row title="Approve every send" sub="Loop drafts. You read, edit, and send." right={<Toggle on={!autoSend} onClick={() => setAutoSend(!autoSend)} />} />
          <Hairline T={T} />
          <Row title="Use my calendar context" sub="So scheduling suggestions respect your focus blocks." right={<Toggle on={scanCal} onClick={() => setScanCal(!scanCal)} />} />
          <Hairline T={T} />
          <div style={{ padding: '14px 0' }}>
            <div style={{ fontFamily: T.fontSans, fontSize: 16, fontWeight: 540, color: T.text, marginBottom: 8 }}>Drafting voice</div>
            <div style={{ display: 'flex', gap: 6 }}>
              {[['match', 'Match me'], ['warm', 'Warmer'], ['terse', 'Briefer']].map(([k, l]) => (
                <button key={k} onClick={() => setTone(k)} style={{
                  all: 'unset', cursor: 'pointer', flex: 1, textAlign: 'center',
                  padding: '10px 0', borderRadius: 12,
                  background: tone === k ? T.accent : T.bg,
                  color: tone === k ? '#fff' : T.text,
                  fontFamily: T.fontSans, fontSize: 14, fontWeight: 540,
                }}>{l}</button>
              ))}
            </div>
          </div>
        </div>
      </div>
      <OnbButton T={T} onClick={next}>Continue</OnbButton>
    </div>
  );
}

// Step 4 — Scanning animation
function Step4({ T, next, back }) {
  const [progress, setProgress] = oState(0);
  const [phase, setPhase] = oState(0);
  const phases = [
    'Scanning your inbox…',
    'Reading thread context…',
    'Finding low-friction loops…',
    'Drafting suggestions…',
    'Almost there…',
  ];
  oEffect(() => {
    let p = 0;
    const id = setInterval(() => {
      p = Math.min(100, p + 2);
      setProgress(p);
      setPhase(Math.min(4, Math.floor(p / 22)));
      if (p >= 100) { clearInterval(id); setTimeout(next, 700); }
    }, 60);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '40px 28px 40px', position: 'relative', overflow: 'hidden' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', gap: 36 }}>
        {/* concentric rings */}
        <div style={{ position: 'relative', width: 200, height: 200 }}>
          {[0, 1, 2, 3].map(i => (
            <div key={i} style={{
              position: 'absolute', inset: i * 18, borderRadius: '50%',
              border: `1px solid ${T.accent}`,
              opacity: 0.6 - i * 0.12,
              animation: `loop-pulse 2.4s ease-in-out ${i * 0.3}s infinite`,
            }}/>
          ))}
          <div style={{
            position: 'absolute', inset: 80, borderRadius: '50%',
            background: T.accent, boxShadow: `0 0 30px ${T.accent}`,
          }}/>
        </div>
        <div>
          <div style={{ fontFamily: T.fontSerif, fontSize: 26, color: T.text, letterSpacing: -0.5, marginBottom: 10, fontWeight: 400 }}>
            {phases[phase]}
          </div>
          <div style={{ fontFamily: T.fontSans, fontSize: 14, color: T.textMuted }}>
            {progress}%
          </div>
        </div>
        <div style={{ width: 200, height: 2, background: T.hairline, borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${progress}%`, background: T.accent, transition: 'width 200ms' }}/>
        </div>
      </div>
    </div>
  );
}

// Step 5 — Reveal
function Step5({ T, next }) {
  const [reveal, setReveal] = oState(false);
  oEffect(() => { const t = setTimeout(() => setReveal(true), 300); return () => clearTimeout(t); }, []);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '40px 28px 40px' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', opacity: reveal ? 1 : 0, transform: reveal ? 'translateY(0)' : 'translateY(12px)', transition: 'all 600ms cubic-bezier(.2,.8,.2,1)' }}>
        <div style={{ fontFamily: T.fontSans, fontSize: 13, fontWeight: 540, color: T.accent, letterSpacing: 1.4, textTransform: 'uppercase', marginBottom: 16 }}>
          Today's Momentum
        </div>
        <div style={{ fontFamily: T.fontSerif, fontSize: 54, lineHeight: 1.05, color: T.text, letterSpacing: -1.4, fontWeight: 400, marginBottom: 14 }}>
          12 quick loops.
        </div>
        <div style={{ fontFamily: T.fontSans, fontSize: 17, color: T.textSub, marginBottom: 30, lineHeight: 1.4 }}>
          About 18 minutes of clearing. Most under two minutes each.
        </div>
        <div style={{ background: T.card, border: `0.5px solid ${T.cardEdge}`, borderRadius: 18, padding: 18, boxShadow: T.cardShadow }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <ShimmerDot T={T} />
            <span style={{ fontFamily: T.fontSans, fontSize: 12, color: T.textSub, fontWeight: 540, letterSpacing: 0.4, textTransform: 'uppercase' }}>Drafted for you</span>
          </div>
          <div style={{ fontFamily: T.fontSerif, fontSize: 18, color: T.text, lineHeight: 1.35 }}>
            Sarah, Marcus, Priya, Leah — all waiting on something small.
          </div>
        </div>
      </div>
      <OnbButton T={T} onClick={next}>Start clearing</OnbButton>
    </div>
  );
}

function Onboarding({ T, onDone, initialStep = 0 }) {
  const [step, setStep] = oState(initialStep);
  const total = 6;
  const next = () => step < total - 1 ? setStep(step + 1) : onDone();
  const back = () => setStep(Math.max(0, step - 1));
  const screens = [Step0, Step1, Step2, Step3, Step4, Step5];
  const Screen = screens[step];

  return (
    <div style={{ position: 'absolute', inset: 0, background: T.bg, display: 'flex', flexDirection: 'column' }}>
      <Screen T={T} next={next} back={back} />
      {step > 0 && step < 4 && (
        <div style={{ position: 'absolute', top: 16, left: 0, right: 0, display: 'flex', justifyContent: 'center', gap: 6, pointerEvents: 'none' }}>
          {Array.from({ length: total - 1 }).map((_, i) => <OnbDot key={i} T={T} on={i === step - 1} />)}
        </div>
      )}
    </div>
  );
}

window.Onboarding = Onboarding;
