// Entity drawer — "Known from N sources" + merged timeline + learnings
// Opens from Fabric graph, catalog, people lists, retrieval provenance, etc.

const { useState: useEd } = React;

// Cross-source "resolved entity" drawer (CRM-style: known-from-N-sources,
// merged activity, merge evidence). Used for non-knowledge-graph demo entities
// (people / orgs / deals). Knowledge-graph nodes use the graph-backed
// EntityDrawer in pages.jsx, which delegates here when an id isn't a graph node.
function SourceEntityDrawer({ entity, onClose }) {
  const [tab, setTab] = useEd('activity');
  if (!entity) return null;

  // If the entity is Acme, use the rich data. Otherwise, synthesize a plausible one.
  const isAcme = entity.id === 'org_acme' || entity.id === 'acme';
  const sources = isAcme ? ACME.sources : synthesizeSources(entity);
  const timeline = isAcme ? ACME_TIMELINE : synthesizeTimeline(entity);
  const learnings = isAcme ? LEARNING_STREAM.slice(0, 5) : LEARNING_STREAM.slice(2, 5);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.25)', zIndex: 90,
      display: 'flex', justifyContent: 'flex-end',
      animation: 'fadeIn 160ms',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 640, height: '100%', background: 'var(--surface)',
        borderLeft: '1px solid var(--border)',
        boxShadow: 'var(--shadow-1)',
        display: 'flex', flexDirection: 'column',
        animation: 'slideInR 240ms cubic-bezier(.2,.8,.2,1)',
      }}>
        {/* Header */}
        <div style={{ padding: '20px 24px 0', borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <EntityAvatar entity={entity}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                <span className="chip" style={{ fontSize: 10 }}>{entity.type}</span>
                <h2 className="t-h2" style={{ margin: 0 }}>{entity.label || entity.name}</h2>
              </div>
              {entity.sub && <div className="text-secondary t-small mt-4">{entity.sub}</div>}

              {/* Known from N sources — the key message */}
              <div style={{
                marginTop: 14, padding: '10px 14px',
                background: 'var(--accent-muted)',
                borderRadius: 8,
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <Icons.Sparkle size={14} style={{ color: 'var(--accent-text)', flexShrink: 0 }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--accent-text)' }}>
                    Known from {sources.length} source{sources.length === 1 ? '' : 's'}
                  </div>
                  <div className="t-small" style={{ color: 'var(--accent-text)', opacity: 0.8, marginTop: 2 }}>
                    {sources.map(s => VENDORS[s.vendor]?.name).join(' · ')}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 3 }}>
                  {sources.map(s => <VendorLogo key={s.id || s.vendor} vendor={s.vendor} size={22} radius={5}/>)}
                </div>
              </div>
            </div>
            <button className="btn sm ghost" onClick={onClose}><Icons.X size={14}/></button>
          </div>

          {/* Tabs */}
          <div style={{ marginTop: 16, display: 'flex', gap: 2 }}>
            {[
              ['activity',  'Merged activity'],
              ['merges',    'Merge evidence'],
              ['learnings', 'Learnings'],
              ['graph',     'Connections'],
            ].map(([id, label]) => (
              <button key={id} onClick={() => setTab(id)} style={{
                padding: '9px 12px',
                fontSize: 12, fontWeight: tab === id ? 500 : 400,
                color: tab === id ? 'var(--text-primary)' : 'var(--text-secondary)',
                borderBottom: `2px solid ${tab === id ? 'var(--accent)' : 'transparent'}`,
                marginBottom: -1,
              }}>{label}</button>
            ))}
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {tab === 'activity'  && <ActivityList timeline={timeline}/>}
          {tab === 'merges'    && <MergesList sources={sources}/>}
          {tab === 'learnings' && <LearningsList rows={learnings}/>}
          {tab === 'graph'     && <ConnectionsList entity={entity}/>}
        </div>

        {/* Footer */}
        <div style={{ padding: '12px 24px', borderTop: '1px solid var(--border-subtle)', display: 'flex', gap: 8 }}>
          <button className="btn sm">Open in Fabric <Icons.ArrowR size={11}/></button>
          <button className="btn sm">Cite in API</button>
          <div style={{ flex: 1 }}/>
          <button className="btn sm ghost"><Icons.More size={13}/></button>
        </div>
      </div>
    </div>
  );
}

function EntityAvatar({ entity }) {
  const t = entity.type;
  const bg = {
    Org:     '#E7F4F2', Person:  '#EEF0FE', Deal:    '#FBF2DC',
    Ticket:  '#FBE9EA', Doc:     '#F2F2F5', Channel: '#F3E8F6',
    Dataset: '#E6F6FB',
  }[t] || '#F2F2F5';
  const fg = {
    Org:     '#0F766E', Person:  '#4F46E5', Deal:    '#A16207',
    Ticket:  '#B91C1C', Doc:     '#475569', Channel: '#4A154B',
    Dataset: '#0369A1',
  }[t] || '#475569';
  const glyph = t === 'Person'
    ? (entity.label || 'A').split(' ').map(p => p[0]).slice(0, 2).join('')
    : (entity.label || 'A')[0];
  return (
    <div style={{
      width: 48, height: 48, borderRadius: 12,
      background: bg, color: fg,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 18, fontWeight: 600, flexShrink: 0,
    }}>{glyph}</div>
  );
}

// ----- Tabs -----

function ActivityList({ timeline }) {
  return (
    <div style={{ padding: '8px 24px 24px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '14px 0 10px' }}>
        <span style={{
          width: 7, height: 7, borderRadius: '50%', background: 'var(--success)',
          animation: 'parclePulseLoop 2s ease-out infinite',
        }}/>
        <span className="t-micro text-secondary">Live · interleaved from every connected source</span>
      </div>
      {timeline.map((ev, i) => <ActivityRow key={i} ev={ev} first={i === 0}/>)}
    </div>
  );
}

function ActivityRow({ ev, first }) {
  const lane = LANE_CONFIG[ev.lane] || { color: 'var(--text-tertiary)', label: ev.src };
  const v = VENDORS[ev.src];
  return (
    <div style={{ display: 'flex', gap: 12, padding: '12px 0', borderTop: first ? 'none' : '1px solid var(--border-subtle)' }}>
      <div style={{ width: 4, flexShrink: 0, background: lane.color, borderRadius: 2 }}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
          <VendorLogo vendor={ev.src} size={14} radius={3}/>
          <span className="mono-sm mono text-tertiary" style={{ fontSize: 11 }}>
            {v?.name} · {ev.date || ev.t}
          </span>
          {first && (
            <span style={{
              padding: '1px 6px', borderRadius: 4,
              background: 'var(--success-bg)', color: 'var(--success)',
              fontSize: 9, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em',
            }}>Live</span>
          )}
        </div>
        <div style={{ fontSize: 13 }}>
          <span style={{ fontWeight: 500 }}>{ev.actor}</span>{' '}
          <span className="text-secondary">{ev.verb}</span>{' '}
          <span style={{ fontWeight: 500, color: lane.color }}>{ev.target}</span>
        </div>
        <div className="t-small text-secondary" style={{ marginTop: 4 }}>{ev.preview}</div>
      </div>
    </div>
  );
}

function MergesList({ sources }) {
  return (
    <div style={{ padding: 24 }}>
      <div className="t-small text-secondary" style={{ marginBottom: 14 }}>
        Parcle resolved this entity across {sources.length} sources using the matches below. Each row is an auditable decision with a confidence score.
      </div>
      {sources.map(s => <MergeDetailRow key={s.id || s.vendor} src={s}/>)}
    </div>
  );
}

function MergeDetailRow({ src }) {
  const v = VENDORS[src.vendor];
  const pct = Math.round(src.conf * 100);
  return (
    <div style={{
      padding: 14, marginBottom: 10,
      border: '1px solid var(--border-subtle)', borderRadius: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <VendorLogo vendor={src.vendor} size={32} radius={8}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 500 }}>
            {v?.name} · <span className="text-secondary" style={{ fontWeight: 400 }}>{src.kind}</span>
          </div>
          <div className="mono-sm mono text-tertiary" style={{ marginTop: 2 }}>
            {src.count}
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: src.conf >= 0.95 ? 'var(--success)' : 'var(--accent-text)' }}>
            {pct}%
          </div>
          <div className="mono-sm mono text-tertiary" style={{ fontSize: 10 }}>confidence</div>
        </div>
      </div>
      <div style={{
        marginTop: 10, padding: 10,
        background: 'var(--bg)', borderRadius: 6,
        fontSize: 12, color: 'var(--text-secondary)',
      }}>
        <span className="t-micro text-tertiary" style={{ fontSize: 10, marginRight: 6 }}>MATCHED BY</span>
        {src.resolvedBy}
      </div>
    </div>
  );
}

function LearningsList({ rows }) {
  return (
    <div style={{ padding: 24 }}>
      <div className="t-small text-secondary" style={{ marginBottom: 14 }}>
        Recent things Parcle learned about this entity.
      </div>
      <div className="card" style={{ padding: 0 }}>
        {rows.map((r, i) => (
          <div key={r.id} style={{
            display: 'flex', gap: 12, padding: 14,
            borderTop: i === 0 ? 'none' : '1px solid var(--border-subtle)',
          }}>
            <div style={{ flexShrink: 0 }}><LearningGlyph type={r.type}/></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{r.title}</div>
              <div className="t-small text-secondary" style={{ marginTop: 3 }}>{r.body}</div>
              <div className="mono-sm mono text-tertiary" style={{ marginTop: 6, fontSize: 10 }}>
                {r.t} · conf {r.conf.toFixed(2)}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ConnectionsList({ entity }) {
  // Use Acme's graph as canonical demo even for other entities
  const edges = ACME_GRAPH_EDGES;
  const nodes = ACME_GRAPH_NODES;
  return (
    <div style={{ padding: 24 }}>
      <div className="t-small text-secondary" style={{ marginBottom: 14 }}>
        Related entities — expand to navigate the fabric.
      </div>
      {[
        { label: 'People',       filter: 'Person' },
        { label: 'Deals',        filter: 'Deal' },
        { label: 'Tickets',      filter: 'Ticket' },
        { label: 'Documents',    filter: 'Doc' },
        { label: 'Channels',     filter: 'Channel' },
        { label: 'Datasets',     filter: 'Dataset' },
      ].map(g => {
        const list = nodes.filter(n => n.type === g.filter);
        if (list.length === 0) return null;
        return (
          <div key={g.label} style={{ marginBottom: 18 }}>
            <div className="t-micro text-tertiary" style={{ marginBottom: 6 }}>{g.label} · {list.length}</div>
            {list.map(n => (
              <div key={n.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 6, fontSize: 13 }}>
                <span style={{ fontWeight: 500 }}>{n.label}</span>
                <span className="mono-sm mono text-tertiary" style={{ fontSize: 11 }}>· {n.sub}</span>
                <div style={{ flex: 1 }}/>
                <button className="btn sm ghost"><Icons.ChevronR size={11}/></button>
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
}

// Fallback data synthesizers (for non-Acme entities)
function synthesizeSources(entity) {
  const base = [
    { id: 'salescrm', vendor: 'salescrm', kind: 'Record',   count: 1,  conf: 1.00, resolvedBy: 'Primary ID match' },
    { id: 'gmail',    vendor: 'gmail',    kind: 'Mentions', count: 12, conf: 0.92, resolvedBy: 'Full name match + domain' },
    { id: 'chatroom', vendor: 'chatroom', kind: 'Messages', count: 48, conf: 0.88, resolvedBy: 'Username + display name' },
  ];
  return base;
}

function synthesizeTimeline(entity) {
  return [
    { t: 'just now', date: 'Today',    src: 'gmail',    lane: 'email', actor: entity.label || 'They', verb: 'mentioned in', target: 'thread', preview: 'Reference appeared in a recent conversation.' },
    { t: '1 h ago',  date: 'Today',    src: 'chatroom', lane: 'chat',  actor: entity.label || 'They', verb: 'tagged in',    target: '#general', preview: 'Referenced in team chat.' },
    { t: '1 d ago',  date: 'Yesterday',src: 'salescrm', lane: 'crm',   actor: entity.label || 'They', verb: 'linked to',    target: 'record', preview: 'CRM record updated.' },
  ];
}

Object.assign(window, { SourceEntityDrawer });
