// Kayser v2 — Onboarding flow (Google-first)
// 6 screens: welcome → sign in (Google or manual) → tell me about you → what else
//            → Kayser folder in Drive → first find
// Lives as a full-screen overlay above the app.

// ============ INDUSTRY OPTIONS ============
const KXV2_INDUSTRIES = [
  { id: 'foundation', label: 'Foundation repair', emoji: '🏠' },
  { id: 'plumbing',   label: 'Plumbing',          emoji: '🔧' },
  { id: 'hvac',       label: 'HVAC',              emoji: '❄️' },
  { id: 'roofing',    label: 'Roofing',           emoji: '🏗️' },
  { id: 'electric',   label: 'Electrical',        emoji: '⚡' },
  { id: 'general',    label: 'General contractor', emoji: '🧱' },
  { id: 'cleaning',   label: 'Cleaning services',  emoji: '🧹' },
  { id: 'landscape',  label: 'Landscaping',       emoji: '🌳' },
  { id: 'lawyer',     label: 'Solo law practice', emoji: '⚖️' },
  { id: 'realtor',    label: 'Real estate agent', emoji: '🔑' },
  { id: 'accountant', label: 'Accountant / CPA',  emoji: '📊' },
  { id: 'consultant', label: 'Consultant / coach', emoji: '💼' },
  { id: 'therapist',  label: 'Therapist / health practitioner', emoji: '🧠' },
  { id: 'other',      label: 'Something else',    emoji: '✦' },
];

// ============ MAIN ONBOARDING ============
function KxV2Onboarding({ onComplete, onSkip }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    google: false,            // signed in with Google?
    manual: null,             // { email, imap, calendarUrl } when not Google
    name: '',
    business: '',
    industry: null,
    industryOther: '',
    money: 'sheets',          // sheets (default if Google) | qb | xero | fresh | wave | track-with-kayser | skip
    tasks: 'kayser',          // kayser | google | external (string) | skip
    docs: 'drive',            // drive | dropbox | external | kayser
  });

  const totalSteps = 6;
  const goNext = () => setStep(s => Math.min(s + 1, totalSteps - 1));
  const goBack = () => setStep(s => Math.max(s - 1, 0));

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: KX2_WALLPAPER,
      color: KX2.ink, fontFamily: KX2.fontUI,
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', padding: '14px 18px', gap: 14, flexShrink: 0,
      }}>
        {step > 0 && step < totalSteps - 1 && (
          <button onClick={goBack} aria-label="Back" style={{
            background: 'transparent', border: 'none', color: KX2.ink2,
            cursor: 'pointer', padding: 4,
            display: 'flex', alignItems: 'center', gap: 4,
            fontFamily: KX2.fontUI, fontSize: 13,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
            Back
          </button>
        )}
        <span style={{ flex: 1 }} />
        <ProgressDots count={totalSteps} active={step} />
        <span style={{ flex: 1 }} />
        {step > 0 && step < totalSteps - 1 && (
          <button onClick={onSkip} style={{
            background: 'transparent', border: 'none', color: KX2.ink3,
            cursor: 'pointer', padding: 4, fontFamily: KX2.fontUI, fontSize: 13,
          }}>Skip setup</button>
        )}
      </div>

      {/* Step content */}
      <div style={{ flex: 1, overflowY: 'auto', display: 'flex', justifyContent: 'center' }}>
        <div style={{ width: '100%', maxWidth: 480, padding: '12px 24px 32px' }}>
          {step === 0 && <StepWelcome onNext={goNext} />}
          {step === 1 && <StepSignIn onNext={goNext} data={data} setData={setData} />}
          {step === 2 && <StepTellMe onNext={goNext} data={data} setData={setData} />}
          {step === 3 && <StepWhatElse onNext={goNext} data={data} setData={setData} />}
          {step === 4 && <StepDriveFolder onNext={goNext} data={data} />}
          {step === 5 && <StepFirstFind data={data} onComplete={onComplete} />}
        </div>
      </div>
    </div>
  );
}

function ProgressDots({ count, active }) {
  return (
    <div style={{ display: 'flex', gap: 5 }}>
      {[...Array(count)].map((_, i) => (
        <div key={i} style={{
          width: i === active ? 16 : 6, height: 6, borderRadius: 3,
          background: i <= active ? KX2.brand : 'rgba(255,255,255,.15)',
          transition: 'all 220ms',
        }} />
      ))}
    </div>
  );
}

// ============ STEP 0 · Welcome ============
function StepWelcome({ onNext }) {
  return (
    <div style={{ padding: '40px 0', textAlign: 'center' }}>
      <div style={{
        width: 72, height: 72, borderRadius: 36, margin: '0 auto 24px',
        background: `linear-gradient(135deg, ${KX2.brand} 0%, ${KX2.brandDeep} 100%)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: KX2.fontBrand, fontWeight: 700, color: '#fff', fontSize: 32,
        boxShadow: '0 0 0 1px rgba(255,255,255,.18) inset, 0 12px 32px rgba(124,58,237,.5)',
      }}>K</div>
      <div style={{ fontFamily: KX2.fontBrand, fontSize: 30, fontWeight: 700, color: KX2.ink, letterSpacing: -0.5, marginBottom: 12 }}>I'm Kayser.</div>
      <div style={{ fontSize: 16, color: KX2.ink2, lineHeight: 1.5, maxWidth: 380, margin: '0 auto 32px' }}>
        Think of me as a second set of hands for your business — I read what comes in,
        draft what needs to go out, and handle the routine so you don't have to.
      </div>
      <div style={{ display: 'grid', gap: 10, marginBottom: 24, textAlign: 'left' }}>
        {[
          { t: 'I start out asking before I do anything.', s: 'You stay in control.' },
          { t: 'The more you approve, the more I do on my own.', s: "I'll never auto-handle something you haven't shown me first." },
          { t: 'Three minutes to set up. You can change anything later.', s: '' },
        ].map((r, i) => (
          <div key={i} style={{ ...kx2GlassThin({ borderRadius: 12 }), padding: '12px 14px', display: 'flex', gap: 12 }}>
            <span style={{
              width: 24, height: 24, borderRadius: 12, background: KX2.brandSoft,
              color: KX2.brand, display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: KX2.fontMono, fontWeight: 700, fontSize: 12, flexShrink: 0,
            }}>{i + 1}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, color: KX2.ink, fontWeight: 500 }}>{r.t}</div>
              {r.s && <div style={{ fontSize: 12, color: KX2.ink3, marginTop: 2 }}>{r.s}</div>}
            </div>
          </div>
        ))}
      </div>
      <button onClick={onNext} style={primaryBtn()}>Let's go →</button>
    </div>
  );
}

// ============ STEP 1 · Sign in (Google or manual) ============
function StepSignIn({ onNext, data, setData }) {
  const [manualOpen, setManualOpen] = React.useState(false);
  const [manualData, setManualData] = React.useState({ email: '', imap: 'gmail', calendarUrl: '' });

  const signInGoogle = () => {
    // Real flow: redirect to OAuth. Here we fake success.
    setData(d => ({ ...d, google: true, manual: null }));
    setTimeout(onNext, 250);
  };

  const finishManual = () => {
    setData(d => ({ ...d, google: false, manual: manualData }));
    setTimeout(onNext, 100);
  };

  return (
    <div style={{ padding: '24px 0' }}>
      <div style={{ fontFamily: KX2.fontBrand, fontSize: 26, fontWeight: 700, color: KX2.ink, letterSpacing: -0.4 }}>
        Connect your work life.
      </div>
      <div style={{ fontSize: 14, color: KX2.ink2, marginTop: 8, lineHeight: 1.5 }}>
        Almost everything I do works best through Google — email, calendar, docs, sheets, drive — all in one sign-in. <span style={{ color: KX2.ink, fontWeight: 500 }}>It's the fastest way to get started.</span>
      </div>

      {/* Big Google button */}
      <button onClick={signInGoogle} style={{
        marginTop: 28, width: '100%', padding: '16px',
        borderRadius: 14, border: `1px solid ${KX2.glassLine}`,
        background: '#fff', color: '#1a1a1a',
        fontFamily: KX2.fontUI, fontSize: 15, fontWeight: 600,
        cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
        boxShadow: '0 8px 24px rgba(255,255,255,.08)',
      }}>
        <GoogleG size={20} />
        Continue with Google
      </button>

      {/* What it grants */}
      <div style={{
        ...kx2GlassThin({ borderRadius: 12 }),
        marginTop: 14, padding: '12px 14px',
      }}>
        <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase', marginBottom: 8 }}>
          One sign-in connects:
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {[
            { i: 'M', label: 'Gmail',       sub: 'I read inbound, draft replies' },
            { i: 'C', label: 'Calendar',    sub: 'I watch for conflicts' },
            { i: 'D', label: 'Drive',       sub: 'I save things you own' },
            { i: 'S', label: 'Sheets',      sub: 'Books, customers, tasks' },
            { i: 'X', label: 'Docs',        sub: 'Notes, contracts, quotes' },
            { i: '+', label: 'Forms',       sub: 'Catch web form leads' },
          ].map(x => (
            <div key={x.label} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{
                width: 22, height: 22, borderRadius: 6,
                background: KX2.chipBg, color: KX2.ink2,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: KX2.fontMono, fontWeight: 700, fontSize: 11,
              }}>{x.i}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, color: KX2.ink, fontWeight: 500 }}>{x.label}</div>
                <div style={{ fontSize: 10.5, color: KX2.ink3, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{x.sub}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Trust note */}
      <div style={{
        marginTop: 14, padding: '10px 14px',
        fontSize: 11.5, color: KX2.ink3, lineHeight: 1.5,
        borderLeft: `2px solid ${KX2.brand}`,
        background: 'rgba(124,58,237,.06)', borderRadius: '0 8px 8px 0',
      }}>
        Everything I write lives in your Drive, in your account, in formats you own — Sheets, Docs, files. If you ever stop using Kayser, your data stays put.
      </div>

      {/* Manual escape hatch */}
      <div style={{ marginTop: 24, textAlign: 'center' }}>
        <button onClick={() => setManualOpen(o => !o)} style={{
          background: 'transparent', border: 'none', color: KX2.ink3,
          cursor: 'pointer', fontFamily: KX2.fontUI, fontSize: 13,
          textDecoration: 'underline', textUnderlineOffset: 3,
        }}>
          Don't use Google?
        </button>
      </div>

      {manualOpen && (
        <div style={{
          ...kx2GlassThin({ borderRadius: 12 }),
          marginTop: 14, padding: 14,
        }}>
          <div style={{ fontSize: 13, color: KX2.ink, fontWeight: 500, marginBottom: 4 }}>
            That's okay — I can work with what you have.
          </div>
          <div style={{ fontSize: 12, color: KX2.ink3, lineHeight: 1.5, marginBottom: 14 }}>
            Connect your email (any provider) and calendar separately. Some Google-specific features (Sheets-based books, Docs-based notes) will be limited until you connect one.
          </div>

          <OnbInput label="Email address" placeholder="you@yourbusiness.com"
            value={manualData.email} onChange={(v) => setManualData(d => ({ ...d, email: v }))} />
          <div style={{ marginTop: 12 }}>
            <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase', marginBottom: 6 }}>Email provider</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 6 }}>
              {['gmail', 'outlook', 'other (IMAP)'].map(p => (
                <button key={p} onClick={() => setManualData(d => ({ ...d, imap: p }))} style={{
                  padding: '8px', borderRadius: 8, fontSize: 12, fontFamily: KX2.fontUI,
                  background: manualData.imap === p ? KX2.brandSoft : KX2.glassInput,
                  border: `1px solid ${manualData.imap === p ? KX2.brand : KX2.glassLine}`,
                  color: KX2.ink, cursor: 'pointer', textTransform: 'capitalize',
                }}>{p}</button>
              ))}
            </div>
          </div>
          <div style={{ marginTop: 12 }}>
            <OnbInput label="Calendar (iCal URL, optional)" placeholder="https://calendar.example.com/feed.ics"
              value={manualData.calendarUrl} onChange={(v) => setManualData(d => ({ ...d, calendarUrl: v }))} />
          </div>
          <button onClick={finishManual} disabled={!manualData.email} style={{
            marginTop: 16, width: '100%', padding: '12px',
            borderRadius: 12, border: 'none',
            background: manualData.email ? KX2.brand : KX2.chipBg,
            color: manualData.email ? '#fff' : KX2.ink3,
            fontFamily: KX2.fontUI, fontSize: 14, fontWeight: 600,
            cursor: manualData.email ? 'pointer' : 'not-allowed',
            opacity: manualData.email ? 1 : 0.6,
          }}>Continue with email-only</button>
        </div>
      )}
    </div>
  );
}

function GoogleG({ size = 20 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 48 48">
      <path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 13 4 4 13 4 24s9 20 20 20 20-9 20-20c0-1.3-.1-2.7-.4-3.9z"/>
      <path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 16 19 13 24 13c3.1 0 5.8 1.2 7.9 3.1l5.7-5.7C34 6.1 29.3 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/>
      <path fill="#4CAF50" d="M24 44c5.2 0 10-2 13.6-5.2l-6.3-5.2c-2 1.5-4.5 2.4-7.3 2.4-5.2 0-9.6-3.3-11.2-7.9l-6.5 5C9.5 39.6 16.2 44 24 44z"/>
      <path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.3-2.3 4.3-4.3 5.7l6.3 5.2c-.4.4 6.7-4.9 6.7-14.9 0-1.3-.1-2.7-.4-3.9z"/>
    </svg>
  );
}

// ============ STEP 2 · Tell me about you ============
function StepTellMe({ onNext, data, setData }) {
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const isOther = data.industry === 'other';
  const ready = data.name.trim() && data.business.trim() && data.industry && (!isOther || data.industryOther.trim());
  return (
    <div style={{ padding: '20px 0' }}>
      <div style={{ fontFamily: KX2.fontBrand, fontSize: 24, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3 }}>
        Tell me about you.
      </div>
      <div style={{ fontSize: 14, color: KX2.ink2, marginTop: 6, lineHeight: 1.5 }}>
        I'll use this to talk like a real coworker — using the words you actually use.
      </div>

      <div style={{ marginTop: 24, display: 'grid', gap: 12 }}>
        <OnbInput label="Your name" placeholder="e.g. Wes" value={data.name} onChange={(v) => set('name', v)} />
        <OnbInput label="Business name" placeholder="e.g. Kayser Foundation Repair" value={data.business} onChange={(v) => set('business', v)} />
      </div>

      <div style={{ marginTop: 24 }}>
        <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase', marginBottom: 10 }}>What do you do?</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {KXV2_INDUSTRIES.map(i => (
            <button key={i.id} onClick={() => set('industry', i.id)} style={{
              padding: '12px 12px', borderRadius: 12, textAlign: 'left',
              background: data.industry === i.id ? KX2.brandSoft : KX2.glassInput,
              border: `1px solid ${data.industry === i.id ? KX2.brand : KX2.glassLine}`,
              color: KX2.ink, fontFamily: KX2.fontUI, cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <span style={{ fontSize: 18 }}>{i.emoji}</span>
              <span style={{ fontSize: 13.5, fontWeight: 500 }}>{i.label}</span>
            </button>
          ))}
        </div>
        {isOther && (
          <div style={{ marginTop: 12 }}>
            <OnbInput label="What kind of work?" placeholder="e.g. pet boarding · audio production · paralegal services"
              value={data.industryOther} onChange={(v) => set('industryOther', v)} />
            <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 6, lineHeight: 1.5, paddingLeft: 2 }}>
              I'll ask a few quick questions in chat once we're done so I get your vocabulary right.
            </div>
          </div>
        )}
      </div>

      <button onClick={onNext} disabled={!ready} style={{
        ...primaryBtn(), marginTop: 28,
        background: ready ? KX2.brand : KX2.chipBg,
        color: ready ? '#fff' : KX2.ink3,
        cursor: ready ? 'pointer' : 'not-allowed',
        opacity: ready ? 1 : 0.6,
        boxShadow: ready ? '0 8px 24px rgba(124,58,237,.45)' : 'none',
      }}>Continue →</button>
    </div>
  );
}

// ============ STEP 3 · What else (money / tasks / docs / SMS) ============
function StepWhatElse({ onNext, data, setData }) {
  const isGoogle = data.google;
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));

  // Money options vary slightly based on Google connection
  const moneyOptions = [
    isGoogle && { id: 'sheets',           label: "Track in a Kayser-managed Sheet",   sub: "Auto-maintained P&L in your Google Sheets",  recommended: true },
    { id: 'qb',                            label: 'QuickBooks',                         sub: 'Connect existing books' },
    { id: 'xero',                          label: 'Xero',                                sub: 'Connect existing books' },
    { id: 'fresh',                         label: 'FreshBooks',                          sub: 'Connect existing books' },
    { id: 'track-with-kayser',             label: "I don't track money yet",            sub: "Use Kayser's built-in basic accounting" },
    { id: 'skip',                          label: "I'll handle this later",             sub: "" },
  ].filter(Boolean);

  const tasksOptions = [
    { id: 'kayser', label: "Use Kayser's built-in to-do",       sub: 'Simple list, syncs with chat' },
    isGoogle && { id: 'google', label: 'Google Tasks',           sub: 'Already connected' },
    { id: 'external-todoist',  label: 'Todoist',                 sub: 'Connect later' },
    { id: 'external-notion',   label: 'Notion / Things / other', sub: "I'll forward task mentions to you" },
  ].filter(Boolean);

  const docsOptions = [
    isGoogle && { id: 'drive', label: 'Google Drive',            sub: 'Already connected', recommended: true },
    { id: 'kayser', label: "Use Kayser's built-in files",        sub: 'Simple folder, syncs with chat' },
    { id: 'dropbox', label: 'Dropbox',                            sub: 'Connect later' },
    { id: 'external', label: 'Notion / OneDrive / other',         sub: "I'll forward what I make to you" },
  ].filter(Boolean);

  return (
    <div style={{ padding: '20px 0' }}>
      <div style={{ fontFamily: KX2.fontBrand, fontSize: 24, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3 }}>
        {isGoogle ? "A few more details." : "Anything else I should know?"}
      </div>
      <div style={{ fontSize: 14, color: KX2.ink2, marginTop: 6, lineHeight: 1.5 }}>
        {isGoogle
          ? "I already have your email and calendar via Google. These help me handle the rest."
          : "Tell me where you keep things. Each one I see gives me more to work with."}
      </div>

      {/* Phone — coming soon */}
      <div style={{
        ...kx2GlassThin({ borderRadius: 12 }),
        marginTop: 22, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12,
        opacity: 0.65,
      }}>
        <span style={{
          width: 32, height: 32, borderRadius: 8, background: KX2.chipBg, color: KX2.ink2,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: KX2.fontMono, fontWeight: 700, fontSize: 14, flexShrink: 0,
        }}>📱</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, color: KX2.ink, fontWeight: 500 }}>Phone & SMS</div>
          <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 1 }}>I'll provision a number for you once you're set up. Coming after launch.</div>
        </div>
        <span style={{
          fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
          color: KX2.warn, padding: '2px 8px', borderRadius: 4,
          background: 'rgba(251,191,36,.12)', fontWeight: 700,
        }}>SOON</span>
      </div>

      {/* Money */}
      <OnbPicker
        label="How do you handle money?"
        options={moneyOptions}
        value={data.money}
        onChange={(v) => set('money', v)}
      />

      {/* Tasks */}
      <OnbPicker
        label="To-do list?"
        options={tasksOptions}
        value={data.tasks}
        onChange={(v) => set('tasks', v)}
      />

      {/* Docs */}
      <OnbPicker
        label="Where do your files live?"
        options={docsOptions}
        value={data.docs}
        onChange={(v) => set('docs', v)}
      />

      <div style={{
        ...kx2GlassThin({ borderRadius: 12 }),
        marginTop: 18, padding: '12px 14px',
        fontSize: 12.5, color: KX2.ink2, lineHeight: 1.5,
      }}>
        <div style={{ color: KX2.brand, fontWeight: 600, marginBottom: 4 }}>Using something I don't list?</div>
        Forward emails to <span style={{
          fontFamily: KX2.fontMono, color: KX2.ink, background: KX2.chipBg,
          padding: '1px 6px', borderRadius: 4,
        }}>automations@kayser.com</span> and I'll parse them. Works with any CRM, scheduler, or quoting tool.
      </div>

      <button onClick={onNext} style={{ ...primaryBtn(), marginTop: 28 }}>Continue →</button>
    </div>
  );
}

function OnbPicker({ label, options, value, onChange }) {
  return (
    <div style={{ marginTop: 22 }}>
      <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase', marginBottom: 8 }}>{label}</div>
      <div style={{ display: 'grid', gap: 6 }}>
        {options.map(o => (
          <button key={o.id} onClick={() => onChange(o.id)} style={{
            padding: '11px 14px', borderRadius: 10, textAlign: 'left',
            background: value === o.id ? KX2.brandSoft : KX2.glassInput,
            border: `1px solid ${value === o.id ? KX2.brand : KX2.glassLine}`,
            color: KX2.ink, fontFamily: KX2.fontUI, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 14, fontWeight: 600 }}>{o.label}</span>
                {o.recommended && (
                  <span style={{
                    fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
                    color: KX2.brand, padding: '1px 6px', borderRadius: 4,
                    background: KX2.brandSoft, fontWeight: 700,
                  }}>BEST</span>
                )}
              </div>
              {o.sub && <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 2 }}>{o.sub}</div>}
            </div>
            {value === o.id && <span style={{ color: KX2.brand, fontSize: 16 }}>✓</span>}
          </button>
        ))}
      </div>
    </div>
  );
}

function OnbInput({ label, placeholder, value, onChange }) {
  return (
    <div>
      <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase', marginBottom: 6 }}>{label}</div>
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
        style={{
          width: '100%', boxSizing: 'border-box',
          padding: '12px 14px',
          background: KX2.glassInput,
          border: `1px solid ${KX2.glassLine}`,
          borderRadius: 12, outline: 'none',
          color: KX2.ink, fontSize: 15, fontFamily: KX2.fontUI,
        }} />
    </div>
  );
}

// ============ STEP 4 · Kayser folder created (the moat) ============
function StepDriveFolder({ onNext, data }) {
  const isGoogle = data.google;
  const [showOpen, setShowOpen] = React.useState(true);
  return (
    <div style={{ padding: '32px 0' }}>
      <div style={{ textAlign: 'center', marginBottom: 28 }}>
        <div style={{
          width: 64, height: 64, borderRadius: 16, margin: '0 auto 18px',
          background: 'linear-gradient(135deg, #4285f4 0%, #1a73e8 100%)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 28, color: '#fff',
          boxShadow: '0 8px 24px rgba(66,133,244,.4)',
        }}>📁</div>
        <div style={{ fontFamily: KX2.fontBrand, fontSize: 24, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3, marginBottom: 10 }}>
          {isGoogle ? "I made a Kayser folder in your Drive." : "Here's your Kayser workspace."}
        </div>
        <div style={{ fontSize: 14, color: KX2.ink2, lineHeight: 1.5, maxWidth: 400, margin: '0 auto' }}>
          {isGoogle
            ? "Everything I write lives here, in your account, in formats you own. You can open any of it in Google Drive directly."
            : "Everything I save lives in your private Kayser workspace. You can connect Google later to keep it all in your own Drive."}
        </div>
      </div>

      {/* Folder preview */}
      <div style={{ ...kx2Glass({ borderRadius: 14 }), overflow: 'hidden' }}>
        <div style={{
          padding: '10px 14px', borderBottom: `1px solid ${KX2.glassLine}`,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <span style={{ fontSize: 14 }}>📁</span>
          <span style={{ fontFamily: KX2.fontMono, fontSize: 12, color: KX2.ink2 }}>Drive / Kayser /</span>
        </div>
        <div style={{ padding: 6 }}>
          {[
            { i: '📊', n: 'Customers.sheet', d: 'Auto-maintained · who they are, what they need' },
            { i: '💰', n: 'Money.sheet',      d: 'Auto-maintained · invoices, bills, P&L' },
            { i: '✓',  n: 'Tasks.sheet',      d: 'Auto-maintained · to-do list synced to chat' },
            { i: '📄', n: 'Notes / (folder)', d: 'One doc per customer · gate codes, quirks, history' },
            { i: '📎', n: 'Files / (folder)', d: 'Receipts, photos, contracts · auto-filed' },
          ].map(r => (
            <div key={r.n} style={{
              padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 12,
              borderRadius: 8,
            }}>
              <span style={{ fontSize: 18, flexShrink: 0 }}>{r.i}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, color: KX2.ink, fontWeight: 500 }}>{r.n}</div>
                <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 1 }}>{r.d}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{
        marginTop: 16, padding: '12px 14px',
        fontSize: 12.5, color: KX2.ink2, lineHeight: 1.5,
        borderLeft: `2px solid ${KX2.approve}`,
        background: 'rgba(52,211,153,.06)', borderRadius: '0 8px 8px 0',
      }}>
        <span style={{ color: KX2.approve, fontWeight: 600 }}>You own your data.</span> If you ever leave Kayser, your customer list, your books, your notes — they all stay in your Drive.
      </div>

      <button onClick={onNext} style={{ ...primaryBtn(), marginTop: 24 }}>Looks good →</button>
    </div>
  );
}

// ============ STEP 5 · First find (honest about readiness) ============
function StepFirstFind({ data, onComplete }) {
  const [phase, setPhase] = React.useState('settling'); // settling → ready
  React.useEffect(() => {
    const t = setTimeout(() => setPhase('ready'), 2200);
    return () => clearTimeout(t);
  }, []);

  const name = data.name || 'there';
  const ind = KXV2_INDUSTRIES.find(i => i.id === data.industry);
  const industryLabel = data.industry === 'other' && data.industryOther
    ? data.industryOther
    : (ind?.label?.toLowerCase() || 'your business');

  return (
    <div style={{ padding: '32px 0', textAlign: 'center' }}>
      <div style={{
        width: 64, height: 64, borderRadius: 32, margin: '0 auto 20px',
        background: `linear-gradient(135deg, ${KX2.brand} 0%, ${KX2.brandDeep} 100%)`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: KX2.fontBrand, fontWeight: 700, color: '#fff', fontSize: 26,
        position: 'relative',
        boxShadow: '0 0 0 1px rgba(255,255,255,.18) inset, 0 8px 24px rgba(124,58,237,.45)',
      }}>
        K
        {phase === 'settling' && (
          <span style={{
            position: 'absolute', inset: -6, borderRadius: '50%',
            border: `2px solid ${KX2.brand}`, opacity: 0.4,
            animation: 'kxPing 1.4s ease-out infinite',
          }} />
        )}
      </div>
      <style>{`@keyframes kxPing { 0%{transform:scale(1);opacity:.6} 100%{transform:scale(1.6);opacity:0} }`}</style>

      {phase === 'settling' ? (
        <>
          <div style={{ fontFamily: KX2.fontBrand, fontSize: 22, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3, marginBottom: 10 }}>
            Settling in…
          </div>
          <div style={{ fontSize: 13.5, color: KX2.ink3, lineHeight: 1.5 }}>
            Setting up your folder and learning the basics of {industryLabel}.
          </div>
        </>
      ) : (
        <>
          <div style={{ fontFamily: KX2.fontBrand, fontSize: 22, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3, marginBottom: 10 }}>
            Ready, {name}.
          </div>
          <div style={{ fontSize: 14, color: KX2.ink2, lineHeight: 1.5, maxWidth: 400, margin: '0 auto 24px' }}>
            I'm going to spend the next few minutes reading through what I have access to. As I find things worth your attention, I'll surface them in chat.
          </div>

          <div style={{
            ...kx2Glass({ borderRadius: 14 }),
            padding: 14, textAlign: 'left', marginBottom: 20,
          }}>
            <div style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, letterSpacing: 0.4, marginBottom: 6 }}>WHAT TO EXPECT FIRST</div>
            <div style={{ display: 'grid', gap: 10 }}>
              {[
                { i: '◌', t: 'A few "watching" notes', s: "Things I'm keeping an eye on, like unsent invoices or stale leads." },
                { i: '◇', t: 'A couple of approvals', s: "Drafts I'd like to send — you tap Send, Edit, or Skip." },
                { i: '✓', t: 'A trust dial that grows', s: "The more you approve, the more I'll handle on my own." },
              ].map(x => (
                <div key={x.t} style={{ display: 'flex', gap: 10 }}>
                  <span style={{
                    width: 22, height: 22, borderRadius: 11, background: KX2.brandSoft, color: KX2.brand,
                    fontFamily: KX2.fontMono, fontWeight: 700, fontSize: 11, flexShrink: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{x.i}</span>
                  <div>
                    <div style={{ fontSize: 13.5, color: KX2.ink, fontWeight: 500 }}>{x.t}</div>
                    <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 1, lineHeight: 1.45 }}>{x.s}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <button onClick={() => onComplete?.(data)} style={primaryBtn()}>
            Take me in →
          </button>
        </>
      )}
    </div>
  );
}

// ============ Helpers ============
function primaryBtn() {
  return {
    width: '100%', padding: '14px', borderRadius: 14, border: 'none',
    background: KX2.brand, color: '#fff',
    fontFamily: KX2.fontUI, fontSize: 15, fontWeight: 600,
    cursor: 'pointer', boxShadow: '0 8px 24px rgba(124,58,237,.45)',
  };
}

Object.assign(window, { KxV2Onboarding, KXV2_INDUSTRIES });
