// ════════════ OVERLAYS · drawers, modals, toasts, create menu ════════════
const { Icon, Spark, Pex, Avatar, Card, Btn, Pill, Label, Num, Field, Toggle, Select, TextArea } = window;

// ── Primitives ───────────────────────────────────────────────
window.Modal = function Modal({ title, sub, children, foot, w = 540, onClose }) {
  const P = window.PX;
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(27,25,21,0.34)', backdropFilter: 'blur(2px)', zIndex: 180, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.sans, padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: w, maxHeight: '88vh', background: P.card, borderRadius: 16, border: `1px solid ${P.line}`, boxShadow: P.shPop, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: '16px 20px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 22, color: P.ink, letterSpacing: -0.3 }}>{title}</div>
            {sub && <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 2 }}>{sub}</div>}
          </div>
          <div onClick={onClose} style={{ cursor: 'pointer', color: P.ink3, padding: 4, borderRadius: 7 }}><Icon name="x" size={18}/></div>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>{children}</div>
        {foot && <div style={{ padding: '14px 20px', borderTop: `1px solid ${P.line}`, display: 'flex', justifyContent: 'flex-end', gap: 8, background: P.canvas }}>{foot}</div>}
      </div>
    </div>
  );
};

window.Drawer = function Drawer({ title, sub, tag, children, foot, w = 560, onClose }) {
  const P = window.PX;
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(27,25,21,0.34)', backdropFilter: 'blur(2px)', zIndex: 180, display: 'flex', justifyContent: 'flex-end', fontFamily: P.sans }}>
      <div onClick={e => e.stopPropagation()} style={{ width: w, height: '100%', background: P.card, borderLeft: `1px solid ${P.line}`, boxShadow: P.shPop, display: 'flex', flexDirection: 'column', animation: 'pxslide .2s ease' }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${P.line}`, display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ flex: 1 }}>
            {tag && <div style={{ marginBottom: 6 }}>{tag}</div>}
            <div style={{ fontFamily: P.serif, fontStyle: 'italic', fontSize: 24, color: P.ink, letterSpacing: -0.3, lineHeight: 1.1 }}>{title}</div>
            {sub && <div style={{ fontSize: 12.5, color: P.ink3, marginTop: 4 }}>{sub}</div>}
          </div>
          <div onClick={onClose} style={{ cursor: 'pointer', color: P.ink3, padding: 4 }}><Icon name="x" size={18}/></div>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: 22 }}>{children}</div>
        {foot && <div style={{ padding: '14px 22px', borderTop: `1px solid ${P.line}`, display: 'flex', gap: 8, background: P.canvas }}>{foot}</div>}
      </div>
    </div>
  );
};

// ── Toaster ──────────────────────────────────────────────────
window.Toaster = function Toaster() {
  const { toasts } = window.useApp(); const P = window.PX;
  return (
    <div style={{ position: 'fixed', bottom: 20, left: '50%', transform: 'translateX(-50%)', zIndex: 300, display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center', fontFamily: P.sans }}>
      {toasts.map(t => (
        <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 10, background: P.ink, color: '#fff', padding: '10px 16px', borderRadius: 11, boxShadow: P.shLg, fontSize: 13, animation: 'pxpop .2s ease', maxWidth: 460 }}>
          {t.icon && <span style={{ width: 22, height: 22, borderRadius: 22, background: t.tone === 'sage' ? P.sage : t.tone === 'rose' ? P.rose : 'rgba(255,255,255,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={t.icon} size={13} color="#fff" stroke={2.5}/></span>}
          <span>{t.msg}</span>
          {t.action && <span style={{ color: '#FFC58A', fontWeight: 600, cursor: 'pointer', marginLeft: 4 }}>{t.action}</span>}
        </div>
      ))}
    </div>
  );
};

// ── Dispatcher ───────────────────────────────────────────────
window.Overlays = function Overlays() {
  const { overlay, closeOverlay } = window.useApp();
  if (!overlay) return null;
  const map = {
    create: CreateMenu, proposalPreview: ProposalPreview, compose: ComposeEmail,
    addContact: AddContact, addEvent: AddEvent, askPex: AskPexModal, creditGate: CreditGate,
  };
  const C = map[overlay.type];
  return C ? <C {...overlay.props} onClose={closeOverlay}/> : null;
};

// ── Create menu ──────────────────────────────────────────────
function CreateMenu({ onClose }) {
  const P = window.PX; const { go, openOverlay } = window.useApp();
  const go2 = (r) => { onClose(); go(r); };
  const items = [
    { icon: 'receipt', t: 'Invoice', s: 'Bill a customer', act: () => go2('money/invoices/new') },
    { icon: 'user', t: 'Contact', s: 'Add someone to People', act: () => openOverlay('addContact') },
    { icon: 'mail', t: 'Email', s: 'Compose a message', act: () => openOverlay('compose') },
    { icon: 'calendar', t: 'Event', s: 'Schedule something', act: () => openOverlay('addEvent') },
    { icon: 'fileText', t: 'Bill / expense', s: 'Record money out', act: () => go2('money/bills') },
    { icon: 'layout', t: 'Web page', s: 'Add to your site', act: () => go2('website/pages') },
    { icon: 'megaphone', t: 'Campaign', s: 'Marketing blast', act: () => go2('marketing/campaigns') },
    { icon: 'sparkles', t: 'Ask Pex', s: 'Describe an outcome', spark: true, act: () => openOverlay('askPex') },
  ];
  return (
    <window.Modal title="Create" sub="What would you like to make?" w={520} onClose={onClose}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {items.map((it, i) => (
          <div key={i} onClick={it.act} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 13, borderRadius: 11, border: `1px solid ${it.spark ? P.sparkTint : P.line}`, background: it.spark ? P.sparkWash : P.card, cursor: 'pointer' }}
            onMouseEnter={e => e.currentTarget.style.background = it.spark ? P.sparkWash : P.hover} onMouseLeave={e => e.currentTarget.style.background = it.spark ? P.sparkWash : P.card}>
            {it.spark ? <Pex size={32}/> : <div style={{ width: 32, height: 32, borderRadius: 9, background: P.sunk, color: P.ink2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={it.icon} size={16}/></div>}
            <div><div style={{ fontSize: 13.5, fontWeight: 600, color: P.ink }}>{it.t}</div><div style={{ fontSize: 11, color: P.ink3 }}>{it.s}</div></div>
          </div>
        ))}
      </div>
    </window.Modal>
  );
}

// ── Proposal preview (drawer) — shows the actual drafted artifact ──
function ProposalPreview({ proposal, onClose }) {
  const P = window.PX; const { actProposal } = window.useApp();
  const p = proposal || {};
  const body = {
    p1: { kind: 'email', to: 'marc@cafebleu.nyc', subj: 'Gentle reminder · Invoice #1024', text: ['Hi Marc,', 'Hope the bakery\'s treating you well! Just a friendly note that invoice #1024 ($1,420) has been open since March 1st. No rush at all — I know February was quiet for everyone.', 'Whenever you get a sec, here\'s the payment link. And thank you, as always, for being one of our favorite wholesale partners.', 'Warmly,\nAmara'] },
    p2: { kind: 'diff', changes: [['Since 2018', 'Since 2019'], ['our two bakers', 'our team of five bakers'], ['a single oven', 'two stone-deck ovens']] },
    p3: { kind: 'email', to: 'past customers', subj: 'March sourdough class — seats are open', text: ['Our March class is open, and like always it\'s a small group — six seats, one oven, three hours.', 'You\'ll mix, shape, and score your own loaf, then take home a starter and the recipe.', 'Wednesday March 26, 6pm. $80. Grab your seat below.'] },
  }[p.id] || { kind: 'note', text: ['Pex has prepared this task and will execute it on approval.'] };
  const { toast } = window.useApp();
  const [editing, setEditing] = React.useState(false);
  const [email, setEmail] = React.useState(() => body.kind === 'email' ? { to: body.to, subj: body.subj, text: body.text.join('\n\n') } : { to: '', subj: '', text: '' });
  const [diff, setDiff] = React.useState(() => body.kind === 'diff' ? body.changes.map(() => true) : []);
  const inp = { border: `1px solid ${P.lineStrong}`, borderRadius: 8, padding: '7px 9px', fontSize: 13, color: P.ink, fontFamily: P.sans, outline: 'none', width: '100%', background: P.card };

  return (
    <window.Drawer onClose={onClose}
      tag={<div style={{ display: 'flex', gap: 6 }}><Pill tone={p.tone}>{p.tag}</Pill>{p.urgent && <Pill tone="rose">urgent</Pill>}<Pill tone="spark"><Spark size={10}/>{p.cost} ⚡</Pill></div>}
      title={p.title} sub={p.ctx}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Close</Btn><div style={{ flex: 1 }}/><Btn kind={editing ? 'primary' : 'default'} size="md" icon={editing ? 'check' : 'pencil'} onClick={() => { if (editing) toast('Edits saved to the draft.', { icon: 'check' }); setEditing(v => !v); }}>{editing ? 'Done' : 'Edit'}</Btn><Btn kind="spark" size="md" icon="check" onClick={() => { actProposal(p.id, 'approved'); onClose(); }}>Approve · {p.cost} ⚡</Btn></>}>
      <div style={{ display: 'flex', gap: 10, marginBottom: 16, padding: 12, background: P.sparkWash, borderRadius: 11, border: `1px solid ${P.sparkTint}` }}>
        <Pex size={28}/><div style={{ fontSize: 12.5, color: P.ink2, lineHeight: 1.5 }}>{editing ? 'Editing the draft — change anything, then Done. Nothing sends until you approve.' : "Here's exactly what I'll do. Nothing happens until you approve — and you can edit any of it first."}</div>
      </div>
      {body.kind === 'email' && (
        <Card pad={0}>
          <div style={{ padding: '12px 16px', borderBottom: `1px solid ${P.line}`, fontSize: 12.5 }}>
            {editing ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><span style={{ color: P.ink3, width: 44 }}>To</span><input value={email.to} onChange={e => setEmail(s => ({ ...s, to: e.target.value }))} style={inp}/></div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><span style={{ color: P.ink3, width: 44 }}>Subject</span><input value={email.subj} onChange={e => setEmail(s => ({ ...s, subj: e.target.value }))} style={inp}/></div>
              </div>
            ) : (
              <>
                <div style={{ display: 'flex', gap: 8, padding: '2px 0' }}><span style={{ color: P.ink3, width: 44 }}>To</span><span style={{ color: P.ink }}>{email.to}</span></div>
                <div style={{ display: 'flex', gap: 8, padding: '2px 0' }}><span style={{ color: P.ink3, width: 44 }}>Subject</span><span style={{ color: P.ink, fontWeight: 600 }}>{email.subj}</span></div>
              </>
            )}
          </div>
          <div style={{ padding: 16 }}>
            {editing
              ? <textarea value={email.text} onChange={e => setEmail(s => ({ ...s, text: e.target.value }))} rows={10} style={{ ...inp, resize: 'vertical', lineHeight: 1.6 }}/>
              : email.text.split('\n\n').map((t, i) => <p key={i} style={{ fontSize: 13.5, color: P.ink, lineHeight: 1.6, margin: '0 0 12px', whiteSpace: 'pre-line' }}>{t}</p>)}
          </div>
        </Card>
      )}
      {body.kind === 'diff' && (
        <Card pad={16}>
          <Label style={{ marginBottom: 10 }}>Proposed edits · About page{editing ? ' · toggle which to apply' : ''}</Label>
          {body.changes.map((c, i) => (
            <div key={i} style={{ padding: '10px 0', borderBottom: i < body.changes.length - 1 ? `1px solid ${P.line}` : 'none', display: 'flex', gap: 10, alignItems: 'flex-start', opacity: diff[i] ? 1 : 0.4 }}>
              {editing && <window.Check on={diff[i]} onClick={() => setDiff(d => d.map((v, j) => j === i ? !v : v))}/>}
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: P.rose, textDecoration: 'line-through', marginBottom: 3 }}>− {c[0]}</div>
                <div style={{ fontSize: 13, color: P.sage }}>+ {c[1]}</div>
              </div>
            </div>
          ))}
        </Card>
      )}
      {body.kind === 'note' && <Card pad={16}><div style={{ fontSize: 13.5, color: P.ink2, lineHeight: 1.6 }}>{body.text[0]}</div></Card>}
    </window.Drawer>
  );
}

// ── Compose email (modal) ────────────────────────────────────
function ComposeEmail({ onClose, to: initTo, subject: initSubject }) {
  const P = window.PX; const { toast, go } = window.useApp();
  const [to, setTo] = React.useState(initTo || '');
  const [subject, setSubject] = React.useState(initSubject || '');
  const [body, setBody] = React.useState('');
  const draftWithPex = () => setBody('Hi — just following up on our last conversation. Wanted to make sure everything is on track, and to see if there is anything you need from my end. Happy to hop on a quick call if that is easier.\n\nWarmly,\nAmara');
  const send = () => {
    if (!to || !/.+@.+\..+/.test(to)) { toast('Add a valid recipient email.', { tone: 'rose', icon: 'alert' }); return; }
    if (!subject.trim()) { toast('Add a subject.', { tone: 'rose', icon: 'alert' }); return; }
    window.PXMail.set(s => ({ ...s, mails: [{ id: window.pxid('m'), box: 'sent', f: 'To: ' + to, e: to, s: subject, p: (body || '(no message)').slice(0, 72), t: 'Just now', tone: 'sage', body: (body || '(no message)').split('\n\n') }, ...(s.mails || [])] }));
    onClose(); toast('Message sent — it’s in your Sent folder.', { tone: 'sage', icon: 'check', action: 'View' });
    go('mail');
  };
  const saveDraft = () => {
    window.PXMail.set(s => ({ ...s, mails: [{ id: window.pxid('m'), box: 'drafts', f: 'To: ' + (to || '—'), e: to || '', s: subject || '(no subject)', p: (body || '(empty draft)').slice(0, 72), t: 'Just now', tone: 'neutral', body: (body || '(empty draft)').split('\n\n') }, ...(s.mails || [])] }));
    onClose(); toast('Saved to Drafts.', { icon: 'check' });
  };
  return (
    <window.Modal title="New message" sub="From amara@honestloaves.com" w={620} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" icon="sparkles" onClick={draftWithPex}>Pex: write it for me · 1 ⚡</Btn><div style={{ flex: 1 }}/><Btn kind="default" size="md" onClick={saveDraft}>Save draft</Btn><Btn kind="spark" size="md" icon="send" onClick={send}>Send</Btn></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 0', borderBottom: `1px solid ${P.line}` }}>
          <span style={{ fontSize: 12.5, color: P.ink3, width: 56 }}>To</span>
          <input value={to} onChange={e => setTo(e.target.value)} placeholder="name@email.com" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 14, color: P.ink, fontFamily: P.sans }}/>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '11px 0', borderBottom: `1px solid ${P.line}` }}>
          <span style={{ fontSize: 12.5, color: P.ink3, width: 56 }}>Subject</span>
          <input value={subject} onChange={e => setSubject(e.target.value)} placeholder="Subject" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 14, color: P.ink, fontFamily: P.sans }}/>
        </div>
        <textarea value={body} onChange={e => setBody(e.target.value)} placeholder="Write your message… or let Pex draft it." style={{ border: 'none', outline: 'none', background: 'transparent', resize: 'none', minHeight: 200, fontSize: 14, color: P.ink, fontFamily: P.sans, lineHeight: 1.6, padding: '14px 0' }}/>
      </div>
    </window.Modal>
  );
}

// ── Add contact (modal) ──────────────────────────────────────
function AddContact({ onClose }) {
  const P = window.PX; const { toast, go } = window.useApp();
  const [first, setFirst] = React.useState('');
  const [last, setLast] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [co, setCo] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [tags, setTags] = React.useState([]);
  const [paste, setPaste] = React.useState('');
  const [enriching, setEnriching] = React.useState(false);
  const toggleTag = (t) => setTags(ts => ts.includes(t) ? ts.filter(x => x !== t) : [...ts, t]);
  const enrich = () => {
    if (!paste.trim()) { toast('Paste a website or LinkedIn URL first.', { tone: 'rose', icon: 'alert' }); return; }
    setEnriching(true);
    setTimeout(() => {
      // Simulate pulling details from the pasted source.
      const host = (paste.match(/([a-z0-9-]+)\.(com|co|nyc|org|io)/i) || [])[1] || 'company';
      setFirst(f => f || 'Jordan'); setLast(l => l || 'Rivera');
      setCo(c => c || host.replace(/(^|-)([a-z])/g, (_, a, b) => (a ? ' ' : '') + b.toUpperCase()).trim());
      setEmail(e => e || `hello@${host}.com`);
      setEnriching(false);
      toast('Pulled details from the link — review and adjust.', { tone: 'sage', icon: 'sparkles' });
    }, 900);
  };
  const add = () => {
    const name = `${first} ${last}`.trim();
    if (!name) { toast('Add a name first.', { tone: 'rose', icon: 'alert' }); return; }
    if (!email || !/.+@.+\..+/.test(email)) { toast('Add a valid email.', { tone: 'rose', icon: 'alert' }); return; }
    const c = { id: window.pxid('c'), name, co: co.trim() || '—', role: 'Contact', tags: tags.length ? tags : ['new'], deal: 0, last: 'Today', tone: 'sky', signal: 'Added just now', email: email.trim(), phone: phone.trim(), ltv: 0, rel: 50 };
    window.PXPeople.addContact(c);
    onClose(); toast(`${name} added to People.`, { tone: 'sage', icon: 'check' });
    go('people');
  };
  return (
    <window.Modal title="Add a contact" w={540} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="primary" size="md" onClick={add}>Add contact</Btn></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="First name" placeholder="Jordan" value={first} onChange={setFirst}/>
        <Field label="Last name" placeholder="Rivera" value={last} onChange={setLast}/>
        <Field label="Email" placeholder="jordan@email.com" icon="mail" value={email} onChange={setEmail} style={{ gridColumn: '1 / -1' }}/>
        <Field label="Company" placeholder="Optional" icon="building" value={co} onChange={setCo}/>
        <Field label="Phone" placeholder="Optional" icon="phone" value={phone} onChange={setPhone}/>
      </div>
      <div style={{ marginTop: 14 }}><Label style={{ marginBottom: 6 }}>Tags</Label><div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{['wholesale', 'class', 'press', 'vip'].map((t) => <Pill key={t} tone="neutral" on={tags.includes(t)} onClick={() => toggleTag(t)} style={{ padding: '4px 10px' }}>#{t}</Pill>)}</div></div>
      <div style={{ marginTop: 16, padding: 12, background: P.sparkWash, borderRadius: 11, border: `1px solid ${P.sparkTint}` }}>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 10 }}>
          <Pex size={26}/><div style={{ flex: 1, fontSize: 12.5, color: P.ink2 }}>Paste a website or LinkedIn and I'll fill the rest.</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input value={paste} onChange={e => setPaste(e.target.value)} placeholder="https://…" style={{ flex: 1, border: `1px solid ${P.sparkTint}`, borderRadius: 8, padding: '7px 10px', fontSize: 13, color: P.ink, fontFamily: P.sans, outline: 'none', background: P.card }}/>
          <Btn kind="spark" size="sm" icon="sparkles" loading={enriching} onClick={enrich}>Autofill</Btn>
        </div>
      </div>
    </window.Modal>
  );
}

// Day columns + hour rows mirror the Calendar grid so a new event lands in a real cell.
const CAL_DAYS = ['Mon 10', 'Tue 11', 'Wed 12', 'Thu 13', 'Fri 14', 'Sat 15', 'Sun 16'];
const CAL_TIMES = ['8:00', '9:00', '10:00', '11:00', '12:00', '1:00', '2:00', '3:00', '4:00'];
function AddEvent({ onClose }) {
  const P = window.PX; const { toast, go } = window.useApp();
  const [title, setTitle] = React.useState('');
  const [day, setDay] = React.useState('2');   // Wed (today)
  const [time, setTime] = React.useState('1'); // 9:00
  const [invite, setInvite] = React.useState('');
  const [prep, setPrep] = React.useState(true);
  const add = () => {
    if (!title.trim()) { toast('Give the event a title.', { tone: 'rose', icon: 'alert' }); return; }
    const col = Number(day), row = Number(time);
    const dayShort = CAL_DAYS[col].split(' ')[0];
    const ev = { t: title.trim(), tone: 'spark', prep, detail: {
      time: `${CAL_TIMES[row]} · ${dayShort}`, title: title.trim(),
      who: invite.trim() ? invite.trim() : 'You',
      lines: [invite.trim() ? `With ${invite.trim()}` : 'Added from the New event dialog', prep ? 'Pex will prep talking points beforehand' : 'No prep requested'] } };
    window.PXCalendar.set(s => ({ ...s, events: { ...(s.events || {}), [`${row}-${col}`]: ev } }));
    onClose(); toast(`“${title.trim()}” added to ${dayShort} at ${CAL_TIMES[row]}.`, { tone: 'sage', icon: 'check' });
    go('calendar');
  };
  return (
    <window.Modal title="New event" w={520} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="primary" size="md" onClick={add}>Add event</Btn></>}>
      <Field label="Title" placeholder="Coffee with…" value={title} onChange={setTitle} style={{ marginBottom: 14 }}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Select label="Day" value={day} onChange={setDay} options={CAL_DAYS.map((d, i) => ({ v: String(i), label: d }))}/>
        <Select label="Time" value={time} onChange={setTime} options={CAL_TIMES.map((t, i) => ({ v: String(i), label: t }))}/>
      </div>
      <div style={{ marginTop: 14 }}><Field label="Invite (optional)" placeholder="Name or email" icon="at" value={invite} onChange={setInvite}/></div>
      <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 16, fontSize: 13, color: P.ink2, cursor: 'pointer' }}><Toggle on={prep} size="sm" onClick={() => setPrep(v => !v)}/>Let Pex prep talking points beforehand</label>
    </window.Modal>
  );
}

// ── Low-Spark credit gate ─────────────────────────────────────
function CreditGate({ needed = 5, balance = 0, onClose }) {
  const P = window.PX; const { go, setSparks, toast } = window.useApp();
  const short = Math.max(0, needed - balance);
  const buy = (amount, sparks) => { setSparks(s => s + sparks); onClose(); toast(`Topped up ${sparks} ⚡ for ${amount}. Pex is picking it back up.`, { tone: 'sage', icon: 'zap' }); };
  return (
    <window.Modal title="Not enough Sparks" sub="This action costs more than you have on hand." w={460} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Not now</Btn><div style={{ flex: 1 }}/><Btn kind="default" size="md" icon="sliders" onClick={() => { onClose(); go('settings/sparks'); }}>More options</Btn></>}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, background: P.sparkWash, borderRadius: 12, border: `1px solid ${P.sparkTint}`, marginBottom: 16 }}>
        <Spark size={26}/>
        <div>
          <div style={{ fontSize: 13.5, color: P.ink, fontWeight: 600 }}>Needs {needed} ⚡ · you have {balance} ⚡</div>
          <div style={{ fontSize: 12, color: P.ink3, marginTop: 2 }}>Top up {short} more Sparks and Pex will pick this back up automatically.</div>
        </div>
      </div>
      <Label style={{ marginBottom: 8 }}>Quick top-up</Label>
      <div style={{ display: 'flex', gap: 8 }}>
        {[['$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={20}>{b[0]}</Num><div style={{ fontSize: 10.5, color: P.ink3, marginTop: 2 }}>{b[2]}</div>
          </div>
        ))}
      </div>
    </window.Modal>
  );
}

function AskPexModal({ onClose }) {
  const P = window.PX; const { go, toast } = window.useApp();
  const [prompt, setPrompt] = React.useState('');
  const submit = (text) => {
    const t = (text != null ? text : prompt).trim();
    if (!t) { toast('Describe what you’d like Pex to do.', { tone: 'rose', icon: 'alert' }); return; }
    window.PXPex.setDraftPrompt(t);
    onClose(); go('pex');
  };
  return (
    <window.Modal title="Ask Pex" sub="Describe the outcome you want. Pex scopes it and quotes in Sparks." w={560} onClose={onClose}
      foot={<><Btn kind="ghost" size="md" onClick={onClose}>Cancel</Btn><div style={{ flex: 1 }}/><Btn kind="spark" size="md" icon="arrowRight" onClick={() => submit()}>Send to Pex</Btn></>}>
      <textarea autoFocus value={prompt} onChange={e => setPrompt(e.target.value)} placeholder="e.g. Design a loyalty punch-card I can print, and an email announcing it to my regulars." style={{ width: '100%', border: `1px solid ${P.lineStrong}`, borderRadius: 11, padding: 14, minHeight: 120, fontSize: 14, color: P.ink, fontFamily: P.sans, lineHeight: 1.6, outline: 'none', resize: 'none' }}/>
      <Label style={{ margin: '16px 0 8px' }}>Or start from something Pex noticed</Label>
      {['Double class capacity — you keep selling out', 'A summer wholesale push to 5 new cafés', 'Refresh the logo across everything'].map((s, i) => (
        <div key={i} onClick={() => submit(s)} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 9, border: `1px solid ${P.line}`, marginBottom: 6, cursor: 'pointer', fontSize: 13, color: P.ink }}
          onMouseEnter={e => e.currentTarget.style.background = P.hover} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
          <Spark size={13}/><span style={{ flex: 1 }}>{s}</span><Icon name="arrowRight" size={14} color={P.ink4}/>
        </div>
      ))}
    </window.Modal>
  );
}
