// signin/SignIn.jsx
// Sign-in flow for the Ordentus iOS app. The server is always ordent.us, so
// there is no server-URL step — the user signs straight in. Brand voice:
// quiet, plain, declarative — sentence case, no marketing exuberance,
// em-dashes for pivots.
//
// Screens:
//   Welcome           — splash (bedtime gradient), brand mark, CTA
//   Credentials       — username + password (keyboard up)
//   SigningIn         — credentials, primary CTA in busy state
//   CredentialsError  — wrong password
//   Tour1, Tour2, Tour3 — paginated first-run tour, 3 panels
//
// Each accepts dark:boolean. Renders inside an IOSDevice frame.

// ────────────────────────────────────────────────────────────
// 1. WELCOME
// ────────────────────────────────────────────────────────────
function Welcome({ dark = false }) {
  return (
    <FrameScreen dark={dark}>
      <div className="si-canvas">
        <div className="si-splash"/>
        {/* content */}
        <div style={{ position: 'relative', zIndex: 1, padding: '120px 28px 0', color: '#fff', flex: 1, display: 'flex', flexDirection: 'column' }}>
          <div className="lockup">
            <svg width="46" height="46" viewBox="0 0 24 24" fill="none">
              <rect x="3.2" y="4.5" width="17.6" height="16.3" rx="3" stroke="#1B1464" strokeWidth="2.2"/>
              <path d="M3.2 9.2h17.6M8 2.7v3.6M16 2.7v3.6" stroke="#1B1464" strokeWidth="2.2" strokeLinecap="round"/>
              <rect x="6" y="11.5" width="3" height="3" rx="0.6" fill="#1B1464"/>
            </svg>
          </div>
          <div style={{ marginTop: 28 }}>
            <div className="cp" style={{ color: 'rgba(255,255,255,.5)', textTransform: 'uppercase', letterSpacing: 1, fontWeight: 600 }}>Ordentus</div>
            <div className="lt" style={{ color: '#fff', marginTop: 10, letterSpacing: -0.6, fontWeight: 600, fontSize: 36, lineHeight: 1.08 }}>
              One page for your life.
            </div>
            <div className="bd" style={{ color: 'rgba(255,255,255,.7)', marginTop: 14, lineHeight: 1.45 }}>
              Your calendars and your body, on the same page, every morning.
            </div>
          </div>

          {/* simple value props — three plain rows */}
          <div style={{ marginTop: 36, display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              { ic: 'calendar', t: 'Every feed, in one grid.' },
              { ic: 'heart',    t: 'Tonight\u2019s bedtime, worked back from tomorrow.' },
              { ic: 'lock',     t: 'Private by default \u2014 only you can see it.' },
            ].map((r, i) => (
              <div key={i} className="row" style={{ gap: 14 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 9,
                  background: 'rgba(255,255,255,0.10)',
                  border: '1px solid rgba(255,255,255,0.16)',
                  display: 'grid', placeItems: 'center',
                  color: '#fff', flexShrink: 0,
                }}>
                  <Icon name={r.ic} size={16} stroke={2.2}/>
                </div>
                <div className="bd" style={{ color: 'rgba(255,255,255,.85)', lineHeight: 1.35 }}>{r.t}</div>
              </div>
            ))}
          </div>

          <div style={{ flex: 1 }}/>

          <div style={{ paddingBottom: 40, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <button className="si-cta" style={{ background: '#fff', color: '#1B1464' }}>
              Sign in
            </button>
          </div>
        </div>
      </div>
    </FrameScreen>
  );
}
window.Welcome = Welcome;

// ────────────────────────────────────────────────────────────
// 2. CREDENTIALS — username + password (server is always ordent.us)
// ────────────────────────────────────────────────────────────
function Credentials({ dark = false, state = 'idle' /* idle|busy|error */ }) {
  const isError = state === 'error';
  const busy = state === 'busy';

  return (
    <IOSDevice width={402} height={874} dark={dark} keyboard>
      <div className="io" data-theme={dark ? 'dark' : 'light'} style={{ minHeight: '100%', position: 'relative' }}>
        <div style={{ padding: '56px 12px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ color: 'var(--io-blue)', fontSize: 17, letterSpacing: -0.4, display: 'flex', alignItems: 'center', gap: 2 }}>
            <Icon name="chevron-left" size={22} stroke={2.6}/>
            <span style={{ marginLeft: -2 }}>Back</span>
          </div>
          <div style={{ width: 60 }}/>
        </div>

        <div style={{ padding: '8px 24px 18px' }}>
          <div className="eyebrow" style={{ color: 'var(--io-label-tertiary)' }}>Welcome back</div>
          <div className="t1" style={{ marginTop: 6, letterSpacing: -0.5 }}>Sign in.</div>
          <div className="row" style={{ gap: 6, marginTop: 8 }}>
            <span style={{
              width: 8, height: 8, borderRadius: 50, background: 'var(--io-green)', flexShrink: 0,
            }}/>
            <span className="fn" style={{ color: 'var(--io-label-secondary)' }}>
              <span style={{ color: 'var(--io-label)', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace' }}>ordent.us</span>
            </span>
          </div>
        </div>

        <div style={{ padding: '4px 16px 0' }}>
          <div className="field-group">
            <div className={'field ' + (isError ? '' : 'focused')}>
              <span className="label">Username</span>
              <div className="input">
                <span className="typed">lukas</span>
                {!isError && <span className="caret"/>}
              </div>
            </div>
            <div className={'field ' + (isError ? 'error' : '')}>
              <span className="label">Password</span>
              <div className="input">
                <span className="typed" style={{ letterSpacing: 2, color: 'var(--io-label)' }}>••••••••</span>
                {isError && <span className="caret"/>}
              </div>
              <span className="right-ic" style={{ color: isError ? 'var(--io-red)' : 'var(--io-label-tertiary)' }}>
                <Icon name={isError ? 'alert' : 'lock'} size={16} stroke={2.2}/>
              </span>
            </div>
          </div>
          {isError ? (
            <div className="hintrow err">
              <Icon name="alert" size={14} stroke={2.4}/>
              That password isn't right. Try again — three left before lockout.
            </div>
          ) : (
            <div className="between" style={{ paddingTop: 8 }}>
              <span className="fn" style={{ color: 'var(--io-blue)', fontWeight: 500 }}>Forgot password?</span>
              <span className="fn" style={{ color: 'var(--io-label-tertiary)' }}>Session lasts 30 days</span>
            </div>
          )}
        </div>

        <div style={{ flex: 1 }}/>

        <div style={{ padding: '20px 16px 16px' }}>
          <button className={'si-cta' + (busy ? ' busy' : '')} disabled={busy}>
            {busy ? <><span className="spinner"/> Signing in…</> : 'Sign in'}
          </button>
        </div>
      </div>
    </IOSDevice>
  );
}
window.Credentials = Credentials;

// ────────────────────────────────────────────────────────────
// 3. FIRST-RUN TOUR — three paginated panels
// ────────────────────────────────────────────────────────────
function TourPanel({ dark = false, panel = 1 }) {
  const panels = [
    {
      key: 'cal', dot: 0,
      eyebrow: 'Calendar',
      title: 'Every feed, in one grid.',
      body: 'Subscribed iCal, manual events, your university timetable — Ordentus merges them, deduplicates, and color-codes by source.',
      art: <PreviewCalendar dark={dark}/>,
    },
    {
      key: 'health', dot: 1,
      eyebrow: 'Health',
      title: 'Tonight\u2019s bedtime — backed out from tomorrow.',
      body: 'Connect Apple Health and Ordentus reads sleep, heart rate and activity in the background. The bedtime number lives at the top of the page every morning.',
      art: <PreviewHealth dark={dark}/>,
    },
    {
      key: 'shared', dot: 2,
      eyebrow: 'Share',
      title: 'Share a slice, without the noise.',
      body: 'Generate a link that exposes one feed or one date range. Revoke it any time. Detail-level visibility is up to you.',
      art: <PreviewShare dark={dark}/>,
    },
  ];
  const p = panels[panel - 1];
  return (
    <FrameScreen dark={dark}>
      <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
        {/* Skip */}
        <div style={{ padding: '56px 20px 0', display: 'flex', justifyContent: 'flex-end' }}>
          <span className="bd" style={{ color: 'var(--io-blue)', fontWeight: 500 }}>Skip</span>
        </div>

        {/* Art */}
        <div style={{ padding: '12px 24px 0', flex: 1, display: 'grid', placeItems: 'center' }}>
          {p.art}
        </div>

        {/* Copy */}
        <div style={{ padding: '12px 28px 8px' }}>
          <div className="eyebrow" style={{ color: 'var(--io-red)' }}>{p.eyebrow}</div>
          <div className="t1" style={{ marginTop: 8, letterSpacing: -0.5, textWrap: 'balance' }}>{p.title}</div>
          <div className="bd" style={{ color: 'var(--io-label-secondary)', marginTop: 10, lineHeight: 1.45 }}>{p.body}</div>
        </div>

        {/* Dots + CTAs */}
        <div style={{ padding: '20px 16px 40px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div className="dots-row">
            {[0,1,2].map(i => <i key={i} className={i === p.dot ? 'on' : ''}/>)}
          </div>
          <button className="si-cta" style={{ width: 'auto', padding: '12px 22px' }}>
            {panel < 3 ? 'Continue' : 'Get started'}
            <Icon name="arrow-right" size={16} stroke={2.4}/>
          </button>
        </div>
      </div>
    </FrameScreen>
  );
}
window.TourPanel = TourPanel;

// ── Preview illustrations (data-only, no SVG handiwork) ────────────
function PreviewCalendar({ dark }) {
  // A miniature day-view artboard built from real chips.
  return (
    <div style={{
      width: '100%', maxWidth: 340,
      background: 'var(--io-bg-elev)',
      borderRadius: 22, padding: 14,
      border: '1px solid var(--io-separator)',
      position: 'relative', overflow: 'hidden',
    }}>
      <div className="between">
        <div>
          <div className="cp" style={{ color: 'var(--io-red)', textTransform: 'uppercase', letterSpacing: 0.7, fontWeight: 600 }}>Today</div>
          <div className="hd" style={{ marginTop: 2 }}>Sunday <span data-num>16</span></div>
        </div>
        <div className="row" style={{ gap: 6 }}>
          <span style={{ width: 8, height: 8, borderRadius: 50, background: FEED_HEX.work }}/>
          <span style={{ width: 8, height: 8, borderRadius: 50, background: FEED_HEX.uni }}/>
          <span style={{ width: 8, height: 8, borderRadius: 50, background: FEED_HEX.gym }}/>
          <span style={{ width: 8, height: 8, borderRadius: 50, background: FEED_HEX.bedtime }}/>
        </div>
      </div>
      <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {[
          { feed: 'work',     t: 'Morning shift',  time: '7:15 AM' },
          { feed: 'work',     t: 'Standup',        time: '10:00 AM' },
          { feed: 'uni',      t: 'Algorithms',     time: '2:30 PM' },
          { feed: 'gym',      t: 'Climbing',       time: '5:00 PM' },
          { feed: 'bedtime',  t: '🌙 Wind down',   time: '10:00 PM' },
        ].map((e, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 10px',
            borderRadius: 8,
            background: `color-mix(in oklab, ${FEED_HEX[e.feed]} 8%, var(--io-bg-elev))`,
            borderLeft: `3px solid ${FEED_HEX[e.feed]}`,
          }}>
            <div className="ca" style={{ flex: 1, fontWeight: 500, fontSize: 13 }}>{e.t}</div>
            <div className="cp" style={{ color: 'var(--io-label-secondary)' }} data-num>{e.time}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PreviewHealth({ dark }) {
  return (
    <div style={{ width: '100%', maxWidth: 340, display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{
        borderRadius: 22, padding: '20px 22px',
        background: 'var(--io-grad-bedtime-deep)',
        color: '#fff', position: 'relative', overflow: 'hidden',
      }}>
        <div className="eyebrow" style={{ color: 'rgba(255,255,255,.65)' }}>Tonight's bedtime</div>
        <div className="m-hero" data-num style={{ color: '#fff', marginTop: 8, fontSize: 56, letterSpacing: -2 }}>
          10:30 <span style={{ fontSize: 20, opacity: 0.6 }}>PM</span>
        </div>
        <div className="fn" style={{ color: 'rgba(255,255,255,.65)', marginTop: 4 }}>Wake 6:15 AM · 8h goal</div>
      </div>
      <div className="row" style={{ gap: 8 }}>
        <div style={{ flex: 1, background: 'var(--io-bg-elev)', borderRadius: 14, padding: 12, border: '1px solid var(--io-separator)' }}>
          <div className="cp" style={{ color: 'var(--io-label-secondary)', textTransform:'uppercase', letterSpacing: 0.6, fontWeight: 600 }}>Last night</div>
          <div className="m-md" data-num style={{ marginTop: 6, fontSize: 28 }}>6.2<span className="m-unit" style={{ fontSize: 13 }}>h</span></div>
        </div>
        <div style={{ flex: 1, background: 'var(--io-bg-elev)', borderRadius: 14, padding: 12, border: '1px solid var(--io-separator)' }}>
          <div className="cp" style={{ color: 'var(--io-label-secondary)', textTransform:'uppercase', letterSpacing: 0.6, fontWeight: 600 }}>Debt 14d</div>
          <div className="m-md" data-num style={{ marginTop: 6, fontSize: 28, color: 'var(--io-orange)' }}>4.5<span className="m-unit" style={{ fontSize: 13 }}>h</span></div>
        </div>
      </div>
    </div>
  );
}

function PreviewShare({ dark }) {
  return (
    <div style={{ width: '100%', maxWidth: 340, display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{
        background: 'var(--io-bg-elev)', border: '1px solid var(--io-separator)',
        borderRadius: 18, padding: '16px 18px',
      }}>
        <div className="between" style={{ marginBottom: 8 }}>
          <div className="hd" style={{ fontSize: 15 }}>Work · this week</div>
          <span className="pill low">Active</span>
        </div>
        <div style={{
          padding: '8px 10px', borderRadius: 8,
          background: 'var(--io-fill-tertiary)',
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
          fontSize: 12, color: 'var(--io-label-secondary)',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>portal.lukas.dev/s/aB7r2…</div>
        <div className="between" style={{ marginTop: 10 }}>
          <span className="fn" style={{ color: 'var(--io-label-secondary)' }}>Expires Mar 23 · 7 days</span>
          <span className="fn" style={{ color: 'var(--io-red)', fontWeight: 500 }}>Revoke</span>
        </div>
      </div>
      <div style={{
        background: 'var(--io-bg-elev)', border: '1px solid var(--io-separator)',
        borderRadius: 18, padding: '14px 18px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{
          width: 28, height: 28, borderRadius: 8,
          background: 'var(--io-blue)', color: '#fff',
          display: 'grid', placeItems: 'center',
        }}><Icon name="plus" size={16} stroke={2.4}/></div>
        <div className="bd" style={{ color: 'var(--io-blue)', fontWeight: 500 }}>New share link</div>
      </div>
    </div>
  );
}
