// ════════════ SETTINGS cluster (deep) ════════════
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Toggle, Field, Select, Tabs, money } = window;

window.SCREENS['settings'] = function Settings({ sub }) {
  const P = window.PX; const { go } = window.useApp();
  const active = (sub || '').split('/')[0] || 'profile';
  const nav = [
    { label: 'Account', items: [
      { k: 'profile', icon: 'user', label: 'Profile' },
      { k: 'workspace', icon: 'building', label: 'Workspace' },
      { k: 'members', icon: 'users', label: 'Members', badge: 5 },
      { k: 'notifications', icon: 'bell', label: 'Notifications' },
    ]},
    { label: 'Billing', items: [
      { k: 'plan', icon: 'star', label: 'Plan' },
      { k: 'sparks', icon: 'zap', label: 'Sparks' },
      { k: 'payment', icon: 'card', label: 'Payment methods' },
    ]},
    { label: 'System', items: [
      { k: 'brand', icon: 'palette', label: 'Brand & theme' },
      { k: 'integrations', icon: 'layers', label: 'Integrations' },
      { k: 'security', icon: 'shield', label: 'Security' },
      { k: 'data', icon: 'database', label: 'Data & export' },
      { k: 'onboard', icon: 'sparkles', label: 'Setup & onboarding' },
    ]},
  ];
  return (
    <window.SubLayout title="Settings" nav={nav} active={active} onNav={k => go(k === 'onboard' ? 'onboard' : 'settings/' + k)}>
      <div style={{ padding: 24, maxWidth: 820 }}>
        {active === 'profile' && <SetProfile/>}
        {active === 'workspace' && <SetWorkspace/>}
        {active === 'members' && <SetMembers/>}
        {active === 'notifications' && <SetNotifications/>}
        {active === 'plan' && <SetPlan/>}
        {active === 'sparks' && <SetSparks/>}
        {active === 'payment' && <SetPayment/>}
        {active === 'brand' && <SetBrand/>}
        {active === 'integrations' && <SetIntegrations/>}
        {active === 'security' && <SetSecurity/>}
        {active === 'data' && <SetData/>}
      </div>
    </window.SubLayout>
  );
};

const SetHead = ({ t, s }) => { const P = window.PX; return <div style={{ marginBottom: 20 }}><div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 26, color: P.ink }}>{t}</div><div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2 }}>{s}</div></div>; };
const Row = ({ label, sub, children }) => { const P = window.PX; return <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '14px 0', borderBottom: `1px solid ${P.line}` }}><div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{label}</div>{sub && <div style={{ fontSize: 11.5, color: P.ink3, marginTop: 2 }}>{sub}</div>}</div>{children}</div>; };

function SetProfile() {
  const P = window.PX; const { toast } = window.useApp();
  const initial = { name: 'Amara Okafor', title: 'Owner & Head Baker', email: 'amara@honestloaves.com', phone: '+1 (718) 555-0142' };
  const [f, setF] = React.useState(initial);
  const set = (k) => (v) => setF(s => ({ ...s, [k]: v }));
  const dirty = JSON.stringify(f) !== JSON.stringify(initial);
  return (
    <>
      <SetHead t="Profile" s="How you appear across Pexxie"/>
      <Card pad={20} style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18 }}>
          <Avatar name={f.name} size={64}/>
          <div><Btn kind="default" size="sm" onClick={() => toast('Choose a photo — your file picker would open here.', { icon: 'image' })}>Change photo</Btn><div style={{ fontSize: 11, color: P.ink3, marginTop: 6 }}>JPG or PNG · max 2MB</div></div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Full name" value={f.name} onChange={set('name')}/>
          <Field label="Title" value={f.title} onChange={set('title')}/>
          <Field label="Email" value={f.email} onChange={set('email')} icon="mail"/>
          <Field label="Phone" value={f.phone} onChange={set('phone')} icon="phone"/>
        </div>
      </Card>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}><Btn kind="ghost" size="md" disabled={!dirty} onClick={() => setF(initial)}>Cancel</Btn><Btn kind="primary" size="md" disabled={!dirty} onClick={() => toast('Profile saved.', { tone: 'sage', icon: 'check' })}>Save changes</Btn></div>
    </>
  );
}

function SetWorkspace() {
  const P = window.PX; const { toast } = window.useApp();
  const initial = { name: 'Honest Loaves', industry: 'Artisan bakery', address: '241 Metropolitan Ave', city: 'Brooklyn, NY 11211', ein: '••-•••4821', currency: 'USD ($)' };
  const [f, setF] = React.useState(initial);
  const set = (k) => (v) => setF(s => ({ ...s, [k]: v }));
  const dirty = JSON.stringify(f) !== JSON.stringify(initial);
  return (
    <>
      <SetHead t="Workspace" s="Business details used across invoices, your site, and Pex"/>
      <Card pad={20}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18 }}>
          <div style={{ width: 56, height: 56, borderRadius: 12, background: '#3A2A1C', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.serif, fontStyle: 'italic', color: '#F5D8A8', fontSize: 26 }}>hl</div>
          <Btn kind="default" size="sm" onClick={() => toast('Upload a logo — your file picker would open here.', { icon: 'image' })}>Change logo</Btn>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Business name" value={f.name} onChange={set('name')}/>
          <Field label="Industry" value={f.industry} onChange={set('industry')}/>
          <Field label="Address" value={f.address} onChange={set('address')}/>
          <Field label="City / State" value={f.city} onChange={set('city')}/>
          <Field label="Tax ID (EIN)" value={f.ein} onChange={set('ein')} mono/>
          <Select label="Currency" value={f.currency} onChange={set('currency')} options={['USD ($)', 'EUR (€)', 'GBP (£)', 'CAD ($)', 'AUD ($)']}/>
        </div>
      </Card>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 16 }}><Btn kind="ghost" size="md" disabled={!dirty} onClick={() => setF(initial)}>Cancel</Btn><Btn kind="primary" size="md" disabled={!dirty} onClick={() => toast('Workspace details saved.', { tone: 'sage', icon: 'check' })}>Save changes</Btn></div>
    </>
  );
}

function SetMembers() {
  const P = window.PX; const { toast } = window.useApp();
  const [team, setTeam] = React.useState([['Amara Okafor', 'amara@honestloaves.com', 'Owner', 'sage'], ['Rosa Kim', 'rosa@honestloaves.com', 'Admin', 'sky'], ['Diego Torres', 'diego@honestloaves.com', 'Member', 'neutral'], ['Ethan Brooks', 'ethan@honestloaves.com', 'Member', 'neutral'], ['Priya Venkatesan', 'priya@honestloaves.com', 'Member · PT', 'neutral']]);
  const [inviting, setInviting] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const [role, setRole] = React.useState('Member');
  const [menu, setMenu] = React.useState(null);
  const invite = () => {
    if (!email || !/.+@.+\..+/.test(email)) { toast('Enter a valid email to invite.', { tone: 'rose', icon: 'alert' }); return; }
    const name = email.split('@')[0].replace(/[._]/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
    setTeam(t => [...t, [name, email, role + ' · invited', 'amber']]);
    setEmail(''); setInviting(false); toast(`Invite sent to ${email}.`, { tone: 'sage', icon: 'send' });
  };
  const removeMember = (i) => { setTeam(t => t.filter((_, j) => j !== i)); setMenu(null); toast('Member removed.', { icon: 'trash' }); };
  return (
    <>
      <SetHead t="Members" s={`${team.length} people · unlimited seats on every plan`}/>
      <Card>
        <div style={{ padding: '12px 18px', display: 'flex', borderBottom: `1px solid ${P.line}` }}><span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: P.ink }}>Team</span><Btn kind="primary" size="sm" icon="plus" onClick={() => setInviting(v => !v)}>Invite</Btn></div>
        {inviting && (
          <div style={{ padding: '14px 18px', display: 'flex', gap: 10, alignItems: 'flex-end', borderBottom: `1px solid ${P.line}`, background: P.canvas }}>
            <Field label="Email to invite" value={email} onChange={setEmail} placeholder="name@honestloaves.com" icon="mail" style={{ flex: 1 }}/>
            <Select label="Role" value={role} onChange={setRole} options={['Admin', 'Member']} style={{ width: 130 }}/>
            <Btn kind="primary" size="md" onClick={invite}>Send invite</Btn>
          </div>
        )}
        {team.map((m, i) => (
          <div key={i} style={{ padding: '13px 18px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: i < team.length - 1 ? `1px solid ${P.line}` : 'none', position: 'relative' }}>
            <Avatar name={m[0]} size={34}/>
            <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>{m[0]}</div><div style={{ fontSize: 11.5, color: P.ink3 }}>{m[1]}</div></div>
            <Pill tone={m[3]}>{m[2]}</Pill>
            <Icon name="dotsV" size={16} color={P.ink4} style={{ cursor: 'pointer' }} onClick={() => setMenu(menu === i ? null : i)}/>
            {menu === i && (
              <div style={{ position: 'absolute', right: 18, top: 44, background: P.card, border: `1px solid ${P.line}`, borderRadius: 10, boxShadow: P.shPop, zIndex: 20, overflow: 'hidden', width: 150 }}>
                <div onClick={() => { toast('Role change would open here.', { icon: 'user' }); setMenu(null); }} style={{ padding: '9px 12px', fontSize: 12.5, color: P.ink, cursor: 'pointer' }} onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>Change role</div>
                {m[2] !== 'Owner' && <div onClick={() => removeMember(i)} style={{ padding: '9px 12px', fontSize: 12.5, color: P.rose, cursor: 'pointer' }} onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>Remove</div>}
              </div>
            )}
          </div>
        ))}
      </Card>
    </>
  );
}

function SetNotifications() {
  const P = window.PX;
  const groups = [['Pex proposals', 'When Pex has work ready for you', ['Push', 'Email digest · daily 7am', 'SMS for urgent']], ['Money', 'Payments, overdue invoices, low balance', ['Invoice paid', 'Invoice overdue', 'Low balance']], ['People', 'New leads and replies', ['New website lead', 'Customer reply']]];
  const [on, setOn] = React.useState({ 'Push': true, 'Email digest · daily 7am': true, 'SMS for urgent': false, 'Invoice paid': true, 'Invoice overdue': true, 'Low balance': false, 'New website lead': true, 'Customer reply': true });
  const toggle = (k) => setOn(s => ({ ...s, [k]: !s[k] }));
  return (
    <>
      <SetHead t="Notifications" s="Choose what reaches you, and how"/>
      {groups.map((g, i) => (
        <Card key={i} pad={18} style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: P.ink }}>{g[0]}</div>
          <div style={{ fontSize: 11.5, color: P.ink3, marginBottom: 4 }}>{g[1]}</div>
          {g[2].map((label, j) => <Row key={j} label={label}><Toggle on={on[label]} onClick={() => toggle(label)}/></Row>)}
        </Card>
      ))}
    </>
  );
}

function SetPlan() {
  const P = window.PX; const { toast } = window.useApp();
  const [plan, setPlan] = React.useState('Free');
  const upgrade = (name) => { setPlan(name); toast(`You're on ${name} now — Sparks and storage updated.`, { tone: 'sage', icon: 'check' }); };
  return (
    <>
      <SetHead t="Plan" s={`You're on ${plan} · unlimited seats`}/>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14 }}>
        {[
          { n: 'Free', p: '$0', sub: '+ Sparks as you go', feat: ['All 12 apps', 'Unlimited seats', '15 GB files', '10 ⚡/mo'] },
          { n: 'Pro', p: '$100', sub: '/month', feat: ['Everything in Free', '120 ⚡/mo', '500 GB files', 'Priority Pex'], hot: true },
          { n: 'Scale', p: '$200', sub: '/month', feat: ['Everything in Pro', '320 ⚡/mo', '2 TB files', 'Senior Pex'] },
        ].map((t, i) => {
          const cur = plan === t.n;
          return (
          <Card key={i} pad={20} style={{ background: t.hot ? P.sparkWash : P.card, color: P.ink, border: `1.5px solid ${t.hot ? P.spark : P.line}`, position: 'relative' }}>
            {t.hot && <div style={{ position: 'absolute', top: -9, left: 20, background: P.spark, color: '#fff', padding: '2px 9px', borderRadius: 10, fontSize: 10, fontWeight: 600 }}>POPULAR</div>}
            {cur && <div style={{ position: 'absolute', top: 16, right: 16 }}><Pill tone="sage">Current</Pill></div>}
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>{t.n}</div>
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 40, letterSpacing: -1, lineHeight: 1 }}>{t.p}</div>
            <div style={{ fontSize: 11.5, opacity: 0.7, marginTop: 2, marginBottom: 16 }}>{t.sub}</div>
            {t.feat.map((f, j) => <div key={j} style={{ display: 'flex', gap: 8, fontSize: 12.5, padding: '4px 0', opacity: 0.9 }}><Icon name="check" size={14} color={t.hot ? P.spark : P.sage}/>{f}</div>)}
            <Btn kind={cur ? 'soft' : t.hot ? 'spark' : 'default'} size="md" full style={{ marginTop: 16 }} disabled={cur} onClick={() => upgrade(t.n)}>{cur ? 'Current plan' : plan === 'Free' ? 'Upgrade' : (t.n === 'Free' ? 'Downgrade' : 'Switch')}</Btn>
          </Card>
          );
        })}
      </div>
    </>
  );
}

function SetSparks() {
  const P = window.PX; const { sparks, setSparks, openOverlay, toast } = window.useApp();
  const [autoRefill, setAutoRefill] = React.useState(true);
  const [log, setLog] = React.useState([['Today', 'March class email draft', '−4 ⚡'], ['Today', 'Café Bleu reminder', '−1 ⚡'], ['Mar 11', 'Logo v3 exploration', '−5 ⚡'], ['Mar 10', 'Auto-refill · $20', '+180 ⚡'], ['Mar 8', 'Q1 tax estimate', '−2 ⚡'], ['Mar 6', 'Competitor radar', '−10 ⚡']]);
  const buy = (amount, n) => { setSparks(s => s + n); setLog(l => [['Just now', `Top-up · ${amount}`, `+${n} ⚡`], ...l]); toast(`Added ${n} ⚡ for ${amount}.`, { tone: 'sage', icon: 'zap' }); };
  return (
    <>
      <SetHead t="Sparks" s="Credits Pex spends doing work. They never expire."/>
      <Card pad={20} style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 24 }}>
          <div style={{ flex: 1 }}>
            <Label>Balance</Label>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}><Num size={52}>{sparks}</Num><Spark size={22}/></div>
            <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 4 }}>≈ 11 days left · 13/day · auto-refill {autoRefill ? 'on' : 'off'}</div>
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              {[['$10', 120, '120 ⚡'], ['$20', 270, '270 ⚡ · +bonus', true], ['$50', 750, '750 ⚡']].map((b, i) => (
                <div key={i} onClick={() => buy(b[0], b[1])} style={{ flex: 1, padding: 12, border: `1px solid ${b[3] ? P.spark : P.line}`, borderRadius: 11, background: b[3] ? P.sparkWash : P.card, textAlign: 'center', cursor: 'pointer' }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = P.spark} onMouseLeave={e => e.currentTarget.style.borderColor = b[3] ? P.spark : P.line}>
                  <Num size={22}>{b[0]}</Num><div style={{ fontSize: 10.5, color: P.ink3, marginTop: 2 }}>{b[2]}</div>
                </div>
              ))}
            </div>
          </div>
          <div style={{ width: 1, alignSelf: 'stretch', background: P.line }}/>
          <div style={{ width: 200 }}>
            <Label style={{ marginBottom: 8 }}>Auto-refill</Label>
            <Row label="On · $20 at 20 ⚡"><Toggle on={autoRefill} onClick={() => setAutoRefill(v => !v)}/></Row>
            <div style={{ fontSize: 11, color: P.ink3, marginTop: 10, lineHeight: 1.5 }}>We charge Visa ••4290 when you drop below 20 Sparks. Cancel anytime.</div>
            <span onClick={() => openOverlay('creditGate', { needed: 8, balance: sparks })} style={{ display: 'inline-block', marginTop: 10, fontSize: 11, color: P.spark, cursor: 'pointer', fontWeight: 500 }}>Preview low-balance gate</span>
          </div>
        </div>
      </Card>
      <Card>
        <div style={{ padding: '12px 18px', fontSize: 13, fontWeight: 600, color: P.ink, borderBottom: `1px solid ${P.line}` }}>History</div>
        {log.map((r, i) => (
          <div key={i} style={{ padding: '11px 18px', display: 'grid', gridTemplateColumns: '110px 1fr auto', gap: 12, fontSize: 12.5, color: P.ink, borderBottom: i < log.length - 1 ? `1px solid ${P.line}` : 'none' }}>
            <span style={{ color: P.ink3 }}>{r[0]}</span><span>{r[1]}</span><span style={{ fontFamily: P.mono, color: r[2].startsWith('+') ? P.sage : P.ink, fontWeight: 500 }}>{r[2]}</span>
          </div>
        ))}
      </Card>
    </>
  );
}

function SetPayment() {
  const P = window.PX; const { toast } = window.useApp();
  const [menu, setMenu] = React.useState(false);
  return (
    <>
      <SetHead t="Payment methods" s="For Sparks, your plan, and domain renewals"/>
      <Card pad={18} style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, position: 'relative' }}>
          <div style={{ width: 44, height: 30, background: '#1A1F71', borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11, fontWeight: 700 }}>VISA</div>
          <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 500 }}>Visa ending 4290</div><div style={{ fontSize: 11.5, color: P.ink3 }}>Expires 06/27 · Amara Okafor</div></div>
          <Pill tone="sage">Default</Pill>
          <Icon name="dotsV" size={16} color={P.ink4} style={{ cursor: 'pointer' }} onClick={() => setMenu(v => !v)}/>
          {menu && (
            <div style={{ position: 'absolute', right: 0, top: 30, background: P.card, border: `1px solid ${P.line}`, borderRadius: 10, boxShadow: P.shPop, zIndex: 20, overflow: 'hidden', width: 150 }}>
              {['Edit card', 'Set as default', 'Remove'].map(a => <div key={a} onClick={() => { toast(`${a} — this would open here.`, { icon: 'card' }); setMenu(false); }} style={{ padding: '9px 12px', fontSize: 12.5, color: a === 'Remove' ? P.rose : P.ink, cursor: 'pointer' }} onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>{a}</div>)}
            </div>
          )}
        </div>
      </Card>
      <Btn kind="default" size="md" icon="plus" onClick={() => toast('Add a card — your secure card form would open here.', { icon: 'card' })}>Add payment method</Btn>
    </>
  );
}

function SetBrand() {
  const P = window.PX; const { setBrand } = window.useApp();
  const mode = window.PX_MODE, accent = window.PX_ACCENT, radius = window.PX_RADIUS, font = window.PX_FONT;

  const Swatch = ({ active, onClick, children, title }) => (
    <div onClick={onClick} title={title} style={{ cursor: 'pointer', padding: 2, borderRadius: 999, border: `2px solid ${active ? P.spark : 'transparent'}` }}>{children}</div>
  );
  const Choice = ({ active, onClick, children }) => (
    <div onClick={onClick} style={{ padding: '8px 14px', borderRadius: P.rCtl, border: `1px solid ${active ? P.spark : P.line}`, background: active ? P.sparkWash : P.card, color: active ? P.sparkDim : P.ink2, fontSize: 12.5, fontWeight: 600, cursor: 'pointer' }}>{children}</div>
  );
  const ACCENT_HEX = { orange: '#E5662A', sky: '#3B6CA0', sage: '#3E7A50', plum: '#6B4A86', rose: '#B0463A' };

  return (
    <>
      <SetHead t="Brand & theme" s="How Pexxie looks for your team — same idea a customer's AI-compiled brand uses, simplified to swatches here."/>
      <Card pad={20} style={{ marginBottom: 14 }}>
        <Label style={{ marginBottom: 10 }}>Appearance</Label>
        <div style={{ display: 'flex', gap: 8 }}>
          {[['light', 'sun', 'Light'], ['dark', 'moon', 'Dark']].map(([k, ic, lbl]) => (
            <Choice key={k} active={mode === k} onClick={() => setBrand({ mode: k })}><span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name={ic} size={14}/>{lbl}</span></Choice>
          ))}
        </div>
      </Card>
      <Card pad={20} style={{ marginBottom: 14 }}>
        <Label style={{ marginBottom: 10 }}>Accent</Label>
        <div style={{ display: 'flex', gap: 10 }}>
          {window.PX_ACCENT_KEYS.map(k => (
            <Swatch key={k} active={accent === k} title={k} onClick={() => setBrand({ accent: k })}>
              <div style={{ width: 26, height: 26, borderRadius: 999, background: ACCENT_HEX[k] }}/>
            </Swatch>
          ))}
        </div>
      </Card>
      <Card pad={20} style={{ marginBottom: 14 }}>
        <Label style={{ marginBottom: 10 }}>Radius</Label>
        <div style={{ display: 'flex', gap: 8 }}>
          {window.PX_RADIUS_KEYS.map(k => <Choice key={k} active={radius === k} onClick={() => setBrand({ radius: k })}>{k}</Choice>)}
        </div>
      </Card>
      <Card pad={20} style={{ marginBottom: 18 }}>
        <Label style={{ marginBottom: 10 }}>Typography</Label>
        <div style={{ display: 'flex', gap: 8 }}>
          {window.PX_FONT_KEYS.map(k => <Choice key={k} active={font === k} onClick={() => setBrand({ font: k })}>{k}</Choice>)}
        </div>
      </Card>

      <Label style={{ marginBottom: 10 }}>Live preview</Label>
      <Card pad={20}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink }}>Honest Loaves</div>
          <Pill tone="spark"><Spark size={11}/>142 Sparks</Pill>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
          <Btn kind="primary">Send invoice</Btn>
          <Btn kind="default">Add contact</Btn>
          <Btn kind="soft">Draft with Pex</Btn>
          <Btn kind="ghost">Cancel</Btn>
          <Btn kind="danger">Delete</Btn>
        </div>
        <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
          <Pill tone="sage">Paid</Pill><Pill tone="amber">Due soon</Pill><Pill tone="rose">Overdue</Pill><Pill tone="sky">Draft</Pill>
        </div>
        <Field label="Business name" value="Honest Loaves" style={{ maxWidth: 320 }}/>
      </Card>
    </>
  );
}

function SetIntegrations() {
  const P = window.PX; const { toast } = window.useApp();
  const [ints, setInts] = React.useState([['Stripe', 'Payments & payouts', true, '#635BFF'], ['Google Workspace', 'Email & calendar', true, '#4285F4'], ['Shopify', 'Online store sync', true, '#95BF47'], ['QuickBooks', 'Sync accounting', false, '#2CA01C'], ['Instagram', 'Post & analytics', true, '#E4405F'], ['Slack', 'Team alerts', false, '#4A154B'], ['Cloudflare', 'DNS & domains', true, '#F38020'], ['Zapier', '5,000+ apps', false, '#FF4A00']]);
  const [busy, setBusy] = React.useState(null);
  const connect = (name) => {
    setBusy(name);
    setTimeout(() => { setInts(list => list.map(it => it[0] === name ? [it[0], it[1], true, it[3]] : it)); setBusy(null); toast(`${name} connected.`, { tone: 'sage', icon: 'check' }); }, 900);
  };
  const disconnect = (name) => { setInts(list => list.map(it => it[0] === name ? [it[0], it[1], false, it[3]] : it)); toast(`${name} disconnected.`, { icon: 'x' }); };
  return (
    <>
      <SetHead t="Integrations" s="Pexxie runs your stack so you don't juggle logins"/>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
        {ints.map((it, i) => (
          <Card key={i} pad={16} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: it[3], display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 15, fontWeight: 700 }}>{it[0][0]}</div>
            <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, color: P.ink, fontWeight: 600 }}>{it[0]}</div><div style={{ fontSize: 11.5, color: it[2] ? P.sage : P.ink3 }}>{busy === it[0] ? 'Connecting…' : it[2] ? 'Connected' : it[1]}</div></div>
            {it[2]
              ? <Btn kind="soft" size="sm" onClick={() => disconnect(it[0])}>Disconnect</Btn>
              : <Btn kind="default" size="sm" loading={busy === it[0]} onClick={() => connect(it[0])}>Connect</Btn>}
          </Card>
        ))}
      </div>
    </>
  );
}

function SetSecurity() {
  const P = window.PX; const { toast } = window.useApp();
  const [twofa, setTwofa] = React.useState(true);
  const [alerts, setAlerts] = React.useState(true);
  const [delArm, setDelArm] = React.useState(false);
  return (
    <>
      <SetHead t="Security" s="Keep your business safe"/>
      <Card pad={18}>
        <Row label="Password" sub="Last changed 3 months ago"><Btn kind="default" size="sm" onClick={() => toast('Change password — the flow would open here.', { icon: 'lock' })}>Change</Btn></Row>
        <Row label="Two-factor authentication" sub={twofa ? 'Authenticator app · enabled' : 'Disabled — turn on for safety'}><Toggle on={twofa} onClick={() => { setTwofa(v => !v); toast(twofa ? '2FA turned off.' : '2FA turned on.', { icon: 'shield', tone: twofa ? 'neutral' : 'sage' }); }}/></Row>
        <Row label="Login alerts" sub="Email on new device sign-in"><Toggle on={alerts} onClick={() => setAlerts(v => !v)}/></Row>
        <Row label="Active sessions" sub="2 devices · MacBook, iPhone"><Btn kind="ghost" size="sm" onClick={() => toast('MacBook Pro · Brooklyn · now · iPhone · Brooklyn · 2h ago', { icon: 'shield' })}>View</Btn></Row>
      </Card>
      <Card pad={18} style={{ marginTop: 14, borderColor: P.roseTint }}>
        <div style={{ fontSize: 13.5, fontWeight: 600, color: P.rose, marginBottom: 8 }}>Danger zone</div>
        <Row label="Delete workspace" sub={delArm ? 'This is permanent — click again to confirm.' : 'Permanently removes Honest Loaves and all data'}>
          <Btn kind="danger" size="sm" onClick={() => { if (!delArm) { setDelArm(true); } else { setDelArm(false); toast('Workspace deletion is disabled in this prototype.', { tone: 'rose', icon: 'alert' }); } }}>{delArm ? 'Confirm delete' : 'Delete'}</Btn>
        </Row>
      </Card>
    </>
  );
}

function SetData() {
  const P = window.PX; const { toast } = window.useApp();
  const [busy, setBusy] = React.useState(null);
  const exportOne = (label) => { setBusy(label); setTimeout(() => { setBusy(null); toast(`${label} ready — download started.`, { tone: 'sage', icon: 'download' }); }, 1000); };
  return (
    <>
      <SetHead t="Data & export" s="Your data is yours. Take it whenever."/>
      <Card pad={18}>
        {[['Export everything', 'Full ZIP — contacts, money, files, site', 'download'], ['Export contacts (CSV)', '428 people', 'users'], ['Export transactions (CSV)', '847 records', 'activity'], ['Download invoices (PDF)', 'All 28 invoices', 'receipt']].map((r, i) => (
          <Row key={i} label={r[0]} sub={r[1]}><Btn kind="default" size="sm" icon={r[2]} loading={busy === r[0]} onClick={() => exportOne(r[0])}>Export</Btn></Row>
        ))}
      </Card>
    </>
  );
}
