// ReturnScribe — onboarding modals: Consent · Background Refresh · Scan progress

// Brand mark used across onboarding (no fake logo art)
function BrandMark({ size = 56, color }) {
  // proportional geometry — matches the canonical 60px mark at any size:
  // radius 10/60, border 2/60, seal dot 12/60 offset -5/60 (center lands on the corner arc)
  const c = color || '#C2451E';
  return (
    <div style={{
      width: size, height: size, borderRadius: size * (10 / 60), flexShrink: 0,
      background: 'transparent',
      border: `${size / 30}px solid ${c}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative',
    }}>
      <span style={{
        fontFamily: '"Instrument Serif", Georgia, serif', fontSize: size * 0.63,
        color: c, lineHeight: 1, fontStyle: 'italic',
      }}>R</span>
      <div style={{
        // seal dot — center pinned to the frame's rounded-corner arc (45° point).
        // NOTE: abs-positioning anchors to the PADDING box (inside the 2px border),
        // so the outer-relative arc offset (−0.0512·size) gains the border width:
        // −(0.0512 + 1/30) · size ≈ −0.0845 · size
        position: 'absolute', right: -size * 0.0845, bottom: -size * 0.0845,
        width: size * 0.2, height: size * 0.2,
        borderRadius: 99, background: c,
      }}></div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 0 · WELCOME / SIGN-UP — first screen on app launch
// ─────────────────────────────────────────────────────────────
function AppleGlyph({ size = 18, color = '#fff' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block' }}>
      <path fill={color} d="M17.05 12.54c-.03-2.4 1.96-3.55 2.05-3.61-1.12-1.63-2.86-1.86-3.47-1.88-1.47-.15-2.88.87-3.63.87-.75 0-1.9-.85-3.13-.83-1.61.02-3.09.94-3.92 2.38-1.67 2.9-.43 7.2 1.2 9.56.8 1.16 1.75 2.46 3 2.41 1.2-.05 1.66-.78 3.12-.78 1.46 0 1.87.78 3.14.76 1.3-.02 2.12-1.18 2.92-2.34.92-1.34 1.3-2.64 1.32-2.71-.03-.01-2.53-.97-2.56-3.83Z"/>
      <path fill={color} d="M14.66 5.04c.66-.8 1.1-1.91.98-3.02-.95.04-2.1.63-2.78 1.43-.61.7-1.14 1.84-1 2.92 1.06.08 2.14-.54 2.8-1.33Z"/>
    </svg>
  );
}

function GoogleGlyph({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block' }}>
      <path fill="#4285F4" d="M23.5 12.27c0-.85-.08-1.66-.22-2.45H12v4.64h6.45a5.52 5.52 0 0 1-2.39 3.62v3h3.87c2.26-2.09 3.57-5.16 3.57-8.81Z"/>
      <path fill="#34A853" d="M12 24c3.24 0 5.96-1.07 7.93-2.91l-3.87-3c-1.07.72-2.45 1.15-4.06 1.15-3.12 0-5.77-2.11-6.71-4.95H1.29v3.1A12 12 0 0 0 12 24Z"/>
      <path fill="#FBBC05" d="M5.29 14.29a7.2 7.2 0 0 1 0-4.58v-3.1H1.29a12 12 0 0 0 0 10.78l4-3.1Z"/>
      <path fill="#EA4335" d="M12 4.76c1.76 0 3.34.6 4.58 1.79l3.44-3.44A11.97 11.97 0 0 0 12 0 12 12 0 0 0 1.29 6.61l4 3.1C6.23 6.87 8.88 4.76 12 4.76Z"/>
    </svg>
  );
}

function MicrosoftGlyph({ size = 17 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 23 23" style={{ display: 'block' }}>
      <rect x="0" y="0" width="10.5" height="10.5" fill="#F25022"/>
      <rect x="12.5" y="0" width="10.5" height="10.5" fill="#7FBA00"/>
      <rect x="0" y="12.5" width="10.5" height="10.5" fill="#00A4EF"/>
      <rect x="12.5" y="12.5" width="10.5" height="10.5" fill="#FFB900"/>
    </svg>
  );
}

function WelcomeScreen({ t, onAuth }) {
  const authBtn = (label, icon, { inverted } = {}) => (
    <PressScale>
      <button onClick={onAuth} style={{
        width: '100%', height: 52, borderRadius: 14, cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        background: inverted ? t.text1 : t.surface1,
        color: inverted ? t.canvas : t.text1,
        border: inverted ? 'none' : `1px solid ${t.borderStrong}`,
        ...applyType(RSType.headline),
      }}>
        {icon}{label}
      </button>
    </PressScale>
  );

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      {/* Masthead — logo pinned to the exact same spot as the consent screen (64/28, size 60) */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '64px 28px 0' }}>
        <BrandMark size={60} color={t.accent}/>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', paddingBottom: 24 }}>
        <div style={{ borderTop: `3px double ${t.text1}`, paddingTop: 18 }}>
          <h1 style={{ margin: 0, color: t.text1, ...applyDisp(RSType.large, { fontSize: 40, lineHeight: 1.06 }) }}>
            Every receipt,<br/>on the record.
          </h1>
          <p style={{ color: t.text2, ...applyType(RSType.callout), margin: '16px 0 0', maxWidth: 320, lineHeight: 1.5 }}>
            Purchases, return windows, refunds, and subscriptions — kept in one running
            ledger, so money stops slipping away.
          </p>
        </div>
        {/* AI feature — the innovation moment */}
        <div style={{ marginTop: 18, borderTop: `1px solid ${t.border}`, paddingTop: 16, display: 'flex', gap: 13, alignItems: 'flex-start' }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10, flexShrink: 0,
            border: `1.5px solid ${t.accent}`, background: t.accentDim,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon name="sparkles" size={18} color={t.accent}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ color: t.accent, ...applyMono(RSType.caption, { letterSpacing: 1.6, fontWeight: 600 }), textTransform: 'uppercase' }}>
              ReturnScribe Intelligence
            </div>
            <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 4, lineHeight: 1.5 }}>
              Purpose-built AI reads every receipt like a meticulous bookkeeper — stitching together
              merchants, amounts, items, and deadlines from messy emails, automatically.
            </div>
          </div>
        </div>
        </div>
      </div>

      {/* Auth stack */}
      <div style={{ padding: '14px 24px 30px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {authBtn('Continue with Apple', <AppleGlyph size={19} color={t.canvas}/>, { inverted: true })}
        {authBtn('Continue with Google', <GoogleGlyph size={18}/>)}
        {authBtn('Continue with Outlook', <MicrosoftGlyph size={17}/>)}
        {authBtn('Continue with Email', <Icon name="envelope" size={18} color={t.text1}/>)}
        <p style={{ color: t.text3, ...applyType(RSType.caption), textAlign: 'center', margin: '8px 0 0', lineHeight: 1.5 }}>
          Already have an account? Signing in with the same method restores it.
        </p>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 1 · CONSENT — final step before account creation
// ─────────────────────────────────────────────────────────────
function ConsentScreen({ t, onContinue }) {
  const link = { color: t.accent, fontWeight: 600, textDecoration: 'none', cursor: 'pointer' };
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: '64px 28px 16px', display: 'flex', flexDirection: 'column' }}>
        <BrandMark size={60} color={t.accent}/>
        <h1 style={{ margin: '28px 0 0', color: t.text1, ...applyType(RSType.large), fontSize: 30 }}>
          Before you start
        </h1>
        <p style={{ color: t.text2, ...applyType(RSType.callout), margin: '14px 0 0', lineHeight: 1.5 }}>
          ReturnScribe uses AI to read your receipt emails and pull out purchase details.
          Some receipt content is processed by a third-party AI service to do this.{' '}
          <span style={link}>Learn more</span> in our Privacy Policy.
        </p>

        {/* What it does — honest, scannable */}
        <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 16 }}>
          {[
            { icon: 'envelope', title: 'Read-only access', sub: 'We can never send, move, or delete your email.' },
            { icon: 'shield',   title: 'Private by design', sub: 'Receipt data is never sold or used for ads.' },
            { icon: 'lock',     title: 'Encrypted in transit & at rest', sub: 'Export or delete your data anytime.' },
          ].map((r, i) => (
            <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
              <div style={{
                width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                background: t.accentDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name={r.icon} size={19} color={t.accent}/>
              </div>
              <div>
                <div style={{ color: t.text1, ...applyType(RSType.headline) }}>{r.title}</div>
                <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 2 }}>{r.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Sticky footer — legal line directly above the single button */}
      <div style={{ padding: '14px 24px 28px', borderTop: `0.5px solid ${t.border}`, background: t.canvas }}>
        <p style={{ color: t.text2, ...applyType(RSType.footnote), textAlign: 'center', margin: '0 0 14px', lineHeight: 1.45 }}>
          By tapping Continue, you agree to our <span style={link}>Terms of Use</span>{' '}
          (including the Arbitration Agreement) and <span style={link}>Privacy Policy</span>.
        </p>
        <PressScale>
          <Button t={t} kind="primary" onClick={onContinue}>Continue</Button>
        </PressScale>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 2 · CONNECT MAILBOX — must precede the scan (it's what gets scanned)
// ─────────────────────────────────────────────────────────────
function MailboxConnectScreen({ t, onContinue }) {
  const [connected, setConnected] = React.useState([]);
  const providers = [
    { id: 'gmail',   name: 'Gmail',   addr: 'dan@reyes.example' },
    { id: 'outlook', name: 'Outlook', addr: 'daniel.work@acme.example' },
  ];
  const toggle = (id) => setConnected(c => c.includes(id) ? c : [...c, id]);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '0 28px', textAlign: 'center' }}>
        <div style={{
          width: 76, height: 76, borderRadius: 22,
          background: t.accentDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="envelope" size={36} color={t.accent}/>
        </div>
        <h1 style={{ margin: '24px 0 0', color: t.text1, ...applyType(RSType.title1), fontSize: 28 }}>
          Connect a mailbox
        </h1>
        <p style={{ color: t.text2, ...applyType(RSType.callout), margin: '12px 0 0', maxWidth: 310, lineHeight: 1.5 }}>
          Pick where ReturnScribe should look. Connect at least one mailbox so your first
          scan has something to read — you can add more later in Settings.
        </p>

        <div style={{ marginTop: 28, width: '100%', maxWidth: 320, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {providers.map(pr => {
            const isOn = connected.includes(pr.id);
            return (
              <PressScale key={pr.id}>
                <button onClick={() => toggle(pr.id)} style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 12,
                  padding: '14px 16px', borderRadius: 14, cursor: 'pointer', textAlign: 'left',
                  background: t.surface1,
                  border: isOn ? `1.5px solid ${t.success}` : `1px solid ${t.borderStrong}`,
                }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                    background: isOn ? t.success + '1F' : t.chip,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <Icon name={isOn ? 'check' : 'envelope'} size={18} color={isOn ? t.success : t.text2} weight={isOn ? 2.4 : 1.8}/>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ color: t.text1, ...applyType(RSType.headline) }}>{pr.name}</div>
                    <div style={{ color: t.text2, ...applyType(RSType.footnote), marginTop: 1 }}>
                      {isOn ? pr.addr : 'Sign in with ' + pr.name}
                    </div>
                  </div>
                  {!isOn && <Icon name="chevron.right" size={14} color={t.text3} weight={2.2}/>}
                </button>
              </PressScale>
            );
          })}
        </div>
      </div>

      <div style={{ padding: '14px 24px 28px' }}>
        <PressScale>
          <Button t={t} kind="primary" onClick={() => connected.length > 0 && onContinue(connected)}
            style={{ opacity: connected.length > 0 ? 1 : 0.4, cursor: connected.length > 0 ? 'pointer' : 'default' }}>
            {connected.length > 1 ? 'Continue with 2 mailboxes' : 'Continue'}
          </Button>
        </PressScale>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 3 · BACKGROUND APP REFRESH — honest ask, no time estimates
// ─────────────────────────────────────────────────────────────
function BackgroundRefreshAsk({ t, onAllow, onSkip }) {
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, overflowY: 'auto', padding: '72px 28px 16px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
        <div style={{
          width: 76, height: 76, borderRadius: 22,
          background: t.accentDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="arrow.triangle.2" size={38} color={t.accent}/>
        </div>
        <h1 style={{ margin: '26px 0 0', color: t.text1, ...applyType(RSType.large), fontSize: 28 }}>
          Find new receipts on their own
        </h1>
        <p style={{ color: t.text2, ...applyType(RSType.callout), margin: '14px 0 0', maxWidth: 320, lineHeight: 1.5 }}>
          With Background App Refresh on, ReturnScribe can check for new receipts while you’re not
          using the app. iOS decides when this runs based on your usage and battery — it may not be
          immediate, and you can change this anytime in Settings.
        </p>
      </div>
      <div style={{ padding: '14px 24px 28px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        <PressScale>
          <Button t={t} kind="primary" onClick={onAllow}>Turn on Background Refresh</Button>
        </PressScale>
        <button onClick={onSkip} style={{
          background: 'none', border: 'none', cursor: 'pointer', color: t.text2,
          ...applyType(RSType.headline), padding: '10px', fontWeight: 500,
        }}>Not now</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 4 · SCAN PROGRESS — foreground bar + "we'll notify you" backgrounded state
// ─────────────────────────────────────────────────────────────
function ScanProgressScreen({ t, onDone }) {
  const sources = ['dan@reyes.example', 'daniel.work@acme.example'];
  const merchants = ['Apple', 'Patagonia', 'Best Buy', 'Allbirds', 'Uniqlo', 'Sephora', 'REI', 'Bose', 'Chewy', 'Amazon'];
  const [pct, setPct] = React.useState(0);
  const [found, setFound] = React.useState(0);
  const [mi, setMi] = React.useState(0);
  const [backgrounded, setBackgrounded] = React.useState(false);
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (done) return;
    const id = setInterval(() => {
      setPct(p => {
        const np = Math.min(100, p + (backgrounded ? 3 : 7));
        if (np >= 100) { setDone(true); }
        return np;
      });
    }, backgrounded ? 360 : 260);
    return () => clearInterval(id);
  }, [backgrounded, done]);

  React.useEffect(() => {
    setFound(Math.round((pct / 100) * 84));
    setMi(Math.min(merchants.length - 1, Math.floor((pct / 100) * merchants.length)));
  }, [pct]);

  // Backgrounded confirmation state
  if (backgrounded && !done) {
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 32px' }}>
        <div style={{
          width: 80, height: 80, borderRadius: 24, background: t.accentDim,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Icon name="bell" size={38} color={t.accent}/>
        </div>
        <h1 style={{ margin: '26px 0 0', color: t.text1, ...applyType(RSType.title1), fontSize: 26 }}>
          Scanning in the background
        </h1>
        <p style={{ color: t.text2, ...applyType(RSType.callout), margin: '12px 0 0', maxWidth: 300, lineHeight: 1.5 }}>
          You can start using ReturnScribe now — we’ll send a notification the moment your receipts are ready.
        </p>
        <div style={{ marginTop: 28, width: '100%', maxWidth: 280 }}>
          <ScanProgressBar t={t} pct={pct} color={t.accent}/>
          <div style={{ color: t.text3, ...applyType(RSType.footnote), marginTop: 10, ...RSTabular }}>
            {found} receipts found so far
          </div>
        </div>
        <div style={{ marginTop: 30, width: '100%', maxWidth: 320 }}>
          <PressScale>
            <Button t={t} kind="primary" onClick={onDone}>Continue to ReturnScribe</Button>
          </PressScale>
        </div>
        <button onClick={() => setBackgrounded(false)} style={{
          marginTop: 14, background: 'none', border: 'none', cursor: 'pointer',
          color: t.text2, ...applyType(RSType.headline), fontWeight: 500,
        }}>Watch progress</button>
      </div>
    );
  }

  // Completed
  if (done) {
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 32px' }}>
        <div style={{
          width: 84, height: 84, borderRadius: 99, background: t.success + '1F',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          animation: 'rsHeroIn 420ms cubic-bezier(.2,.7,.3,1)',
        }}>
          <Icon name="check" size={42} color={t.success} weight={2.6}/>
        </div>
        <h1 style={{ margin: '24px 0 0', color: t.text1, ...applyType(RSType.title1), fontSize: 26 }}>
          You’re all set
        </h1>
        <p style={{ color: t.text2, ...applyType(RSType.callout), margin: '12px 0 0', maxWidth: 300, lineHeight: 1.5 }}>
          Found <b style={{ color: t.text1 }}>84 receipts</b> across {sources.length} mailboxes.
          12 have return windows still open.
        </p>
        <div style={{ marginTop: 30, width: '100%', maxWidth: 320 }}>
          <PressScale>
            <Button t={t} kind="primary" onClick={onDone}>Go to ReturnScribe</Button>
          </PressScale>
        </div>
      </div>
    );
  }

  // Foreground scanning
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 32px' }}>
      <div style={{ position: 'relative', width: 96, height: 96 }}>
        <div style={{
          position: 'absolute', inset: 0, borderRadius: 99,
          border: `3px solid ${t.surface2}`,
        }}/>
        <div style={{
          position: 'absolute', inset: 0, borderRadius: 99,
          border: `3px solid ${t.accent}`, borderTopColor: 'transparent', borderRightColor: 'transparent',
          animation: 'rsSpin 900ms linear infinite',
        }}/>
        <div style={{
          position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: t.text1, fontFamily: RSFont.num, fontSize: 24, fontWeight: 700, ...RSTabular,
        }}>{pct}%</div>
      </div>

      <h1 style={{ margin: '26px 0 0', color: t.text1, ...applyType(RSType.title1), fontSize: 24 }}>
        Scanning your receipts
      </h1>
      <div style={{ color: t.text2, ...applyType(RSType.callout), marginTop: 8, height: 22 }}>
        AI parsing <b style={{ color: t.text1 }}>{merchants[mi]}</b> receipt…
      </div>

      <div style={{ marginTop: 26, width: '100%', maxWidth: 300 }}>
        <ScanProgressBar t={t} pct={pct} color={t.accent}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
          <span style={{ color: t.text3, ...applyType(RSType.footnote), ...RSTabular }}>{found} receipts found</span>
          <span style={{ color: t.text3, ...applyType(RSType.footnote) }}>{sources.length} mailboxes</span>
        </div>
      </div>

      <button onClick={() => setBackgrounded(true)} style={{
        marginTop: 28, background: 'none', border: 'none', cursor: 'pointer',
        color: t.accent, ...applyType(RSType.headline),
      }}>Run in background</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Flow wrapper — consent → connect mailbox → background refresh → scan → done
// ─────────────────────────────────────────────────────────────
function OnboardingFlow({ t, onFinish }) {
  const [step, setStep] = React.useState('welcome');
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
      {step === 'welcome' && <WelcomeScreen t={t} onAuth={() => setStep('consent')}/>}
      {step === 'consent' && <ConsentScreen t={t} onContinue={() => setStep('mailbox')}/>}
      {step === 'mailbox' && <MailboxConnectScreen t={t} onContinue={() => setStep('bar')}/>}
      {step === 'bar' && <BackgroundRefreshAsk t={t} onAllow={() => setStep('scan')} onSkip={() => setStep('scan')}/>}
      {step === 'scan' && <ScanProgressScreen t={t} onDone={onFinish}/>}
    </div>
  );
}

Object.assign(window, {
  BrandMark, WelcomeScreen, ConsentScreen, MailboxConnectScreen, BackgroundRefreshAsk, ScanProgressScreen, OnboardingFlow,
  AppleGlyph, GoogleGlyph, MicrosoftGlyph,
});
