// LedgerBeaver — The Dam · Partner Hub
// People wiki: list + slide-over + timeline + relationship graph + dashboard widget
//
// SUPABASE: see app/dam-data.js for query shapes. List is paginated via
//           supabase.from('people').select('*', { count: 'exact' }).range(...)

const useState_dam = React.useState;
const useEffect_dam = React.useEffect;
const useMemo_dam = React.useMemo;
const useRef_dam = React.useRef;
const damD = window.LB_DAM;

// Type → color/label
const TYPE_META = {
  internal: { label: 'Internal', color: 'amber',  icon: 'user' },
  vendor:   { label: 'Vendor',   color: 'ap',     icon: 'vendors' },
  customer: { label: 'Customer', color: 'ar',     icon: 'building' },
  partner:  { label: 'Partner',  color: 'vendor', icon: 'shield' },
};
const HEALTH_META = {
  active:   { label: 'Active',  color: 'ok' },
  warning:  { label: 'Watch',   color: 'warn' },
  overdue:  { label: 'Overdue', color: 'err' },
  invited:  { label: 'Invited', color: 'info' },
  new:      { label: 'New',     color: 'amber' },
};
const EVENT_META = {
  invoice:  { color: 'var(--ap)',     icon: 'ap' },
  payment:  { color: 'var(--ar)',     icon: 'ar' },
  email:    { color: 'var(--info)',   icon: 'mail' },
  call:     { color: 'var(--amber)',  icon: 'bot' },
  note:     { color: 'var(--text-mid)', icon: 'edit' },
  meeting:  { color: 'var(--gl)',     icon: 'user' },
  edit:     { color: 'var(--text-lo)', icon: 'settings' },
};

// ====================================================================
// MAIN SCREEN — The Dam
// ====================================================================
const ScreenDam = ({ goto }) => {
  const [layout, setLayout]  = useState_dam(() => localStorage.getItem('lb.dam.layout') || 'table');
  const [density, setDensity] = useState_dam(() => localStorage.getItem('lb.dam.density') || 'comfy');
  const [showHealth, setShowHealth] = useState_dam(() => localStorage.getItem('lb.dam.health') !== '0');
  const [showBalance, setShowBalance] = useState_dam(() => localStorage.getItem('lb.dam.balance') !== '0');
  const [type, setType]      = useState_dam('all');
  const [q, setQ]            = useState_dam('');
  const [sel, setSel]        = useState_dam(null);
  const [showAdd, setShowAdd] = useState_dam(false);

  // Persist tweaks
  useEffect_dam(() => { localStorage.setItem('lb.dam.layout', layout); }, [layout]);
  useEffect_dam(() => { localStorage.setItem('lb.dam.density', density); }, [density]);
  useEffect_dam(() => { localStorage.setItem('lb.dam.health', showHealth ? '1' : '0'); }, [showHealth]);
  useEffect_dam(() => { localStorage.setItem('lb.dam.balance', showBalance ? '1' : '0'); }, [showBalance]);

  // Listen for ⌘K → person navigation (dispatched from search)
  useEffect_dam(() => {
    const onOpen = (e) => { if (e.detail?.personId) setSel(e.detail.personId); };
    window.addEventListener('lb-dam-open', onOpen);
    return () => window.removeEventListener('lb-dam-open', onOpen);
  }, []);

  const filtered = useMemo_dam(() => {
    let xs = damD.people;
    if (type !== 'all') xs = xs.filter(p => p.type === type);
    if (q.trim()) {
      const qq = q.toLowerCase();
      xs = xs.filter(p =>
        p.name.toLowerCase().includes(qq) ||
        p.org.toLowerCase().includes(qq)  ||
        (p.email || '').toLowerCase().includes(qq) ||
        (p.tags || []).some(t => t.toLowerCase().includes(qq))
      );
    }
    return xs;
  }, [q, type]);

  const counts = useMemo_dam(() => {
    const c = { all: damD.people.length };
    Object.keys(TYPE_META).forEach(k => { c[k] = damD.people.filter(p => p.type === k).length; });
    return c;
  }, []);

  const selected = sel ? damD.people.find(p => p.id === sel) : null;

  return (
    <div className="screen">
      <SectionHead
        kicker="THE DAM · PARTNER HUB"
        title={<>People &amp; relationships <span style={{color:'var(--amber)'}}>·</span> auto-grown by Claude</>}
        sub="Every vendor, customer, teammate, and partner you've touched — stitched together with the events, invoices, and approvals that connect them."
        actions={<>
          <div className="dam-layout-toggle">
            <button className={layout === 'table' ? 'on' : ''} onClick={() => setLayout('table')} title="Table"><Icon name="rows" size={13} /></button>
            <button className={layout === 'grid' ? 'on' : ''}  onClick={() => setLayout('grid')}  title="Card grid"><Icon name="grid" size={13} /></button>
            <button className={layout === 'kanban' ? 'on' : ''} onClick={() => setLayout('kanban')} title="Kanban by type"><Icon name="board" size={13} /></button>
          </div>
          <button className="btn btn-ghost"><Icon name="download" size={14} /> Export</button>
          <button className="btn btn-primary" onClick={() => setShowAdd(true)}><Icon name="plus" size={14} /> Add person</button>
        </>}
      />

      {/* Auto-growth banner: explains how the Dam fills itself */}
      <div className="dam-banner">
        <span className="dam-banner-mascot">
          <Beaver pose="reading" size={56} halo="stamp" anim="idle" />
        </span>
        <div className="dam-banner-body">
          <strong>The Dam grows itself.</strong>
          <span> Claude added <em>{damD.people.filter(p=>p.autoPop).length}</em> people from invoices &amp; emails this week — last update 12m ago. You stay in control: edit any field, merge duplicates, or hide.</span>
        </div>
        <button className="dam-banner-close" title="Dismiss" onClick={(e) => e.currentTarget.closest('.dam-banner').style.display='none'}>×</button>
      </div>

      {/* Toolbar — filter chips + search + view tools */}
      <div className="dam-toolbar">
        <div className="dam-chips">
          {[
            ['all',     'All',       counts.all],
            ['internal','Internal',  counts.internal],
            ['vendor',  'Vendors',   counts.vendor],
            ['customer','Customers', counts.customer],
            ['partner', 'Partners',  counts.partner],
          ].map(([k, l, n]) => (
            <button key={k} className={"dam-chip " + (type === k ? 'on' : '')} onClick={() => setType(k)}>
              {k !== 'all' && <span className="dot" data-c={TYPE_META[k]?.color} />}
              {l} <span className="n">{n}</span>
            </button>
          ))}
        </div>
        <div className="dam-search">
          <Icon name="search" size={13} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Name, org, email, tag…" />
        </div>
        <DamTools
          density={density} setDensity={setDensity}
          showHealth={showHealth} setShowHealth={setShowHealth}
          showBalance={showBalance} setShowBalance={setShowBalance}
        />
      </div>

      {/* Body */}
      {filtered.length === 0 ? (
        <div className="state" style={{ marginTop: 20 }}>
          <Beaver pose="think" size={110} halo="glow" anim="idle" />
          <h4>Nobody matches that filter.</h4>
          <p>Clear search or pick a different segment chip above.</p>
          <button className="btn btn-soft" onClick={() => { setQ(''); setType('all'); }}>Clear filters</button>
        </div>
      ) : layout === 'grid' ? (
        <DamGrid people={filtered} density={density} showHealth={showHealth} showBalance={showBalance} onOpen={setSel} />
      ) : layout === 'kanban' ? (
        <DamKanban people={filtered} onOpen={setSel} />
      ) : (
        <DamTable people={filtered} density={density} showHealth={showHealth} showBalance={showBalance} onOpen={setSel} selectedId={sel} />
      )}

      {/* Slide-over */}
      <PersonSlideOver
        person={selected}
        onClose={() => setSel(null)}
        onSelect={setSel}
      />

      {/* Add modal */}
      {showAdd && <AddPersonModal onClose={() => setShowAdd(false)} />}
    </div>
  );
};

// ====================================================================
// LAYOUTS
// ====================================================================
const DamTable = ({ people, density, showHealth, showBalance, onOpen, selectedId }) => (
  <div className="card panel" style={{ padding: 0, overflow: 'hidden' }}>
    <table className={"lb-table dam-table " + (density === 'compact' ? 'compact' : '')}>
      <thead>
        <tr>
          <th>Person</th>
          <th>Type</th>
          <th>Tags</th>
          {showHealth && <th>Health</th>}
          {showBalance && <th>Balance</th>}
          <th>Last seen</th>
          <th>Added by</th>
        </tr>
      </thead>
      <tbody>
        {people.map(p => (
          <tr key={p.id} className={selectedId === p.id ? 'sel' : ''} onClick={() => onOpen(p.id)}>
            <td>
              <div className="dam-person-cell">
                <span className="dam-ava" data-c={p.accent}>{p.initials}</span>
                <div>
                  <div className="dam-name">{p.name}</div>
                  <div className="dam-org">{p.role} · {p.org}</div>
                </div>
              </div>
            </td>
            <td><TypeBadge type={p.type} /></td>
            <td>
              <div className="dam-tags">
                {(p.tags || []).slice(0, 2).map(t => <Tag key={t} name={t} />)}
                {(p.tags || []).length > 2 && <span className="dam-tag-more">+{p.tags.length - 2}</span>}
              </div>
            </td>
            {showHealth && <td><HealthChip h={p.health} /></td>}
            {showBalance && (
              <td className="mono num">
                {p.balance === 0 ? <span className="muted">—</span>
                  : <span style={{ color: p.type === 'customer' ? 'var(--ar)' : 'var(--ap)' }}>{fmt(p.balance)}</span>}
              </td>
            )}
            <td className="mono"><span className="muted">{p.lastAt}</span></td>
            <td>{p.autoPop ? <AgentChip name="Claude" /> : <span className="muted-sm" style={{fontFamily:'var(--font-mono)'}}>YOU</span>}</td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);

const DamGrid = ({ people, density, showHealth, showBalance, onOpen }) => (
  <div className={"dam-grid " + (density === 'compact' ? 'compact' : '')}>
    {people.map(p => (
      <div key={p.id} className="dam-card" onClick={() => onOpen(p.id)}>
        <div className="dam-card-top">
          <span className="dam-ava lg" data-c={p.accent}>{p.initials}</span>
          <TypeBadge type={p.type} />
        </div>
        <div className="dam-card-name">{p.name}</div>
        <div className="dam-card-org">{p.role} · {p.org}</div>
        <div className="dam-card-meta">
          {showHealth && <HealthChip h={p.health} />}
          {showBalance && p.balance > 0 && (
            <span className="dam-balance" style={{ color: p.type === 'customer' ? 'var(--ar)' : 'var(--ap)' }}>{fmt(p.balance)}</span>
          )}
          <span className="dam-card-time mono">{p.lastAt}</span>
        </div>
        <div className="dam-tags">
          {(p.tags || []).slice(0, 3).map(t => <Tag key={t} name={t} />)}
        </div>
      </div>
    ))}
  </div>
);

const DamKanban = ({ people, onOpen }) => {
  const cols = ['internal', 'vendor', 'customer', 'partner'];
  return (
    <div className="dam-kanban">
      {cols.map(c => {
        const xs = people.filter(p => p.type === c);
        return (
          <div className="dam-kan-col" key={c}>
            <div className="dam-kan-h">
              <TypeBadge type={c} />
              <span className="n">{xs.length}</span>
            </div>
            <div className="dam-kan-list">
              {xs.map(p => (
                <div key={p.id} className="dam-kan-card" onClick={() => onOpen(p.id)}>
                  <div className="dam-kan-top">
                    <span className="dam-ava" data-c={p.accent}>{p.initials}</span>
                    <span className="dam-kan-name">{p.name}</span>
                    <HealthChip h={p.health} mini />
                  </div>
                  <div className="dam-kan-org">{p.org}</div>
                </div>
              ))}
              {xs.length === 0 && <div className="dam-kan-empty">No one in this segment yet.</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
};

// ====================================================================
// SHARED CHIPS
// ====================================================================
const TypeBadge = ({ type }) => {
  const m = TYPE_META[type] || TYPE_META.internal;
  return <span className="dam-type-badge" data-c={m.color}><span className="dot" />{m.label}</span>;
};
const HealthChip = ({ h, mini }) => {
  const m = HEALTH_META[h] || HEALTH_META.active;
  return <span className={"dam-health " + (mini ? 'mini' : '')} data-c={m.color}>● {m.label}</span>;
};
const Tag = ({ name, onRemove }) => {
  const cat = damD.tagCatalog.find(t => t.name === name);
  return (
    <span className="dam-tag" data-c={cat?.color || 'neutral'}>
      {name}
      {onRemove && <button className="rm" onClick={(e) => { e.stopPropagation(); onRemove(name); }}>×</button>}
    </span>
  );
};

// ====================================================================
// INLINE TOOLS STRIP
// ====================================================================
const DamTools = ({ density, setDensity, showHealth, setShowHealth, showBalance, setShowBalance }) => (
  <div className="dam-tools">
    <span className="dam-tools-h">View</span>
    <div className="dam-tools-row">
      <button className={density === 'comfy' ? 'on' : ''} onClick={() => setDensity('comfy')}>Comfy</button>
      <button className={density === 'compact' ? 'on' : ''} onClick={() => setDensity('compact')}>Compact</button>
    </div>
    <span className="dam-tools-sep" />
    <div className="dam-tools-row">
      <label><input type="checkbox" checked={showHealth} onChange={e => setShowHealth(e.target.checked)} /> Health</label>
      <label><input type="checkbox" checked={showBalance} onChange={e => setShowBalance(e.target.checked)} /> Balance</label>
    </div>
  </div>
);

// ====================================================================
// SLIDE-OVER · Person Detail
// ====================================================================
const PersonSlideOver = ({ person, onClose, onSelect }) => {
  const [tab, setTab] = useState_dam('overview');
  const [editing, setEditing] = useState_dam(false);
  const [tagDraft, setTagDraft] = useState_dam('');
  const [localTags, setLocalTags] = useState_dam([]);
  const overlayRef = useRef_dam(null);

  useEffect_dam(() => {
    if (!person) return;
    setTab('overview');
    setEditing(false);
    setLocalTags(person.tags || []);
    // ESC to close
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [person, onClose]);

  if (!person) return null;
  const m = TYPE_META[person.type];
  const events = damD.events[person.id] || [];
  const rels   = damD.relationships.filter(r => r.from === person.id || r.to === person.id);

  const addTag = () => {
    const t = tagDraft.trim();
    if (!t || localTags.includes(t)) return;
    setLocalTags([...localTags, t]);
    setTagDraft('');
    // SUPABASE: UPDATE people SET tags = array_append(tags, $tag) WHERE id = $id
  };
  const removeTag = (t) => {
    setLocalTags(localTags.filter(x => x !== t));
    // SUPABASE: UPDATE people SET tags = array_remove(tags, $tag) WHERE id = $id
  };

  return (
    <div ref={overlayRef} className="dam-overlay" onMouseDown={(e) => { if (e.target === overlayRef.current) onClose(); }}>
      <aside className="dam-slide" role="dialog" aria-modal="true">
        {/* Header */}
        <div className="dam-slide-h">
          <button className="dam-slide-close" onClick={onClose} aria-label="Close">
            <Icon name="x" size={14} />
          </button>
          <div className="dam-slide-h-row">
            <span className="dam-ava xl" data-c={person.accent}>{person.initials}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <h2 className="dam-slide-name">{person.name}</h2>
              <div className="dam-slide-role">{person.role} · {person.org}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
                <TypeBadge type={person.type} />
                <HealthChip h={person.health} />
                {person.autoPop && <span className="dam-auto-pop" title="Claude auto-added this person from invoice ingestion">
                  <Icon name="bot" size={10} /> auto-grown
                </span>}
              </div>
            </div>
          </div>
          <div className="dam-slide-quick">
            <a className="dam-quick-btn" href={`mailto:${person.email}`}><Icon name="mail" size={13} /> {person.email}</a>
            <a className="dam-quick-btn" href={`tel:${person.phone}`}><Icon name="phone" size={13} /> {person.phone}</a>
          </div>
        </div>

        {/* Tabs */}
        <div className="dam-slide-tabs">
          {[
            ['overview',      'Overview'],
            ['timeline',      `Timeline · ${events.length}`],
            ['relationships', `Relationships · ${rels.length}`],
            ['info',          'Info'],
          ].map(([k, l]) => (
            <button key={k} className={tab === k ? 'on' : ''} onClick={() => setTab(k)}>{l}</button>
          ))}
        </div>

        {/* Body */}
        <div className="dam-slide-body">
          {tab === 'overview' && (
            <>
              {/* Quick stats */}
              <div className="dam-stats">
                <div>
                  <div className="dam-stat-l">{person.type === 'customer' ? 'Owed to you' : 'Owed by you'}</div>
                  <div className="dam-stat-v" style={{ color: person.balance > 0 ? (person.type === 'customer' ? 'var(--ar)' : 'var(--ap)') : 'var(--text-mid)' }}>
                    {person.balance > 0 ? fmt(person.balance) : '—'}
                  </div>
                </div>
                <div>
                  <div className="dam-stat-l">Terms</div>
                  <div className="dam-stat-v">{person.terms}</div>
                </div>
                <div>
                  <div className="dam-stat-l">Last seen</div>
                  <div className="dam-stat-v mono" style={{ fontSize: 16 }}>{person.lastAt}</div>
                </div>
              </div>

              {/* Notes */}
              <div className="dam-section">
                <div className="dam-sect-h">
                  <h4>Notes</h4>
                  <button className="dam-sect-edit" onClick={() => setEditing(!editing)}>
                    <Icon name="edit" size={11} /> {editing ? 'Done' : 'Edit'}
                  </button>
                </div>
                {editing ? (
                  <textarea className="dam-notes-edit" defaultValue={person.notes || ''} placeholder="Add a note about this person…" />
                ) : (
                  <p className="dam-notes">{person.notes || <em style={{ color: 'var(--text-lo)' }}>No notes yet.</em>}</p>
                )}
              </div>

              {/* Tags */}
              <div className="dam-section">
                <div className="dam-sect-h">
                  <h4>Tags</h4>
                </div>
                <div className="dam-tags-edit">
                  {localTags.map(t => <Tag key={t} name={t} onRemove={removeTag} />)}
                  <div className="dam-tag-add">
                    <input
                      value={tagDraft}
                      onChange={e => setTagDraft(e.target.value)}
                      onKeyDown={e => { if (e.key === 'Enter') addTag(); }}
                      placeholder="+ Add tag"
                    />
                  </div>
                </div>
              </div>

              {/* Recent timeline preview */}
              <div className="dam-section">
                <div className="dam-sect-h">
                  <h4>Recent activity</h4>
                  <button className="dam-sect-edit" onClick={() => setTab('timeline')}>View all →</button>
                </div>
                <Timeline events={events.slice(0, 3)} />
              </div>
            </>
          )}

          {tab === 'timeline' && (
            <div className="dam-section">
              <div className="dam-sect-h">
                <h4>Activity timeline</h4>
                <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--text-lo)' }}>
                  {events.length} EVENTS · NEWEST FIRST
                </span>
              </div>
              <Timeline events={events} />
            </div>
          )}

          {tab === 'relationships' && (
            <div className="dam-section">
              <div className="dam-sect-h">
                <h4>Relationship graph</h4>
                <button className="dam-sect-edit">
                  <Icon name="plus" size={11} /> Link
                </button>
              </div>
              <RelationshipGraph centerId={person.id} onSelect={onSelect} />
              <div className="dam-rel-list">
                {rels.map((r, i) => {
                  const other = r.from === person.id ? r.to : r.from;
                  const otherP = damD.people.find(p => p.id === other);
                  if (!otherP) return null;
                  return (
                    <div key={i} className="dam-rel-row" onClick={() => onSelect(other)}>
                      <span className="dam-ava sm" data-c={otherP.accent}>{otherP.initials}</span>
                      <div style={{ flex: 1 }}>
                        <div className="dam-rel-name">{otherP.name}</div>
                        <div className="dam-rel-label"><span className="kind">{r.type.replace('_', ' ')}</span> · {r.label}</div>
                      </div>
                      <TypeBadge type={otherP.type} />
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {tab === 'info' && (
            <div className="dam-section">
              <div className="dam-sect-h">
                <h4>Contact details</h4>
                <button className="dam-sect-edit"><Icon name="edit" size={11} /> Edit</button>
              </div>
              <div className="dam-info-rows">
                <div><span>Email</span><span>{person.email}</span></div>
                <div><span>Phone</span><span>{person.phone}</span></div>
                <div><span>Organization</span><span>{person.org}</span></div>
                <div><span>Role</span><span>{person.role}</span></div>
                <div><span>Type</span><span><TypeBadge type={person.type} /></span></div>
                <div><span>Payment terms</span><span>{person.terms}</span></div>
                <div><span>Added</span><span>{person.autoPop ? <span><AgentChip name="Claude" /> · auto-populated</span> : <span>You · manual</span>}</span></div>
              </div>
              <div className="dam-section" style={{ marginTop: 20 }}>
                <div className="dam-sect-h"><h4>Danger zone</h4></div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <button className="btn btn-soft" style={{ fontSize: 12 }}><Icon name="user" size={12} /> Merge duplicate</button>
                  <button className="btn btn-soft" style={{ fontSize: 12, color: 'var(--err)' }}><Icon name="x" size={12} /> Archive</button>
                </div>
              </div>
            </div>
          )}
        </div>
      </aside>
    </div>
  );
};

// ====================================================================
// TIMELINE
// ====================================================================
const Timeline = ({ events }) => {
  if (!events || events.length === 0) {
    return (
      <div className="dam-empty">
        <Beaver pose="reading" size={80} halo="glow" anim="idle" />
        <div>No events yet. Activity will land here as Claude posts and you act.</div>
      </div>
    );
  }
  return (
    <div className="dam-timeline">
      {events.map((e, i) => {
        const m = EVENT_META[e.type] || EVENT_META.note;
        const [d, time] = e.t.split(' ');
        return (
          <div className="dam-tl-row" key={i}>
            <div className="dam-tl-dot" style={{ background: m.color + '22', color: m.color, borderColor: m.color }}>
              <Icon name={m.icon} size={11} />
            </div>
            <div className="dam-tl-content">
              <div className="dam-tl-meta">
                <span className="dam-tl-type" style={{ color: m.color }}>{e.type.toUpperCase()}</span>
                <AgentChip name={e.source} />
                <time className="mono">{d.slice(5)} · {time}</time>
              </div>
              <div className="dam-tl-title">{e.title}</div>
              {e.body && <div className="dam-tl-body">{e.body}</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
};

// ====================================================================
// RELATIONSHIP GRAPH — central node + connection lines
// ====================================================================
const RelationshipGraph = ({ centerId, onSelect }) => {
  const center = damD.people.find(p => p.id === centerId);
  const rels   = damD.relationships.filter(r => r.from === centerId || r.to === centerId);
  // unique neighbors
  const seen = new Set();
  const neighbors = rels.map(r => {
    const otherId = r.from === centerId ? r.to : r.from;
    return { ...r, other: damD.people.find(p => p.id === otherId), otherId };
  }).filter(r => r.other && !seen.has(r.otherId) && seen.add(r.otherId));

  if (!center || neighbors.length === 0) {
    return (
      <div className="dam-empty" style={{ padding: '32px 16px' }}>
        <Beaver pose="point" size={70} halo="stamp" anim="idle" />
        <div>No connections yet — Claude links people as invoices &amp; emails flow.</div>
      </div>
    );
  }

  const w = 380, h = 280;
  const cx = w / 2, cy = h / 2;
  const r = 110;
  const items = neighbors.slice(0, 6).map((n, i, arr) => {
    const angle = (i / arr.length) * Math.PI * 2 - Math.PI / 2;
    return { ...n, x: cx + Math.cos(angle) * r, y: cy + Math.sin(angle) * r, angle };
  });

  return (
    <div className="dam-graph">
      <svg viewBox={`0 0 ${w} ${h}`} className="dam-graph-svg">
        <defs>
          <radialGradient id="cgrad" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="var(--amber-soft)" />
            <stop offset="100%" stopColor="transparent" />
          </radialGradient>
        </defs>
        <circle cx={cx} cy={cy} r="80" fill="url(#cgrad)" />
        {items.map((n, i) => (
          <g key={i}>
            <line x1={cx} y1={cy} x2={n.x} y2={n.y} stroke="var(--line-2)" strokeWidth="1.2" strokeDasharray="3 3" />
            <text x={(cx + n.x) / 2} y={(cy + n.y) / 2 - 4}
                  fontSize="9" fill="var(--text-lo)" textAnchor="middle"
                  fontFamily="var(--font-mono)" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>
              {n.type.replace('_', ' ')}
            </text>
          </g>
        ))}
      </svg>
      {/* center node */}
      <button className="dam-graph-node dam-graph-center" style={{ left: cx, top: cy }}>
        <span className="dam-ava xl" data-c={center.accent}>{center.initials}</span>
        <span className="dam-graph-label">{center.name.split(' ')[0]}</span>
      </button>
      {/* neighbor nodes */}
      {items.map((n, i) => (
        <button key={i} className="dam-graph-node" style={{ left: n.x, top: n.y }} onClick={() => onSelect(n.otherId)}>
          <span className="dam-ava" data-c={n.other.accent}>{n.other.initials}</span>
          <span className="dam-graph-label">{n.other.name.split(' ')[0]}</span>
        </button>
      ))}
    </div>
  );
};

// ====================================================================
// ADD PERSON MODAL (lightweight)
// ====================================================================
const AddPersonModal = ({ onClose }) => {
  const [type, setType] = useState_dam('vendor');
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 480 }}>
        <h3>Add to the Dam</h3>
        <p>Or just paste an invoice — Claude will add them automatically.</p>
        <div className="dam-type-picker">
          {Object.entries(TYPE_META).map(([k, m]) => (
            <button key={k} className={"dam-type-pick " + (type === k ? 'on' : '')} onClick={() => setType(k)} data-c={m.color}>
              <Icon name={m.icon} size={14} /> {m.label}
            </button>
          ))}
        </div>
        <div className="dam-form">
          <label>Name<input type="text" placeholder="Full name" /></label>
          <label>Role<input type="text" placeholder="e.g. AR Lead" /></label>
          <label>Organization<input type="text" placeholder="Company / firm" /></label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <label>Email<input type="email" placeholder="name@company.com" /></label>
            <label>Phone<input type="tel" placeholder="(415) 555-0100" /></label>
          </div>
        </div>
        <div className="modal-actions">
          <button className="btn btn-soft" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" onClick={onClose}><Icon name="check" size={14} /> Add to Dam</button>
        </div>
      </div>
    </div>
  );
};

// ====================================================================
// DASHBOARD WIDGET — for Console
// ====================================================================
const DamWidget = ({ goto }) => {
  const total = damD.people.length;
  const byType = {};
  Object.keys(TYPE_META).forEach(k => byType[k] = damD.people.filter(p => p.type === k).length);
  const recent = damD.people.slice().sort((a,b) => a.lastAt.localeCompare(b.lastAt)).slice(0, 4);
  const autoCount = damD.people.filter(p => p.autoPop).length;
  return (
    <div className="card panel dam-widget">
      <div className="panel-head">
        <div>
          <div className="eyebrow">THE DAM · PARTNER HUB</div>
          <h3 className="panel-title">{total} people · {autoCount} auto-grown</h3>
        </div>
        <button className="btn btn-ghost" onClick={() => goto('dam')}>Open <Icon name="arrowR" size={14} /></button>
      </div>

      <div className="dam-widget-stats">
        {Object.entries(byType).map(([k, n]) => (
          <button key={k} className="dam-widget-stat" data-c={TYPE_META[k].color} onClick={() => goto('dam')}>
            <span className="n">{n}</span>
            <span className="l">{TYPE_META[k].label.toLowerCase()}{n === 1 ? '' : 's'}</span>
          </button>
        ))}
      </div>

      <div className="dam-widget-recent">
        <div className="eyebrow" style={{ marginBottom: 8 }}>RECENT</div>
        {recent.map(p => (
          <div key={p.id} className="dam-widget-row" onClick={() => { goto('dam'); setTimeout(() => window.dispatchEvent(new CustomEvent('lb-dam-open', { detail: { personId: p.id } })), 50); }}>
            <span className="dam-ava sm" data-c={p.accent}>{p.initials}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="dam-widget-name">{p.name}</div>
              <div className="dam-widget-org">{p.org}</div>
            </div>
            <span className="dam-widget-time mono">{p.lastAt}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// Expose
window.ScreenDam   = ScreenDam;
window.DamWidget   = DamWidget;
