// Institutional CRM — Lead sources + Referral partners management
function PgSources({ toast }) {
  const [sources, setSources] = React.useState(window.ICRM.SOURCES);
  const [openAdd, setOpenAdd] = React.useState(false);
  const [form, setForm] = React.useState({ name: '', detail: '' });
  const { LEADS } = window.ICRM;

  const leadsFor = id => LEADS.filter(l => l.sourceId === id).length;
  const addSource = () => {
    try { fetch('/api/sources', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: form.name, detail: form.detail }) }).catch(() => {}); } catch (e) {}
    setSources(p => [...p, { id: 'src-' + Date.now(), name: form.name, kind: 'custom', detail: form.detail, active: true }]);
    setOpenAdd(false); setForm({ name: '', detail: '' });
    toast('Lead source created');
  };
  const toggle = id => setSources(p => p.map(s => s.id === id ? { ...s, active: !s.active } : s));

  const KIND_LABEL = { intake: 'Automatic intake', partner: 'Referral partner', custom: 'Custom' };

  return (
    <div className="inst-page">
      {openAdd ? (
        <Modal title="Create lead source" onClose={() => setOpenAdd(false)}
          footer={<React.Fragment>
            <button className="inst-btn outline" onClick={() => setOpenAdd(false)}>Cancel</button>
            <button className="inst-btn primary" onClick={addSource} disabled={!form.name}>Create source</button>
          </React.Fragment>}>
          <div style={{ display: 'grid', gap: 14 }}>
            <Field label="Source name"><input className="inst-input" placeholder="e.g. Trade Show — Broker Fair 2026" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></Field>
            <Field label="Description"><input className="inst-input" placeholder="Where do these leads come from?" value={form.detail} onChange={e => setForm({ ...form, detail: e.target.value })} /></Field>
          </div>
          <div style={{ marginTop: 14, fontSize: 12, color: 'var(--inst-ink-3)' }}>
            New sources appear in the lead form and in funnel filters immediately. Referral partners get their own source automatically when added.
          </div>
        </Modal>
      ) : null}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, margin: '4px 0 16px', flexWrap: 'wrap' }}>
        <div className="inst-greeting" style={{ margin: 0 }}>Lead sources</div>
        <button className="inst-btn primary" onClick={() => setOpenAdd(true)}>+ Create source</button>
      </div>

      <div className="inst-notice" style={{ marginBottom: 16 }}>
        <span className="bulb"><IC d={ICONS.zap} size={16} /></span>
        <span>The two <b>automatic intake sources</b> are wired to your public forms: completing the DebtLift settlement calculator or submitting the ExpressFund application creates a lead in the funnel instantly, with the applicant's answers attached.</span>
      </div>

      <SectionCard bar="All sources" right={sources.length + ' sources'}>
        <div className="inst-table-wrap">
          <table className="inst-table">
            <thead><tr><th>Source</th><th>Type</th><th style={{ textAlign: 'right' }}>Leads</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {sources.map(s => (
                <tr key={s.id}>
                  <td>
                    <span className="inst-td-strong">{s.name}</span>
                    {s.kind === 'intake' ? <span style={{ marginLeft: 8, color: 'var(--inst-link)', verticalAlign: 1 }} title="Automatic intake"><IC d={ICONS.zap} size={12} /></span> : null}
                    {s.brand ? <span style={{ marginLeft: 8 }}><BrandTag brand={s.brand} /></span> : null}
                    <div className="inst-td-id">{s.detail}</div>
                  </td>
                  <td><Chip tone={s.kind === 'intake' ? 'blue' : s.kind === 'partner' ? 'navy' : ''}>{KIND_LABEL[s.kind]}</Chip></td>
                  <td className="inst-td-num inst-td-strong">{leadsFor(s.id)}</td>
                  <td><Chip tone={s.active ? 'green' : 'red'}>{s.active ? 'Active' : 'Paused'}</Chip></td>
                  <td>{s.kind !== 'intake' ? <button className="inst-btn outline sm" onClick={() => toggle(s.id)}>{s.active ? 'Pause' : 'Resume'}</button> : <span style={{ fontSize: 11, color: 'var(--inst-ink-3)' }}>Always on</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </div>
  );
}

function PgPartners({ toast }) {
  const [partners, setPartners] = React.useState(window.ICRM.PARTNERS);
  const [openAdd, setOpenAdd] = React.useState(false);
  const [editAccess, setEditAccess] = React.useState(null);
  const [form, setForm] = React.useState({ name: '', company: '', type: 'ISO', email: '', points: 8, accessDL: false, accessEF: true });
  const { fmt } = window.ICRM;

  const addPartner = () => {
    try {
      const acc = [form.accessDL ? 'DebtLift' : null, form.accessEF ? 'ExpressFund' : null].filter(Boolean);
      fetch('/api/partners', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: form.name, company: form.company, type: form.type, email: form.email, points: parseFloat(form.points) || 8, access: acc }) }).catch(() => {});
    } catch (e) {}
    const slug = (form.company || form.name).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    const access = [form.accessDL ? 'DebtLift' : null, form.accessEF ? 'ExpressFund' : null].filter(Boolean);
    const { accessDL, accessEF, ...rest } = form;
    setPartners(p => [...p, { id: 'p' + Date.now(), ...rest, access, points: parseFloat(form.points) || 0, phone: '', link: 'express.fund/r/' + slug, leads: 0, funded: 0, volume: 0, owed: 0, paid: 0 }]);
    setOpenAdd(false); setForm({ name: '', company: '', type: 'ISO', email: '', points: 8, accessDL: false, accessEF: true });
    toast('Partner added — referral link + lead source created');
  };

  const toggleAccess = (pid, brand) => setPartners(ps => ps.map(x => {
    if (x.id !== pid) return x;
    const cur = x.access || ['ExpressFund'];
    const has = cur.includes(brand);
    const access = has ? cur.filter(b => b !== brand) : [...cur, brand];
    return access.length ? { ...x, access } : x; // must keep at least one company
  }));

  return (
    <div className="inst-page">
      {editAccess ? (() => {
        const ea = partners.find(x => x.id === editAccess.id);
        return (
          <Modal title={'Company access — ' + (ea.company || ea.name)} onClose={() => setEditAccess(null)}
            footer={<button className="inst-btn primary" onClick={() => { setEditAccess(null); toast('Access updated'); }}>Done</button>}>
            <div style={{ display: 'grid', gap: 10 }}>
              {['ExpressFund', 'DebtLift'].map(b => {
                const on = (ea.access || ['ExpressFund']).includes(b);
                return (
                  <label key={b} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, border: '1px solid var(--inst-rule)', borderRadius: 6, padding: '12px 14px', cursor: 'pointer' }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <BrandTag brand={b} />
                      <span style={{ fontSize: 13, color: 'var(--inst-ink-2)' }}>{b === 'ExpressFund' ? 'Refer merchants for funding' : 'Refer merchants for debt settlement'}</span>
                    </span>
                    <input type="checkbox" checked={on} onChange={() => toggleAccess(ea.id, b)} />
                  </label>
                );
              })}
            </div>
            <div style={{ marginTop: 12, fontSize: 12, color: 'var(--inst-ink-3)' }}>Partners must keep access to at least one company. Removing access hides that company's referral link, leads and commissions from their portal.</div>
          </Modal>
        );
      })() : null}

      {openAdd ? (
        <Modal title="Add referral partner" onClose={() => setOpenAdd(false)}
          footer={<React.Fragment>
            <button className="inst-btn outline" onClick={() => setOpenAdd(false)}>Cancel</button>
            <button className="inst-btn primary" onClick={addPartner} disabled={(!form.company && !form.name) || (!form.accessDL && !form.accessEF)}>Add partner</button>
          </React.Fragment>}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Field label="Contact name"><input className="inst-input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} /></Field>
            <Field label="Company"><input className="inst-input" value={form.company} onChange={e => setForm({ ...form, company: e.target.value })} /></Field>
            <Field label="Type">
              <select className="inst-input" value={form.type} onChange={e => setForm({ ...form, type: e.target.value })}>
                <option>ISO</option><option>Broker</option><option>CPA</option><option>Attorney</option><option>Other</option>
              </select>
            </Field>
            <Field label="Email"><input className="inst-input" type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></Field>
            <Field label="Commission (points)"><input className="inst-input" type="number" value={form.points} onChange={e => setForm({ ...form, points: e.target.value })} /></Field>
            <Field label="Company access" full>
              <div style={{ display: 'flex', gap: 18, padding: '6px 0 2px' }}>
                <label style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13, color: 'var(--inst-ink-2)', fontWeight: 600, cursor: 'pointer' }}>
                  <input type="checkbox" checked={form.accessEF} onChange={e => setForm({ ...form, accessEF: e.target.checked })} /> ExpressFund (funding)
                </label>
                <label style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 13, color: 'var(--inst-ink-2)', fontWeight: 600, cursor: 'pointer' }}>
                  <input type="checkbox" checked={form.accessDL} onChange={e => setForm({ ...form, accessDL: e.target.checked })} /> DebtLift (settlement)
                </label>
              </div>
            </Field>
          </div>
          <div style={{ marginTop: 14, fontSize: 12, color: 'var(--inst-ink-3)' }}>
            Adding a partner automatically creates a tracked referral link per company (DebtLift links go to the calculator page: calculator.debtlift.co/?ref=…) and a matching lead source. <b>Company access controls what they can refer into and see</b> — partners only get portal access, referral links and lead attribution for the companies checked above.
          </div>
        </Modal>
      ) : null}

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, margin: '4px 0 16px', flexWrap: 'wrap' }}>
        <div className="inst-greeting" style={{ margin: 0 }}>Referral partners</div>
        <button className="inst-btn primary" onClick={() => setOpenAdd(true)}>+ Add partner</button>
      </div>

      <div className="inst-stack">
        {partners.map(p => (
          <SectionCard key={p.id} bar={p.company || p.name} right={p.type + ' · ' + p.points + ' pts'}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '12px 14px 0', flexWrap: 'wrap' }}>
              <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.5px', textTransform: 'uppercase', color: 'var(--inst-ink-3)' }}>Access</span>
              {(p.access || ['ExpressFund']).map(b => <BrandTag key={b} brand={b} />)}
              <button className="inst-btn outline sm" style={{ marginLeft: 4 }} onClick={() => setEditAccess(p)}>Change</button>
            </div>
            <div className="inst-grid-4" style={{ padding: 14, gap: 10 }}>
              <div className="inst-stat" style={{ padding: 8 }}><div className="lbl">Leads sent</div><div className="val" style={{ fontSize: 22 }}>{p.leads}</div></div>
              <div className="inst-stat" style={{ padding: 8 }}><div className="lbl">Funded</div><div className="val" style={{ fontSize: 22 }}>{p.funded}</div></div>
              <div className="inst-stat" style={{ padding: 8 }}><div className="lbl">Volume</div><div className="val" style={{ fontSize: 22 }}>{window.ICRM.fmtK(p.volume)}</div></div>
              <div className="inst-stat" style={{ padding: 8 }}><div className="lbl">Owed / Paid</div><div className="val" style={{ fontSize: 22, color: p.owed ? 'var(--inst-warn)' : undefined }}>{fmt(p.owed)}</div><div className="sub">{fmt(p.paid)} paid</div></div>
            </div>
            <div className="inst-card-foot" style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
              <span style={{ fontSize: 12, color: 'var(--inst-ink-2)' }}><b>{p.name}</b> · {p.email}{p.phone ? ' · ' + p.phone : ''}</span>
              <span style={{ flex: 1 }}></span>
              {(p.access || ['ExpressFund']).map(b => {
                const slug = p.link.split('/r/')[1] || p.link;
                const url = b === 'DebtLift' ? 'calculator.debtlift.co/?ref=' + slug : 'express.fund/r/' + slug;
                return (
                  <span key={b} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <BrandTag brand={b} />
                    <code style={{ fontSize: 12, background: 'var(--brand-50)', border: '1px solid #c8d9f2', borderRadius: 4, padding: '3px 8px', color: 'var(--inst-link)' }}>{url}</code>
                    <button className="inst-btn outline sm" onClick={() => toast(b + ' link copied')}>Copy</button>
                  </span>
                );
              })}
            </div>
          </SectionCard>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { PgSources, PgPartners });
