// Contracts data & section — central contract repository

const CONTRACT_TYPES = [
  { id: 'customer',   name: 'Customer',   tone: 'green' },
  { id: 'vendor',     name: 'Vendor',     tone: 'blue' },
];

const CONTRACTS = [
  // Customer
  { id: 'CT-1024', name: 'Stratoscale Robotics — MSA + Order Form #4', type: 'customer', counterparty: 'Stratoscale Robotics', customerId: 'c1', value: 340800, billing: 'Annual', status: 'Active', signedOn: '2025-03-12', startDate: '2025-04-01', endDate: '2026-03-31', autoRenew: true, renewalNotice: 60, owner: 'e20', signerExt: 'Daria Whitmore, CFO', signerInt: 'e1', files: [ { name: 'MSA — Stratoscale executed.pdf', size: 1400000 }, { name: 'Order Form #4 — Platform tier.pdf', size: 480000 }, { name: 'DPA addendum.pdf', size: 220000 } ], tags: ['msa','annual','enterprise'] },
  { id: 'CT-1031', name: 'Northbrook Manufacturing — Multi-year', type: 'customer', counterparty: 'Northbrook Manufacturing', customerId: 'c2', value: 494400, billing: 'Annual · 2yr', status: 'Renewing', signedOn: '2024-07-01', startDate: '2024-07-01', endDate: '2026-07-15', autoRenew: false, renewalNotice: 90, owner: 'e20', signerExt: 'Roy Eberhart, CIO', signerInt: 'e1', files: [ { name: 'Northbrook MSA — 2024.pdf', size: 2100000 }, { name: 'SOW 2024-A.pdf', size: 380000 } ], tags: ['msa','renewal-q3'] },
  { id: 'CT-1038', name: 'Vellum Health — Order Form', type: 'customer', counterparty: 'Vellum Health', customerId: 'c3', value: 153600, billing: 'Annual', status: 'Active', signedOn: '2025-06-15', startDate: '2025-07-01', endDate: '2026-06-30', autoRenew: true, renewalNotice: 30, owner: 'e21', signerExt: 'Aviv Reuven, COO', signerInt: 'e1', files: [ { name: 'Order Form — Vellum.pdf', size: 360000 }, { name: 'BAA — HIPAA.pdf', size: 280000 } ], tags: ['baa','healthcare'] },
  { id: 'CT-1042', name: 'Klein & Auer — EU Data Addendum', type: 'customer', counterparty: 'Klein & Auer Logistics', customerId: 'c5', value: 271200, billing: 'Annual', status: 'Pending signature', signedOn: null, startDate: '2026-06-01', endDate: '2027-05-31', autoRenew: true, renewalNotice: 60, owner: 'e20', signerExt: 'Helmut Bauer, Geschäftsführer', signerInt: 'e1', files: [ { name: 'EU Data Residency Addendum — v3.pdf', size: 420000 }, { name: 'SCCs.pdf', size: 320000 } ], tags: ['eu','gdpr','renewal'] },
  { id: 'CT-1047', name: 'Halcyon Biotech — Analytics module SOW', type: 'customer', counterparty: 'Halcyon Biotech', customerId: 'c7', value: 78000, billing: 'One-time', status: 'Pending signature', signedOn: null, startDate: '2026-06-01', endDate: '2026-12-31', autoRenew: false, renewalNotice: 0, owner: 'e20', signerExt: 'Maya Forrest, CMO', signerInt: 'e1', files: [ { name: 'SOW — Analytics module.pdf', size: 540000 } ], tags: ['sow'] },
  { id: 'CT-1050', name: 'Marigold Studios — Annual plan', type: 'customer', counterparty: 'Marigold Studios', customerId: 'c4', value: 14400, billing: 'Annual', status: 'Active', signedOn: '2026-05-04', startDate: '2026-05-04', endDate: '2027-05-03', autoRenew: true, renewalNotice: 30, owner: 'e21', signerExt: 'Renée Hsieh, Founder', signerInt: 'e21', files: [ { name: 'Click-through ToS — Marigold.pdf', size: 180000 } ], tags: ['smb','self-serve'] },
  { id: 'CT-1052', name: 'Pinecrest Schools — District contract', type: 'customer', counterparty: 'Pinecrest Schools', customerId: 'c6', value: 45600, billing: 'Annual', status: 'Draft', signedOn: null, startDate: '2026-08-01', endDate: '2027-07-31', autoRenew: false, renewalNotice: 60, owner: 'e21', signerExt: 'Dr. Tanya Beecroft, Superintendent', signerInt: 'e1', files: [ { name: 'District contract — v1.docx', size: 220000 } ], tags: ['education','rfp'] },

  // Vendor
  { id: 'CT-2003', name: 'AWS — Enterprise Discount Program', type: 'vendor', counterparty: 'Amazon Web Services', customerId: null, value: 480000, billing: 'Annual', status: 'Active', signedOn: '2025-01-15', startDate: '2025-02-01', endDate: '2027-01-31', autoRenew: false, renewalNotice: 90, owner: 'e14', signerExt: 'Daniel Pak, Enterprise BD', signerInt: 'e1', files: [ { name: 'AWS EDP 2025 - executed.pdf', size: 1800000 } ], tags: ['cloud','infrastructure','spend'] },
  { id: 'CT-2008', name: 'Datadog — Pro plan', type: 'vendor', counterparty: 'Datadog Inc.', customerId: null, value: 96000, billing: 'Annual', status: 'Active', signedOn: '2025-04-20', startDate: '2025-05-01', endDate: '2026-04-30', autoRenew: true, renewalNotice: 30, owner: 'e14', signerExt: 'Order form click-accept', signerInt: 'e2', files: [ { name: 'Datadog Order Form 2025.pdf', size: 340000 } ], tags: ['monitoring'] },
  { id: 'CT-2014', name: 'Linear — Business plan', type: 'vendor', counterparty: 'Linear Orbit, Inc.', customerId: null, value: 14400, billing: 'Annual', status: 'Expired', signedOn: '2024-05-15', startDate: '2024-06-01', endDate: '2025-05-31', autoRenew: false, renewalNotice: 30, owner: 'e2', signerExt: 'Click-accept', signerInt: 'e2', files: [ { name: 'Linear order form 2024.pdf', size: 120000 } ], tags: ['tools'] },
  { id: 'CT-2018', name: 'Office lease — Bowling Green HQ', type: 'vendor', counterparty: 'Greenbriar Commercial Properties', customerId: null, value: 384000, billing: 'Annual', status: 'Active', signedOn: '2023-09-12', startDate: '2024-01-01', endDate: '2028-12-31', autoRenew: false, renewalNotice: 180, owner: 'e6', signerExt: 'Calvin Greer, Property Mgr', signerInt: 'e1', files: [ { name: 'Lease agreement — executed.pdf', size: 4200000 }, { name: 'Floor plan addendum.pdf', size: 2100000 } ], tags: ['real-estate','long-term'] },
  { id: 'CT-2025', name: 'PEER Audit Co. — SOC 2 engagement', type: 'vendor', counterparty: 'PEER Audit Co.', customerId: null, value: 84000, billing: 'One-time', status: 'Active', signedOn: '2026-04-22', startDate: '2026-04-22', endDate: '2026-12-31', autoRenew: false, renewalNotice: 0, owner: 'e9', signerExt: 'Imogen Yeong, Partner', signerInt: 'e9', files: [ { name: 'SOW — SOC 2 audit.pdf', size: 410000 }, { name: 'MNDA.pdf', size: 180000 } ], tags: ['compliance'] },

  // Partner
  { id: 'CT-3002', name: 'Affiliate program — master agreement', type: 'partner', counterparty: 'All affiliates (master template)', customerId: null, value: 0, billing: 'Per partner', status: 'Active', signedOn: '2024-02-01', startDate: '2024-02-01', endDate: null, autoRenew: true, renewalNotice: 0, owner: 'e5', signerExt: 'Various (8 active)', signerInt: 'e9', files: [ { name: 'Affiliate master agreement — template.pdf', size: 280000 }, { name: 'Payout schedule rider.pdf', size: 90000 } ], tags: ['affiliate','template'] },
  { id: 'CT-3005', name: 'Reseller — APAC distributor', type: 'partner', counterparty: 'Sundara Solutions Pte.', customerId: null, value: 0, billing: 'Revenue share 25%', status: 'Pending signature', signedOn: null, startDate: '2026-07-01', endDate: '2028-06-30', autoRenew: false, renewalNotice: 90, owner: 'e4', signerExt: 'Vikram Iyer, MD', signerInt: 'e1', files: [ { name: 'Reseller agreement — APAC draft v2.docx', size: 320000 } ], tags: ['reseller','apac'] },
  { id: 'CT-3007', name: 'Tech partnership — Plenum Analytics', type: 'partner', counterparty: 'Plenum Analytics', customerId: null, value: 0, billing: 'Mutual referral', status: 'Active', signedOn: '2025-11-10', startDate: '2025-12-01', endDate: '2027-11-30', autoRenew: true, renewalNotice: 60, owner: 'e3', signerExt: 'Ada Whitfield, CEO', signerInt: 'e1', files: [ { name: 'Partnership MoU — executed.pdf', size: 240000 } ], tags: ['technology','referral'] },

  // Employment
  { id: 'CT-4011', name: 'Offer letter — Pratik Sundar', type: 'employment', counterparty: 'Pratik Sundar', customerId: null, value: 75000, billing: 'Annual salary', status: 'Active', signedOn: '2024-02-12', startDate: '2024-03-04', endDate: null, autoRenew: false, renewalNotice: 0, owner: 'e6', signerExt: 'Pratik Sundar', signerInt: 'e4', files: [ { name: 'Offer letter — Pratik.pdf', size: 180000 }, { name: 'IP assignment.pdf', size: 120000 } ], tags: ['offer','sdr'] },
  { id: 'CT-4014', name: 'Contractor — design contractor SOW', type: 'employment', counterparty: 'Inkstone Design Studio', customerId: null, value: 42000, billing: 'Project-based', status: 'Active', signedOn: '2026-03-22', startDate: '2026-04-01', endDate: '2026-09-30', autoRenew: false, renewalNotice: 30, owner: 'e8', signerExt: 'Lin Cho-Hee, Principal', signerInt: 'e8', files: [ { name: 'Contractor SOW — Inkstone.pdf', size: 290000 } ], tags: ['contractor'] },

  // NDA
  { id: 'CT-5004', name: 'NDA — Junction Bank evaluation', type: 'nda', counterparty: 'Junction Bank', customerId: 'c8', value: 0, billing: 'One-time', status: 'Active', signedOn: '2026-05-02', startDate: '2026-05-02', endDate: '2028-05-01', autoRenew: false, renewalNotice: 0, owner: 'e20', signerExt: 'Ines Holloway, Procurement', signerInt: 'e20', files: [ { name: 'Mutual NDA — Junction Bank.pdf', size: 160000 } ], tags: ['mnda','prospect'] },
  { id: 'CT-5008', name: 'NDA — Foxtail Robotics POC', type: 'nda', counterparty: 'Foxtail Robotics', customerId: null, value: 0, billing: 'One-time', status: 'Active', signedOn: '2026-05-08', startDate: '2026-05-08', endDate: '2027-05-07', autoRenew: false, renewalNotice: 0, owner: 'e22', signerExt: 'Jordan Wu, VP Eng', signerInt: 'e22', files: [ { name: 'Mutual NDA — Foxtail.pdf', size: 150000 } ], tags: ['mnda','poc'] },
];

window.HitcentsData.CONTRACT_TYPES = CONTRACT_TYPES;
window.HitcentsData.CONTRACTS = CONTRACTS.filter(c => ['customer','vendor'].includes(c.type));

// ─────────────────────────────────────────────────────────────────────────────
// Contracts section
// ─────────────────────────────────────────────────────────────────────────────

function Contracts() {
  const D = window.HitcentsData;
  const [view, setView] = useState('all');
  const [open, setOpen] = useState(null);
  const [newOpen, setNewOpen] = useState(false);
  const [version, setVersion] = useState(0);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

  const all = D.CONTRACTS;
  const today = new Date('2026-05-15');

  function daysUntil(d) {
    if (!d) return null;
    return Math.round((new Date(d) - today) / (1000*60*60*24));
  }

  const filtered = all.filter(c => {
    if (view !== 'all' && c.type !== view) return false;
    if (statusFilter !== 'all' && c.status !== statusFilter) return false;
    if (search && !`${c.id} ${c.name} ${c.counterparty}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const active = all.filter(c => c.status === 'Active');
  const totalACV = active.filter(c => c.type === 'customer').reduce((s,c) => s + c.value, 0);
  const vendorSpend = active.filter(c => c.type === 'vendor').reduce((s,c) => s + c.value, 0);
  const pendingSig = all.filter(c => c.status === 'Pending signature' || c.status === 'Draft').length;
  const expiringSoon = all.filter(c => {
    const days = daysUntil(c.endDate);
    return c.status === 'Active' && days != null && days >= 0 && days <= 90;
  });

  return (
    <div data-screen-label="Contracts">
      <div className="page-head">
        <div>
          <h1>Contracts</h1>
          <div className="sub">{all.length} contracts on file · {active.length} active · {expiringSoon.length} expiring within 90 days</div>
        </div>
        <div className="row gap-2">
          <Button variant="primary" icon="plus" onClick={() => setNewOpen(true)}>New contract</Button>
        </div>
      </div>

      <div className="grid g-4" style={{ marginBottom: 18, gap: 12 }}>
        <Kpi label="Customer ACV under contract" value={fmtMoney(totalACV)} delta={`${active.filter(c => c.type === 'customer').length} active`} tone="up" />
        <Kpi label="Vendor commitments" value={fmtMoney(vendorSpend)} delta={`${active.filter(c => c.type === 'vendor').length} suppliers`} />
        <Kpi label="Pending signature" value={pendingSig} delta="awaiting countersign" tone={pendingSig > 0 ? 'down' : 'up'} />
        <Kpi label="Expiring ≤ 90 days" value={expiringSoon.length} delta={expiringSoon.length > 0 ? fmtMoney(expiringSoon.reduce((s,c) => s + c.value, 0)) + ' at risk' : 'all current'} tone={expiringSoon.length > 0 ? 'down' : 'up'} />
      </div>

      {/* Renewals strip — high-signal */}
      <div className="card" style={{ marginBottom: 18 }}>
        <div className="card-h">
          <div>
            <h3>Renewals on the horizon</h3>
            <div className="sub">Contracts ending in the next 6 months · sorted by date</div>
          </div>
          <Button size="sm" variant="ghost" iconRight="arrow_r">All renewals</Button>
        </div>
        <RenewalsStrip contracts={all} onOpen={setOpen} />
      </div>

      <div className="tabs" style={{ marginBottom: 16 }}>
        <button className={`tab ${view === 'all' ? 'active' : ''}`} onClick={() => setView('all')}>All ({all.length})</button>
        {D.CONTRACT_TYPES.map(t => (
          <button key={t.id} className={`tab ${view === t.id ? 'active' : ''}`} onClick={() => setView(t.id)}>
            {t.name} ({all.filter(c => c.type === t.id).length})
          </button>
        ))}
      </div>

      <div className="toolbar">
        <div className="search-inline">
          <Icon name="search" size={14} />
          <input placeholder="Search contracts, parties, IDs…" value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)}
                style={{ padding: '7px 10px', border: '1px solid var(--border)', borderRadius: 8, background: 'var(--bg-card)', fontSize: 13 }}>
          <option value="all">All statuses</option>
          <option value="Active">Active</option>
          <option value="Renewing">Renewing</option>
          <option value="Pending signature">Pending signature</option>
          <option value="Draft">Draft</option>
          <option value="Expired">Expired</option>
        </select>
        <div style={{ marginLeft: 'auto' }} className="muted" >{filtered.length} of {all.length}</div>
      </div>

      <div className="card flush">
        <table className="table">
          <thead>
            <tr><th>Contract</th><th>Counterparty</th><th>Type</th><th>Value</th><th>Period</th><th>Status</th><th>Owner</th><th>Files</th></tr>
          </thead>
          <tbody>
            {filtered.map(c => {
              const t = D.CONTRACT_TYPES.find(x => x.id === c.type);
              const o = getEmployee(c.owner);
              const days = daysUntil(c.endDate);
              const statusTone = c.status === 'Active' ? 'green' : c.status === 'Renewing' ? 'orange' : c.status === 'Pending signature' ? 'amber' : c.status === 'Draft' ? 'neutral' : c.status === 'Expired' ? 'red' : 'neutral';
              return (
                <tr key={c.id} className="clickable" onClick={() => setOpen(c)}>
                  <td>
                    <div className="row gap-2">
                      <span className="mono dim" style={{ fontSize: 10.5 }}>{c.id}</span>
                      <div>
                        <div style={{ fontWeight: 500, maxWidth: 360, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                        <div className="dim" style={{ fontSize: 11 }}>{c.tags.map(tag => '#' + tag).join(' ')}</div>
                      </div>
                    </div>
                  </td>
                  <td>{c.counterparty}</td>
                  <td><Badge tone={t.tone}>{t.name}</Badge></td>
                  <td className="mono">{c.value ? fmtMoneyFull(c.value) : '—'}{c.billing && c.value > 0 ? <span className="dim" style={{ fontSize: 11 }}> / {c.billing.split(' ')[0]}</span> : ''}</td>
                  <td className="mono" style={{ fontSize: 11.5 }}>
                    {fmtDateShort(c.startDate)} → {c.endDate ? fmtDateShort(c.endDate) : 'evergreen'}
                    {days != null && days >= 0 && days <= 90 && c.status === 'Active' && (
                      <div className="dim" style={{ fontSize: 10.5 }}>expires in {days}d</div>
                    )}
                  </td>
                  <td><Badge tone={statusTone}>{c.status}</Badge></td>
                  <td>{o ? <div className="row gap-2"><Avatar person={o} size={20} /><span style={{ fontSize: 12 }}>{o.name.split(' ')[0]}</span></div> : <span className="dim">—</span>}</td>
                  <td><div className="row gap-2" style={{ color: 'var(--text-muted)' }}><Icon name="doc" size={12} /><span className="mono" style={{ fontSize: 11 }}>{c.files.length}</span></div></td>
                </tr>
              );
            })}
            {filtered.length === 0 && (
              <tr><td colSpan={8} style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)' }}>No contracts match the current filters.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <Drawer open={!!open} onClose={() => setOpen(null)} title="Contract" width={620}>
        {open && <ContractDetail contract={open} />}
      </Drawer>

      {newOpen && (
        <NewContractModal
          onClose={() => setNewOpen(false)}
          onCreate={(contract) => {
            D.CONTRACTS.unshift(contract);
            setVersion(v => v + 1);
            setNewOpen(false);
            setOpen(contract);
          }} />
      )}
    </div>
  );
}

function RenewalsStrip({ contracts, onOpen }) {
  const today = new Date('2026-05-15');
  const upcoming = contracts
    .filter(c => c.endDate && c.status === 'Active')
    .map(c => ({ ...c, daysLeft: Math.round((new Date(c.endDate) - today) / (1000*60*60*24)) }))
    .filter(c => c.daysLeft >= 0 && c.daysLeft <= 240)
    .sort((a,b) => a.daysLeft - b.daysLeft)
    .slice(0, 6);

  if (upcoming.length === 0) return <div className="dim" style={{ textAlign: 'center', padding: 24 }}>No upcoming renewals in the next 6 months.</div>;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10 }}>
      {upcoming.map(c => {
        const D = window.HitcentsData;
        const t = D.CONTRACT_TYPES.find(x => x.id === c.type);
        const urgent = c.daysLeft <= 60;
        return (
          <div key={c.id} onClick={() => onOpen(c)}
               style={{ padding: 12, background: urgent ? 'var(--brand-orange-tint)' : 'var(--bg-elev)', border: `1px solid ${urgent ? 'var(--brand-orange)' : 'var(--border)'}`, borderLeft: `3px solid ${urgent ? 'var(--brand-orange)' : t.tone === 'neutral' ? 'var(--border-strong)' : `var(--${t.tone})`}`, borderRadius: 8, cursor: 'pointer' }}>
            <div className="row spread" style={{ marginBottom: 4 }}>
              <Badge tone={t.tone} style={{ fontSize: 10 }}>{t.name}</Badge>
              <span className="mono" style={{ fontSize: 11, fontWeight: 600, color: urgent ? 'var(--brand-orange)' : 'var(--text-muted)' }}>{c.daysLeft}d</span>
            </div>
            <div style={{ fontSize: 12.5, fontWeight: 500, marginBottom: 4, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.counterparty}</div>
            <div className="dim" style={{ fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name.replace(c.counterparty + ' — ', '')}</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 6 }}>{c.value ? fmtMoneyFull(c.value) : '—'}</div>
          </div>
        );
      })}
    </div>
  );
}

function ContractDetail({ contract }) {
  const D = window.HitcentsData;
  const t = D.CONTRACT_TYPES.find(x => x.id === contract.type);
  const owner = getEmployee(contract.owner);
  const signerInt = getEmployee(contract.signerInt);
  const customer = contract.customerId ? getCustomer(contract.customerId) : null;
  const today = new Date('2026-05-15');
  const days = contract.endDate ? Math.round((new Date(contract.endDate) - today) / (1000*60*60*24)) : null;
  const isExpiring = days != null && days >= 0 && days <= 90 && contract.status === 'Active';

  return (
    <div>
      <div className="row gap-2" style={{ marginBottom: 4 }}>
        <span className="mono dim" style={{ fontSize: 12 }}>{contract.id}</span>
        <Badge tone={t.tone}>{t.name}</Badge>
        <Badge tone={contract.status === 'Active' ? 'green' : contract.status === 'Renewing' ? 'orange' : contract.status === 'Pending signature' ? 'amber' : contract.status === 'Expired' ? 'red' : 'neutral'}>{contract.status}</Badge>
        {contract.autoRenew && <Badge tone="orange">Auto-renew</Badge>}
      </div>
      <h2 style={{ margin: '6px 0 4px', fontSize: 19, fontWeight: 600 }}>{contract.name}</h2>
      <div className="muted" style={{ marginBottom: 14, fontSize: 13 }}>
        with <strong style={{ color: 'var(--text)' }}>{contract.counterparty}</strong>
        {(() => {
          const v = getVendorForContract(contract);
          return v
            ? <> · <button className="link-btn" onClick={() => window.dispatchEvent(new CustomEvent('hitcents:navigate', { detail: { section: 'vendors', target: { type: 'vendor', id: v.id } } }))}>View vendor →</button></>
            : null;
        })()}
      </div>

      {isExpiring && (
        <div style={{ padding: 12, background: 'var(--brand-orange-tint)', borderLeft: '3px solid var(--brand-orange)', borderRadius: 6, marginBottom: 16, fontSize: 13 }}>
          <div className="row gap-2" style={{ marginBottom: 2 }}>
            <Icon name="bell" size={14} style={{ color: 'var(--brand-orange)' }} />
            <strong>Expires in {days} days</strong>
          </div>
          <div className="muted" style={{ fontSize: 12 }}>
            {contract.renewalNotice > 0 ? `${contract.renewalNotice}-day renewal notice required.` : 'No automatic renewal.'} Action: confirm renewal with {contract.counterparty} or initiate negotiation.
          </div>
          <div className="row gap-2" style={{ marginTop: 8 }}>
            <Button size="sm" variant="primary" icon="bolt">Start renewal</Button>
            <Button size="sm" variant="ghost" icon="mail">Email {contract.counterparty.split(' ')[0]}</Button>
          </div>
        </div>
      )}

      <div className="grid g-2" style={{ gap: 10, marginBottom: 18 }}>
        <InfoRow icon="card" label="Value" value={contract.value ? fmtMoneyFull(contract.value) + (contract.billing ? ` / ${contract.billing.split(' ')[0]}` : '') : 'N/A'} />
        <InfoRow icon="cal" label="Term" value={contract.billing} />
        <InfoRow icon="cal" label="Effective" value={fmtDate(contract.startDate)} />
        <InfoRow icon="cal" label="Expires" value={contract.endDate ? fmtDate(contract.endDate) : 'Evergreen'} />
        <InfoRow icon="users" label="Internal owner" value={owner?.name} />
        <InfoRow icon="users" label="Internal signer" value={signerInt?.name || '—'} />
        <InfoRow icon="globe" label="Counterparty signer" value={contract.signerExt} />
        <InfoRow icon="bell" label="Renewal notice" value={contract.renewalNotice ? `${contract.renewalNotice} days` : 'None'} />
      </div>

      {customer && (
        <>
          <SectionTitle>Linked customer</SectionTitle>
          <div className="card" style={{ padding: 10 }}>
            <div className="row gap-2">
              <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-elev)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, color: 'var(--brand-wine)' }}>{customer.name[0]}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: 13 }}>{customer.name}</div>
                <div className="dim" style={{ fontSize: 11.5 }}>{customer.tier} · {customer.industry} · MRR {customer.mrr ? fmtMoneyFull(customer.mrr) : '—'}</div>
              </div>
              <Button size="sm" variant="ghost" iconRight="arrow_r">Open in CRM</Button>
            </div>
          </div>
        </>
      )}

      <SectionTitle>Files ({contract.files.length})</SectionTitle>
      <div className="col" style={{ gap: 6 }}>
        {contract.files.map((f, i) => {
          const ext = f.name.split('.').pop().toLowerCase();
          const kind = FILE_KINDS[ext] || { color: '#5C6470', label: ext.toUpperCase().slice(0,3) };
          return (
            <div key={i} className="row gap-2" style={{ padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 6 }}>
              <span className="file-glyph" style={{ background: kind.color, width: 22, height: 22, fontSize: 9 }}>{kind.label}</span>
              <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500 }}>{f.name}</span>
              <span className="dim mono" style={{ fontSize: 11 }}>{fileBytes(f.size)}</span>
              <Button size="sm" variant="ghost" icon="download" />
            </div>
          );
        })}
        <Button variant="ghost" icon="upload" size="sm" style={{ justifyContent: 'center', border: '1px dashed var(--border-strong)', marginTop: 4 }}>Attach additional file</Button>
      </div>

      <SectionTitle>Lifecycle</SectionTitle>
      <div className="col" style={{ gap: 0, position: 'relative', paddingLeft: 16 }}>
        <div style={{ position: 'absolute', left: 6, top: 8, bottom: 8, width: 1, background: 'var(--border-strong)' }} />
        {[
          { label: 'Drafted', date: contract.signedOn ? new Date(new Date(contract.signedOn).getTime() - 14*86400000).toISOString().split('T')[0] : new Date(contract.startDate).toISOString().split('T')[0], done: true },
          { label: 'Reviewed by legal', date: contract.signedOn ? new Date(new Date(contract.signedOn).getTime() - 5*86400000).toISOString().split('T')[0] : null, done: !!contract.signedOn || contract.status === 'Pending signature' },
          { label: 'Signed', date: contract.signedOn, done: !!contract.signedOn },
          { label: 'Effective', date: contract.startDate, done: new Date(contract.startDate) <= today },
          { label: 'Expires', date: contract.endDate || 'Evergreen', done: contract.status === 'Expired' },
        ].map((step, i) => (
          <div key={i} className="row gap-3" style={{ padding: '8px 0', position: 'relative' }}>
            <div style={{ position: 'absolute', left: -16, top: 12, width: 13, height: 13, borderRadius: 999, background: step.done ? 'var(--green)' : 'var(--bg-card)', border: step.done ? 'none' : '1.5px solid var(--border-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
              {step.done && <Icon name="check" size={8} stroke={3} />}
            </div>
            <span style={{ fontSize: 13, flex: 1, fontWeight: step.done ? 500 : 400, color: step.done ? 'var(--text)' : 'var(--text-muted)' }}>{step.label}</span>
            <span className="dim mono" style={{ fontSize: 11 }}>{typeof step.date === 'string' && step.date !== 'Evergreen' ? fmtDateShort(step.date) : (step.date || '—')}</span>
          </div>
        ))}
      </div>

      <SectionTitle>Tags</SectionTitle>
      <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
        {contract.tags.map(tag => <Badge key={tag} tone="orange">#{tag}</Badge>)}
      </div>

      <div className="row gap-2" style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
        <Button variant="secondary" icon="download">Download all</Button>
        <Button variant="secondary" icon="send">Send for signature</Button>
        <Button variant="ghost" icon="pencil" style={{ marginLeft: 'auto' }}>Edit terms</Button>
      </div>
    </div>
  );
}

window.Contracts = Contracts;

// ─────────────────────────────────────────────────────────────────────────────
// New Contract modal — lightweight tracking record + PDF upload
// ─────────────────────────────────────────────────────────────────────────────

function NewContractModal({ onClose, onCreate }) {
  const D = window.HitcentsData;
  const [draft, setDraft] = useState({
    type: 'customer',
    name: '',
    companyId: '',
    counterparty: '',
    value: 100000,
    billing: 'Annual',
    startDate: '2026-06-01',
    endDate: '2027-05-31',
    evergreen: false,
    status: 'Draft',
    autoRenew: true,
    renewalNotice: 60,
  });
  const [files, setFiles] = useState([]);
  const [dragOver, setDragOver] = useState(false);
  const fileRef = useRef(null);

  function set(patch) { setDraft(d => ({ ...d, ...patch })); }

  function pickCompany(cid) {
    const c = D.CUSTOMERS.find(x => x.id === cid);
    set({ companyId: cid, counterparty: c ? c.name : '', name: draft.name || (c ? `${c.name} — ` : '') });
  }

  function onFiles(list) {
    const added = Array.from(list).map(f => ({ name: f.name, size: f.size || 0 }));
    setFiles(fs => [...fs, ...added]);
  }
  function removeFile(i) { setFiles(fs => fs.filter((_, idx) => idx !== i)); }

  const counterpartyName = draft.type === 'customer'
    ? (D.CUSTOMERS.find(c => c.id === draft.companyId)?.name || '')
    : draft.counterparty;

  const canCreate = draft.name.trim() && counterpartyName.trim();

  function submit() {
    if (!canCreate) return;
    const prefix = draft.type === 'customer' ? 'CT-1' : draft.type === 'vendor' ? 'CT-2' : 'CT-9';
    const id = `${prefix}${String(Math.floor(Math.random() * 900) + 100)}`;
    const contract = {
      id,
      name: draft.name.trim(),
      type: draft.type,
      counterparty: counterpartyName.trim(),
      customerId: draft.type === 'customer' ? (draft.companyId || null) : null,
      value: draft.value,
      billing: draft.billing,
      status: draft.status,
      signedOn: draft.status === 'Active' || draft.status === 'Renewing' ? draft.startDate : null,
      startDate: draft.startDate,
      endDate: draft.evergreen ? null : draft.endDate,
      autoRenew: draft.autoRenew,
      renewalNotice: draft.renewalNotice,
      owner: draft.type === 'customer' ? 'e20' : 'e9',
      signerExt: counterpartyName.trim(),
      signerInt: 'e1',
      files: files.length ? files : [{ name: `${draft.name.trim() || 'contract'}.pdf`, size: 320000 }],
      tags: [draft.type],
    };
    onCreate(contract);
  }

  const typeMeta = D.CONTRACT_TYPES.find(t => t.id === draft.type);

  return (
    <div className="cmdk-scrim" onClick={onClose} style={{ paddingTop: '7vh', alignItems: 'flex-start' }}>
      <div onClick={e => e.stopPropagation()}
           style={{ width: 620, maxWidth: '94vw', maxHeight: '86vh', background: 'var(--bg-card)', borderRadius: 14, border: '1px solid var(--border)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>

        {/* Header */}
        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>New contract</h2>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>Track a customer or vendor agreement and attach the signed PDF.</div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>

        {/* Body */}
        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          {/* Type */}
          <div className="field" style={{ margin: 0, marginBottom: 16 }}>
            <label>Contract type</label>
            <div className="nc-type-grid">
              {[
                { id: 'customer', label: 'Customer', desc: 'Revenue — we sell', icon: 'card' },
                { id: 'vendor',   label: 'Vendor',   desc: 'Spend — we buy', icon: 'store' },
              ].map(t => (
                <button key={t.id} type="button" onClick={() => set({ type: t.id, companyId: '', counterparty: '' })}
                        className={`nc-type ${draft.type === t.id ? 'active' : ''}`}>
                  <div className="nc-type-icon"><Icon name={t.icon} size={16} /></div>
                  <div style={{ textAlign: 'left' }}>
                    <div style={{ fontWeight: 600, fontSize: 13 }}>{t.label}</div>
                    <div className="dim" style={{ fontSize: 11 }}>{t.desc}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Counterparty + name */}
          <div className="nc-row2">
            {draft.type === 'customer' ? (
              <div className="field" style={{ margin: 0 }}>
                <label>Company</label>
                <select value={draft.companyId} onChange={e => pickCompany(e.target.value)}>
                  <option value="">— Select a company —</option>
                  {D.CUSTOMERS.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </select>
              </div>
            ) : (
              <div className="field" style={{ margin: 0 }}>
                <label>Vendor / counterparty</label>
                <input placeholder="e.g. Amazon Web Services" value={draft.counterparty} onChange={e => set({ counterparty: e.target.value })} />
              </div>
            )}
            <div className="field" style={{ margin: 0 }}>
              <label>Contract title</label>
              <input placeholder="e.g. MSA + Order Form" value={draft.name} onChange={e => set({ name: e.target.value })} />
            </div>
          </div>

          {/* Value + billing */}
          <div className="nc-row2" style={{ marginTop: 14 }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Contract value</label>
              <div style={{ position: 'relative' }}>
                <span style={{ position: 'absolute', left: 12, top: 9, color: 'var(--text-muted)', fontSize: 13.5 }}>$</span>
                <input type="number" min="0" step="1000" value={draft.value} onChange={e => set({ value: +e.target.value })} style={{ paddingLeft: 24, width: '100%' }} />
              </div>
            </div>
            <div className="field" style={{ margin: 0 }}>
              <label>Billing</label>
              <select value={draft.billing} onChange={e => set({ billing: e.target.value })}>
                {['Annual','Annual · 2yr','Monthly','One-time','Per partner','Revenue share'].map(b => <option key={b}>{b}</option>)}
              </select>
            </div>
          </div>

          {/* Period */}
          <div className="field" style={{ margin: 0, marginTop: 14 }}>
            <div className="row spread" style={{ marginBottom: 6 }}>
              <span style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 500, whiteSpace: 'nowrap' }}>Contract period</span>
              <label className="nc-evergreen">
                <input type="checkbox" checked={draft.evergreen} onChange={e => set({ evergreen: e.target.checked })} />
                Evergreen (no end date)
              </label>
            </div>
            <div className="nc-row2">
              <input type="date" value={draft.startDate} onChange={e => set({ startDate: e.target.value })}
                     style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5 }} />
              <input type="date" value={draft.endDate} disabled={draft.evergreen} onChange={e => set({ endDate: e.target.value })}
                     style={{ border: '1px solid var(--border-strong)', borderRadius: 8, padding: '9px 12px', fontSize: 13.5, opacity: draft.evergreen ? 0.5 : 1 }} />
            </div>
          </div>

          {/* Status + auto-renew */}
          <div className="nc-row2" style={{ marginTop: 14, alignItems: 'flex-end' }}>
            <div className="field" style={{ margin: 0 }}>
              <label>Status</label>
              <select value={draft.status} onChange={e => set({ status: e.target.value })}>
                {['Draft','Pending signature','Active','Renewing','Expired'].map(s => <option key={s}>{s}</option>)}
              </select>
            </div>
            <label className="nc-autorenew">
              <input type="checkbox" checked={draft.autoRenew} onChange={e => set({ autoRenew: e.target.checked })} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontWeight: 500, fontSize: 13, whiteSpace: 'nowrap' }}>Auto-renew</div>
                <div className="dim" style={{ fontSize: 11, whiteSpace: 'nowrap' }}>{draft.autoRenew ? `${draft.renewalNotice}-day notice` : 'Manual renewal'}</div>
              </div>
            </label>
          </div>

          {/* PDF upload */}
          <div className="field" style={{ margin: 0, marginTop: 16 }}>
            <label>Signed PDF</label>
            <div className={`nc-drop ${dragOver ? 'over' : ''}`}
                 onClick={() => fileRef.current?.click()}
                 onDragOver={e => { e.preventDefault(); setDragOver(true); }}
                 onDragLeave={() => setDragOver(false)}
                 onDrop={e => { e.preventDefault(); setDragOver(false); onFiles(e.dataTransfer.files); }}>
              <input ref={fileRef} type="file" accept="application/pdf" multiple style={{ display: 'none' }}
                     onChange={e => onFiles(e.target.files)} />
              <Icon name="upload" size={20} />
              <div style={{ fontSize: 13, fontWeight: 500, marginTop: 6 }}>Drop a PDF here or click to browse</div>
              <div className="dim" style={{ fontSize: 11.5 }}>The signed agreement and any addenda</div>
            </div>
            {files.length > 0 && (
              <div className="col" style={{ gap: 6, marginTop: 10 }}>
                {files.map((f, i) => (
                  <div key={i} className="row gap-2" style={{ padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 6 }}>
                    <span className="file-glyph" style={{ background: '#C2452C', width: 22, height: 22, fontSize: 9 }}>PDF</span>
                    <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</span>
                    {f.size > 0 && <span className="dim mono" style={{ fontSize: 11 }}>{fileBytes(f.size)}</span>}
                    <button className="icon-btn" style={{ width: 22, height: 22 }} onClick={(e) => { e.stopPropagation(); removeFile(i); }}><Icon name="x" size={12} /></button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'var(--bg-elev)' }}>
          <div className="row gap-2">
            <Badge tone={typeMeta?.tone || 'neutral'}>{typeMeta?.name}</Badge>
            <span className="dim" style={{ fontSize: 11.5 }}>{fmtMoney(draft.value)} · {draft.billing}</span>
          </div>
          <div className="row gap-2">
            {!canCreate && <span className="dim" style={{ fontSize: 11.5 }}>Counterparty & title required</span>}
            <Button variant="ghost" onClick={onClose}>Cancel</Button>
            <Button variant="primary" icon="check" disabled={!canCreate} onClick={submit}>Create contract</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.NewContractModal = NewContractModal;
