/* Team side of agency accounts: the list with client counts, creating one
   (the password is shown once), resetting a password, deleting; assigning a
   lead to an agency; and the keys the team enters for one client. */

/* How many full reports an agency may start without paying. */
function AllowanceControl({ agency, busy, onSave }) {
  const a = agency.allowance || { free_reports: 0, used: 0, remaining: 0 };
  const [value, setValue] = React.useState(String(a.free_reports));
  React.useEffect(() => { setValue(String(a.free_reports)); }, [a.free_reports]);
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--fg-muted)' }} title="Full reports this agency can start without paying">
      free reports
      <input value={value} onChange={(e) => setValue(e.target.value.replace(/[^0-9]/g, ''))} inputMode="numeric"
        style={{ ...inputStyleAdmin(false), width: 54, padding: '6px 8px', fontSize: 13, textAlign: 'center' }} />
      <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>{a.used} used</span>
      {String(a.free_reports) !== value && <button style={smallBtn('accent')} disabled={busy} onClick={() => onSave(parseInt(value || '0', 10))}>Save</button>}
    </label>);
}

function AgenciesSection({ token, agencies, reports, unclaimed, onChanged, onExpired }) {
  const [name, setName] = React.useState('');
  const [website, setWebsite] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [busy, setBusy] = React.useState('');
  const [flash, setFlash] = React.useState(null);
  const act = async (action, extra) => {
    setBusy(action); setFlash(null);
    try {
      const d = await adminCall('/api/admin', token, { action, ...(extra || {}) });
      if (d.status === 401) { onExpired(); return; }
      if (!d.ok) setFlash({ tone: 'warn', text: d.message || d.error || `${action} failed.` });
      else if (d.password) {
        setFlash({ tone: 'good', text: `${d.agency.name}: login ${d.agency.slug}${d.agency.email ? ` or ${d.agency.email}` : ''}, password ${d.password} — shown once; they sign in at /agency/admin/.${(d.claimed || []).length ? ` Filed ${d.claimed.length} report${d.claimed.length === 1 ? '' : 's'} under it.` : ''}`, copy: d.password });
        setName(''); setWebsite(''); setEmail('');
      }
      onChanged();
    } catch (e) { setFlash({ tone: 'warn', text: 'Could not reach the server.' }); }
    setBusy('');
  };
  return (
    <div style={{ marginTop: 34 }}>
      <h2 className="display" style={{ fontSize: 'clamp(20px,4vw,28px)', margin: '0 0 6px' }}>Agencies</h2>
      <p style={{ fontSize: 14.5, color: 'var(--fg-muted)', margin: '0 0 14px', maxWidth: 680, lineHeight: 1.6 }}>
        An agency account sees the clients it brought, hands out their access codes, runs benchmarks and
        re-scans itself, and keeps its own API keys for the engines Lojo does not pay for. Out of the box
        everything runs on Claude; ChatGPT, Perplexity, Gemini and Google AI Overviews need the agency's keys.
      </p>
      {flash && <div style={{ marginBottom: 12, fontSize: 13.5, color: `var(--${flash.tone})`, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
        <span>{flash.text}</span>{flash.copy && <CopyButton text={flash.copy} label="Copy password" />}
      </div>}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
        {agencies.length === 0 && <div style={{ fontSize: 13.5, color: 'var(--fg-subtle)' }}>No agency accounts yet.</div>}
        {agencies.map((a) =>
        <div key={a.slug} style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', padding: '12px 16px',
          borderRadius: 'var(--r-lg)', background: 'var(--navy-2)', border: '1px solid var(--line)' }}>
          <div style={{ flex: '1 1 220px', minWidth: 0 }}>
            <div style={{ fontSize: 15.5, fontWeight: 600 }}>{a.name} <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>{a.slug}</span></div>
            <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{[a.website, a.email].filter(Boolean).join(' · ')} · {a.clients} client{a.clients === 1 ? '' : 's'}</div>
          </div>
          <AllowanceControl agency={a} busy={!!busy} onSave={(n) => act('agency-allowance', { agency_slug: a.slug, free_reports: n })} />
          <button style={smallBtn()} disabled={!!busy} onClick={() => { if (window.confirm(`Reset ${a.name}'s password? The old one stops working.`)) act('agency-reset-password', { agency_slug: a.slug }); }}>Reset password</button>
          <button style={smallBtn('crit')} disabled={!!busy} onClick={() => { if (window.confirm(`Delete the ${a.name} account? Its clients stay, unassigned; its keys are deleted.`)) act('agency-delete', { agency_slug: a.slug }); }}>Delete</button>
        </div>)}
      </div>
      {(unclaimed || []).length > 0 &&
      <div style={{ marginBottom: 16 }}>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--warn)', marginBottom: 8 }}>Ran reports, no account yet</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {unclaimed.map((u) =>
          <div key={u.suggested_slug} style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', padding: '12px 16px',
            borderRadius: 'var(--r-lg)', background: 'var(--navy-2)', border: '1px solid color-mix(in oklab, var(--warn) 35%, transparent)' }}>
            <div style={{ flex: '1 1 220px', minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>{u.name || u.suggested_slug}</div>
              <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{[u.website, u.email].filter(Boolean).join(' · ')} · {u.clients.length} report{u.clients.length === 1 ? '' : 's'}: {u.clients.map((c) => c.client).join(', ')}</div>
            </div>
            <button style={smallBtn('accent')} disabled={!!busy} onClick={() => act('agency-create', { name: u.name || u.suggested_slug, website: u.website, email: u.email })}>Create their account</button>
          </div>)}
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--fg-subtle)', marginTop: 6 }}>Creating the account files these reports under it. Agencies can also sign up themselves at /agency/admin/ and the same filing happens.</div>
      </div>}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
        <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Agency name" style={{ ...inputStyleAdmin(false), width: 200, padding: '9px 11px', fontSize: 14 }} />
        <input value={website} onChange={(e) => setWebsite(e.target.value)} placeholder="agency-website.com" style={{ ...inputStyleAdmin(false), width: 200, padding: '9px 11px', fontSize: 14 }} />
        <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="login email (optional)" style={{ ...inputStyleAdmin(false), width: 220, padding: '9px 11px', fontSize: 14 }} />
        <button style={smallBtn('accent')} disabled={!!busy || !(name.trim() || website.trim())} onClick={() => act('agency-create', { name: name.trim(), website: website.trim(), email: email.trim() })}>
          {busy === 'agency-create' ? 'Creating…' : 'Create agency account'}
        </button>
      </div>
    </div>);
}

function AgencyAssignPanel({ slug, token, report, agencies, onChanged, onExpired }) {
  const [busy, setBusy] = React.useState(false);
  const current = report.agency_slug || '';
  const change = async (value) => {
    setBusy(true);
    const d = await adminCall('/api/admin', token, { action: 'assign-agency', slug, agency_slug: value });
    if (d.status === 401) onExpired();
    setBusy(false); onChanged();
  };
  return (
    <Panel title="Agency account">
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', fontSize: 13.5, color: 'var(--fg-muted)' }}>
        <span>{current ? `Filed under ${current}: that agency sees this client in its workspace.` : 'Not filed under an agency account.'}</span>
        <select value={current} disabled={busy} onChange={(e) => change(e.target.value)} style={{ ...inputStyleAdmin(false), width: 220, padding: '8px 10px', fontSize: 13.5 }}>
          <option value="">— no agency —</option>
          {agencies.map((a) => <option key={a.slug} value={a.slug}>{a.name}</option>)}
        </select>
      </div>
    </Panel>);
}

const KEY_ENGINE_LABELS = { openai: 'OpenAI (ChatGPT)', perplexity: 'Perplexity', gemini: 'Google Gemini', serpapi: 'SerpApi (Google AI Overviews)' };

/* The same form in both places: the team's per-client keys and the agency's own keys. */
function EngineKeysForm({ tails, onSave, busy, note }) {
  const [values, setValues] = React.useState({});
  const [clear, setClear] = React.useState({});
  const ids = Object.keys(KEY_ENGINE_LABELS);
  const dirty = ids.some((e) => (values[e] || '').trim() || clear[e]);
  const save = () => {
    const keys = {};
    ids.forEach((e) => { if (clear[e]) keys[e] = ''; else if ((values[e] || '').trim()) keys[e] = values[e].trim(); });
    onSave(keys); setValues({}); setClear({});
  };
  return (
    <div>
      {note && <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6, marginBottom: 10 }}>{note}</div>}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 8 }}>
        {ids.map((e) =>
        <label key={e} style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12.5, color: 'var(--fg-subtle)' }}>
          <span>{KEY_ENGINE_LABELS[e]} {tails && tails[e] ? <span style={{ color: 'var(--good)' }}>· set, ends {tails[e]}</span> : <span>· not set</span>}</span>
          <div style={{ display: 'flex', gap: 6 }}>
            <input type="password" autoComplete="off" value={values[e] || ''} disabled={!!clear[e]}
              onChange={(ev) => setValues((v) => ({ ...v, [e]: ev.target.value }))}
              placeholder={tails && tails[e] ? 'paste a new key to replace' : 'paste the API key'}
              style={{ ...inputStyleAdmin(false), padding: '8px 10px', fontSize: 13 }} />
            {tails && tails[e] && <button type="button" onClick={() => setClear((c) => ({ ...c, [e]: !c[e] }))}
              style={{ ...smallBtn(clear[e] ? 'crit' : undefined), padding: '6px 10px', fontSize: 12 }}>{clear[e] ? 'Keep' : 'Remove'}</button>}
          </div>
        </label>)}
      </div>
      <div style={{ marginTop: 10 }}>
        <button style={smallBtn('accent')} disabled={busy || !dirty} onClick={save}>{busy ? 'Saving…' : 'Save keys'}</button>
      </div>
    </div>);
}

function ClientKeysPanel({ slug, token, report, onChanged, onExpired }) {
  const [busy, setBusy] = React.useState(false);
  const [flash, setFlash] = React.useState('');
  const tails = ((report.connections || {}).engine_keys || {}).tails || {};
  const save = async (keys) => {
    setBusy(true); setFlash('');
    const d = await adminCall('/api/admin', token, { action: 'engine-keys', slug, keys });
    if (d.status === 401) { onExpired(); return; }
    if (!d.ok) setFlash(d.message || d.error || 'Could not save.');
    setBusy(false); onChanged();
  };
  return (
    <Panel title={`Engine keys for this client${Object.keys(tails).length ? ` · ${Object.keys(tails).length} set` : ''}`}>
      {flash && <div style={{ marginBottom: 10, fontSize: 13.5, color: 'var(--warn)' }}>{flash}</div>}
      <EngineKeysForm tails={tails} onSave={save} busy={busy}
        note="Claude runs on Lojo's key. For the other engines the client (or you, on their behalf) pays: paste their keys here and benchmarks for this client use them. Stored encrypted; only the last four characters ever come back. A key here wins over the agency's key." />
    </Panel>);
}


/* What one record owns and paid for; comp and revoke. */
function PaymentsPanel({ slug, token, report, pay, onChanged, onExpired }) {
  const [busy, setBusy] = React.useState('');
  const [flash, setFlash] = React.useState('');
  const ents = report.entitlements || {};
  const payments = report.payments || [];
  const owned = (report.pay && report.pay.owned) || {};
  const act = async (action, product, confirmText) => {
    if (confirmText && !window.confirm(confirmText)) return;
    setBusy(action + product); setFlash('');
    try {
      const d = await adminCall('/api/admin', token, { action, slug, product });
      if (d.status === 401) { onExpired(); return; }
      if (!d.ok) setFlash(d.message || d.error || `${action} failed.`);
      onChanged();
    } catch (e) { setFlash('Could not reach the server.'); }
    setBusy('');
  };
  const one = (p) => { const x = pay && pay.prices && pay.prices[p]; if (!x) return ''; return x.list_usd && x.list_usd > x.usd ? `${usd(x.usd)} (was ${usd(x.list_usd)})` : usd(x.usd); };
  const price = (p) => p === 'benchmark' ? `${one('benchmark_byok')} / ${one('benchmark_managed')}` : one(p);
  const discount = async (body) => { const d = await adminCall('/api/admin', token, { action: 'discount', slug, ...body }); if (d.status === 401) { onExpired(); return; } if (!d.ok) setFlash(d.message || 'Discount not saved'); onChanged(); };
  const row = (product, label) => {
    const e = ents[product];
    const legacy = !e && product === 'full_report' && !!report.released;
    const has = !!owned[product] || legacy;
    return (
      <div key={product} style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', padding: '10px 0', borderTop: '1px solid var(--line)' }}>
        <div style={{ flex: '1 1 220px' }}>
          <div style={{ fontSize: 14.5, fontWeight: 600 }}>{label} <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>{price(product)}</span></div>
          <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>
            {!has && (pay && pay.enabled ? 'Not bought. The client buys it from the report page, or comp it here.' : 'Payments are off, so this is open to everyone.')}
            {e && e.source === 'stripe' && `Paid ${e.amount ? usd(e.amount) : ''} on ${String(e.at || '').slice(0, 10)}${e.email ? ' by ' + e.email : ''}${e.variant ? ` (${e.variant === 'benchmark_byok' ? 'client keys' : e.variant === 'benchmark_managed' ? 'Lojo keys' : e.variant})` : ''}.`}
            {product === 'benchmark' && report.pay && report.pay.benchmark && ['purchased', 'keys_needed'].includes(report.pay.benchmark.status) && <span style={{ color: 'var(--warn)' }}> Not run yet: the 24-hour clock started {String(report.pay.benchmark.requested_at || '').slice(0, 16).replace('T', ' ')}.{report.pay.benchmark.status === 'keys_needed' ? ' Waiting for the client to add keys.' : ''}</span>}
            {e && e.source === 'comp' && `Comped by the team on ${String(e.at || '').slice(0, 10)}.`}
            {e && e.source === 'agency' && `Covered by the ${e.agency_slug || 'agency'} allowance on ${String(e.at || '').slice(0, 10)}.`}
            {legacy && 'A code was issued by hand. The client can enter it, or buy from the report page and get the same code.'}
          </div>
        </div>
        {!e && <button style={smallBtn('accent')} disabled={!!busy} onClick={() => act('comp', product, `Comp the ${label.toLowerCase()} for ${report.client || slug}?${product === 'full_report' && !has ? ' This also starts writing the report.' : ''}`)}>Comp it</button>}
        {e && e.source !== 'stripe' && <button style={smallBtn()} disabled={!!busy} onClick={() => act('uncomp', product, `Take the ${label.toLowerCase()} back from ${report.client || slug}?`)}>Revoke</button>}
        {e && e.source === 'stripe' && <Pill tone="good">paid</Pill>}
      </div>);
  };
  return (
    <Panel title="Payments" tone={payments.length ? 'good' : undefined}>
      {flash && <div style={{ fontSize: 13, color: 'var(--warn)', marginBottom: 8 }}>{flash}</div>}
      {row('full_report', 'Full report')}
      {row('benchmark', 'Engine benchmark add-on')}
      <DiscountEditor discounts={(pay && pay.discounts) || report.discounts || []} products={REPORT_FEE_PRODUCTS} onAdd={(add) => discount({ add })} onRemove={(id) => discount({ remove: id })} compact />
      {payments.length > 0 &&
      <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--line)' }}>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.09em', textTransform: 'uppercase', color: 'var(--fg-subtle)', marginBottom: 6 }}>Stripe payments</div>
        {payments.map((p) =>
        <div key={p.session_id} className="mono" style={{ fontSize: 11.5, color: 'var(--fg-muted)', lineHeight: 1.7 }}>
          {String(p.at || '').slice(0, 16).replace('T', ' ')} · {PAY_PRODUCT_LABEL[p.product] || p.product} · {usd(p.amount)} {String(p.currency || '').toUpperCase()} · {p.email} · {p.session_id}{p.live === false ? ' · test' : ''}
        </div>)}
      </div>}
    </Panel>);
}

/* Talk-to-us requests: who asked, which modules, NDA state, status. */
function InquiriesSection({ token, onExpired }) {
  const [d, setD] = React.useState(null);
  const [flash, setFlash] = React.useState('');
  const [busy, setBusy] = React.useState('');
  const load = React.useCallback(() => { adminCall('/api/lojo', token, { module: 'inquiry', action: 'list' }).then((x) => { if (x.status === 401) { onExpired(); return; } setD(x); }); }, [token]);
  React.useEffect(() => { load(); }, [load]);
  if (!d) return null;
  if (!d.ok) return d.error === 'feature-off' ? null : <div style={{ marginTop: 30, color: 'var(--fg-subtle)', fontSize: 13 }}>Inquiries: {d.message || d.error}</div>;
  const setStatus = async (inq, status) => { const note = window.prompt('Note for the record (optional)') || ''; const x = await adminCall('/api/lojo', token, { module: 'inquiry', action: 'set-status', id: inq.id, status, note }); if (!x.ok) setFlash(x.message || 'Not updated'); load(); };
  const tone = { new: 'warn', contacted: 'accent', scheduled: 'accent', proposal: 'good', closed: 'fg-subtle' };
  const runAnalysis = async (inq) => { setBusy(inq.id); const x = await adminCall('/api/lojo', token, { module: 'inquiry', action: 'analyze', id: inq.id, force: true }); setBusy(''); if (!x.ok) setFlash(x.message || 'Analysis failed'); load(); };
  const comp = async (inq, mid) => { if (!mid) return; if (!window.confirm(`Unlock ${mid} for ${inq.contact.company || inq.contact.name} without payment?`)) return; const x = await adminCall('/api/lojo', token, { module: 'inquiry', action: 'comp', id: inq.id, module_id: mid }); if (!x.ok) setFlash(x.message || 'Not unlocked'); load(); };
  const analysable = ['stack', 'execute', 'operations', 'workforce', 'strategy', 'mna', 'portfolio'];
  const discount = async (inq, body) => { const x = await adminCall('/api/lojo', token, { module: 'inquiry', action: 'discount', id: inq.id, ...body }); if (!x.ok) setFlash(x.message || Object.values(x.errors || {}).join(' ') || 'Discount not saved'); load(); };
  return (
    <div style={{ marginTop: 34 }}>
      <h2 className="display" style={{ fontSize: 'clamp(20px,4vw,28px)', margin: '0 0 6px' }}>Module inquiries</h2>
      <p style={{ fontSize: 14.5, color: 'var(--fg-muted)', margin: '0 0 14px', maxWidth: 680, lineHeight: 1.6 }}>Calls and requests from the platform pages. Beta pricing is promised on every one; confirm it on the call. Tier 3 and uploads exist only where an NDA is in place; a counterparty template needs your countersignature before its material is read.</p>
      {flash && <div className="flash warn">{flash}</div>}
      {d.inquiries.length === 0 ? <div style={{ fontSize: 13.5, color: 'var(--fg-subtle)' }}>No inquiries yet.</div> :
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {d.inquiries.map((q) => <div key={q.id} style={{ padding: '12px 16px', borderRadius: 'var(--r-lg)', background: 'var(--navy-2)', border: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ flex: '1 1 240px' }}><div style={{ fontSize: 15.5, fontWeight: 600 }}>{q.contact.company || q.contact.name} <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)' }}>{q.id}</span></div>
              <div style={{ fontSize: 13, color: 'var(--fg-muted)' }}>{q.contact.name} · {q.contact.email}{q.contact.role ? ' · ' + q.contact.role : ''} · {q.modules.join(', ')} · {q.kind}{q.call && q.call.preferred_times && q.call.preferred_times.length ? ' · ' + q.call.preferred_times.join(' / ') + (q.call.timezone ? ' ' + q.call.timezone : '') : ''}</div></div>
            <Pill tone={tone[q.status] || 'fg-subtle'}>{q.status}</Pill>
            <Pill tone={q.nda.status === 'signed_ours' ? 'good' : q.nda.status === 'uploaded_theirs' ? 'warn' : q.nda.status === 'required' ? 'crit' : 'fg-subtle'}>NDA {q.nda.status.replace('_', ' ')}</Pill>
            <select value={q.status} onChange={(e) => setStatus(q, e.target.value)} style={{ ...inputStyleAdmin(false), width: 130, padding: '6px 8px', fontSize: 12.5 }}>{['new', 'contacted', 'scheduled', 'proposal', 'closed'].map((s) => <option key={s} value={s}>{s}</option>)}</select>
          </div>
          {(Object.keys(q.tiers || {}).length > 0 || (q.uploads || []).length > 0) && <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', marginTop: 6, lineHeight: 1.6 }}>
            {Object.entries(q.tiers || {}).map(([t, a]) => <div key={t}>tier {t}: {Object.entries(a).map(([k, v]) => `${k}=${Array.isArray(v) ? v.join('; ') : String(v).slice(0, 120)}`).join(' · ')}</div>)}
            {(q.uploads || []).length > 0 && <div>uploads: {q.uploads.map((u) => `${u.filename} (${u.purpose}, ${Math.round(u.size / 1024)} KB)`).join(' · ')}</div>}
            {q.nda.signed && <div>nda signed by {q.nda.signed.name}, {q.nda.signed.title} at {q.nda.signed.at} · sha {String(q.nda.signed.doc_sha256).slice(0, 12)}</div>}
            {(q.notes || []).map((n, i) => <div key={i}>note {String(n.at).slice(0, 16)} {n.by}: {n.note}</div>)}
          </div>}
          {q.modules.some((m) => analysable.includes(m)) && <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap', marginTop: 8, fontSize: 12.5 }}>
            <Pill tone={(q.analysis || {}).status === 'ready' ? 'good' : (q.analysis || {}).status === 'failed' ? 'crit' : 'fg-subtle'}>analysis {(q.analysis || {}).status || 'none'}{(q.analysis || {}).confidence ? ' · grade ' + q.analysis.confidence : ''}</Pill>
            {(q.analysis || {}).status === 'ready' && <span style={{ color: 'var(--fg-muted)' }}>{q.analysis.gaps} gaps · {q.analysis.researched ? 'researched' : 'no research'} · {q.analysis.model}</span>}
            <span style={{ color: 'var(--fg-muted)' }}>owned: {Object.keys(q.entitlements || {}).filter((e) => e.startsWith('module:')).map((e) => e.slice(7)).join(', ') || 'none'}</span>
            <a href={'/app/?analysis=' + q.id} target="_blank" rel="noreferrer" style={{ color: 'var(--accent)' }}>open analysis</a>
            <button className="app-btn small" disabled={busy === q.id} onClick={() => runAnalysis(q)}>{busy === q.id ? 'Running…' : ((q.analysis || {}).status === 'ready' ? 'Re-run' : 'Run analysis')}</button>
            <select defaultValue="" onChange={(e) => { comp(q, e.target.value); e.target.value = ''; }} style={{ ...inputStyleAdmin(false), width: 150, padding: '4px 8px', fontSize: 12 }}>
              <option value="">Comp a module…</option>{['stack', 'operations', 'workforce', 'strategy', 'mna', 'portfolio'].map((m) => <option key={m} value={m}>{m}</option>)}</select>
          </div>}
          {q.modules.some((m) => analysable.includes(m)) && <DiscountEditor discounts={q.discounts || []} products={MODULE_FEE_PRODUCTS} onAdd={(add) => discount(q, { add })} onRemove={(id) => discount(q, { remove: id })} compact />}
        </div>)}
      </div>}
    </div>);
}

Object.assign(window, { PaymentsPanel, InquiriesSection });
