// H2Learn — Network Hero Screen
// Six modes: Atlas / Orbital / Focus / Anti-dup / Need-Offer / Path
// Filters · detail drawer · why-connected · graph stats · legend

(function() {
  const D = window.H2Data;
  const L = window.GraphLayouts;
  const { useState, useMemo } = React;

  const MODES = [
    { key:'atlas',     label:'Atlas',          icon:'network',  desc:'Force-directed clusters' },
    { key:'orbital',   label:'Orbital',        icon:'target',   desc:'Ecosystem rings' },
    { key:'focus',     label:'Focus',          icon:'compass',  desc:'My local network' },
    { key:'antidup',   label:'Anti-duplication', icon:'alert',  desc:'Overlap detection' },
    { key:'needoffer', label:'Need ↔ Offer',   icon:'git',      desc:'Sankey-style flow' },
    { key:'path',      label:'Path',           icon:'arrowRight', desc:'Connection chain' },
  ];

  const ENTITY_FILTERS = [
    { key:'person', label:'People',     color:'var(--c-person)'  },
    { key:'project',label:'Projects',   color:'var(--c-project)' },
    { key:'org',    label:'Orgs',       color:'var(--c-org)'     },
    { key:'domain', label:'Domains',    color:'var(--c-domain)'  },
    { key:'method', label:'Methods',    color:'var(--c-method)'  },
    { key:'challenge',label:'Challenges',color:'var(--c-challenge)' },
  ];

  const REL_FILTERS = [
    'Similarity','Complementarity','Anti-duplication','Bridge',
    'Method transfer','Shared uncertainty','Need-offer','Project compatibility',
  ];

  const NetworkScreen = () => {
    const [mode, setMode] = useState('atlas');
    const [selectedNode, setSelectedNode] = useState('p_sara');
    const [hoveredNode, setHoveredNode] = useState(null);
    const [selectedEdge, setSelectedEdge] = useState(null);
    const [drawerView, setDrawerView] = useState('node'); // node | edge | why
    const [strengthMin, setStrengthMin] = useState(0.3);
    const [enabledTypes, setEnabledTypes] = useState(new Set(['person','project','org','domain','method']));
    const [enabledRels, setEnabledRels] = useState(new Set(REL_FILTERS));
    const [dimNonAdjacent, setDimNonAdjacent] = useState(false);

    // Compose graph data per mode
    const graph = useMemo(() => {
      if (mode === 'atlas') return { nodes: L.ATLAS.nodes, edges: L.ATLAS.edges, clusters: L.ATLAS.clusters };
      if (mode === 'orbital') {
        const placed = L.placeOrbital(L.ORBITAL);
        return { nodes: Object.values(placed), edges: L.ORBITAL.edges, rings: L.ORBITAL.rings, ringCenter: { cx: L.ORBITAL.cx, cy: L.ORBITAL.cy } };
      }
      if (mode === 'focus') {
        const f = L.buildFocus(selectedNode || 'p_sara');
        return { nodes: f.nodes, edges: f.edges };
      }
      if (mode === 'antidup') return { nodes: L.ANTIDUP.nodes, edges: L.ANTIDUP.edges, clusters: L.ANTIDUP.clusters };
      if (mode === 'path') {
        const f = L.buildPath([
          { id:'p_sara', kind:'person', initials:'SA', label:'You · Sara', edgeReason:'Has expertise in', relationTo:'Similarity' },
          { id:'d_pem', kind:'domain', initials:'P', label:'PEM', edgeReason:'Worked on by', relationTo:'Similarity' },
          { id:'p_liesbeth', kind:'person', initials:'LK', label:'Liesbeth', edgeReason:'Member of', relationTo:'Similarity' },
          { id:'o_tno', kind:'org', initials:'TN', label:'TNO', edgeReason:'Partner in', relationTo:'Similarity' },
          { id:'pj_hydronl', kind:'project', initials:'HN', label:'HYDRO-NL', edgeReason:'Led by', relationTo:'Similarity' },
        ]);
        return { nodes: f.nodes, edges: f.edges, viewBox: '0 0 1100 720' };
      }
      return { nodes: [], edges: [] };
    }, [mode, selectedNode]);

    // Filter
    const filtered = useMemo(() => {
      if (mode === 'needoffer') return graph;
      const ns = graph.nodes.filter(n => !enabledTypes.size || enabledTypes.has(n.kind));
      const ids = new Set(ns.map(n => n.id));
      const es = graph.edges.filter(e =>
        ids.has(e.s) && ids.has(e.t) &&
        enabledRels.has(e.type) &&
        (e.strength || 0) >= strengthMin
      );
      return { ...graph, nodes: ns, edges: es };
    }, [graph, enabledTypes, enabledRels, strengthMin, mode]);

    const onNodeClick = (n) => {
      setSelectedNode(n.id); setSelectedEdge(null); setDrawerView('node');
      if (mode === 'focus') {/* keep focus */}
    };
    const onEdgeClick = (e) => {
      setSelectedEdge(e); setDrawerView('edge');
    };

    const stats = useMemo(() => ({
      nodes: filtered.nodes?.length || 0,
      edges: filtered.edges?.length || 0,
      clusters: filtered.clusters?.length || 4,
      recommended: (filtered.edges || []).filter(e => e.recommended).length,
      antidup: (filtered.edges || []).filter(e => e.alert).length,
    }), [filtered]);

    return (
      <div style={{display:'grid', gridTemplateColumns:'260px 1fr 360px', gap: 0, height:'calc(100vh - 0px)', minHeight: 760, background: 'var(--bg)'}}>

        {/* ============ FILTER PANEL (left) ============ */}
        <FilterPanel
          mode={mode}
          enabledTypes={enabledTypes} setEnabledTypes={setEnabledTypes}
          enabledRels={enabledRels} setEnabledRels={setEnabledRels}
          strengthMin={strengthMin} setStrengthMin={setStrengthMin}
          dimNonAdjacent={dimNonAdjacent} setDimNonAdjacent={setDimNonAdjacent}
        />

        {/* ============ CANVAS (center) ============ */}
        <div className="col" style={{minWidth:0, padding: 16, gap: 12}}>

          {/* mode bar */}
          <div className="row items-center justify-between flex-wrap gap-3">
            <div className="row items-center gap-2 flex-wrap">
              {MODES.map(m => (
                <button key={m.key}
                  onClick={() => setMode(m.key)}
                  className={'btn ' + (mode === m.key ? 'primary' : '') + ' sm'}>
                  <Icon name={m.icon} size={13}/>{m.label}
                </button>
              ))}
            </div>
            <div className="row items-center gap-2">
              <div className="row items-center gap-2" style={{padding:'4px 10px', background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius: 'var(--r-2)'}}>
                <Icon name="search" size={13} color="var(--ink-3)"/>
                <input className="input" placeholder="Search node…" style={{padding:'2px 0', border:'none', background:'transparent', minWidth:140, fontSize:'var(--t-sm)'}}/>
                <span className="kbd">⌘K</span>
              </div>
              <Btn icon="bookmark" variant="ghost" size="sm" onClick={() => proto('View saved as "My ecosystem"', { tag:'simulated' })}>Save view</Btn>
              <Btn icon="download" variant="ghost" size="sm" onClick={() => proto('Network export — PNG/JSON in full build', { tag:'placeholder' })}>Export</Btn>
            </div>
          </div>

          {/* canvas + overlays */}
          <div style={{position:'relative', flex:1, minHeight: 540}}>
            {mode === 'needoffer' ? (
              <NeedOfferView onMatch={() => { setSelectedEdge({matchId:'m_01', type:'Complementarity', s:'p_sara', t:'pj_hydronl', strength: 0.88}); setDrawerView('edge'); }}/>
            ) : (
              <GraphCanvas
                {...filtered}
                viewBox={filtered.viewBox || '0 0 1200 720'}
                selectedNodeId={selectedNode} hoveredNodeId={hoveredNode}
                dimNonAdjacent={dimNonAdjacent}
                onNodeClick={onNodeClick} onNodeHover={setHoveredNode}
                onEdgeClick={onEdgeClick}
                height="100%"
                overlay={<>
                  <ModeBadge mode={mode}/>
                  <Legend/>
                  <GraphStats stats={stats}/>
                  <ZoomControls/>
                  {mode === 'antidup' && <AntiDupBanner/>}
                </>}
              />
            )}
          </div>

        </div>

        {/* ============ DETAIL DRAWER (right) ============ */}
        <DetailDrawer
          view={drawerView} setView={setDrawerView}
          selectedNode={selectedNode} setSelectedNode={setSelectedNode}
          selectedEdge={selectedEdge}
          mode={mode}
        />
      </div>
    );
  };

  // ============ Filter panel ============
  const FilterPanel = ({mode, enabledTypes, setEnabledTypes, enabledRels, setEnabledRels, strengthMin, setStrengthMin, dimNonAdjacent, setDimNonAdjacent}) => {
    const toggleSet = (set, setter, key) => {
      const next = new Set(set);
      if (next.has(key)) next.delete(key); else next.add(key);
      setter(next);
    };
    return (
      <div className="col" style={{borderRight:'1px solid var(--line)', background:'var(--surface)', overflowY:'auto', padding: '20px 18px', gap: 22}}>
        <div className="col gap-1">
          <div className="eyebrow">Network</div>
          <h2 style={{fontFamily:'var(--font-display)', fontSize:'var(--t-xl)', fontWeight:400, margin:0, letterSpacing:'-0.015em'}}>Ecosystem map</h2>
          <div style={{fontSize:'var(--t-xs)', color:'var(--ink-3)'}}>248 nodes · 134 edges across 4 clusters</div>
        </div>

        <FilterGroup title="Entity types">
          {ENTITY_FILTERS.map(t => (
            <FilterRow key={t.key}
              on={enabledTypes.has(t.key)}
              onClick={() => toggleSet(enabledTypes, setEnabledTypes, t.key)}
              swatch={<Swatch type={t.key} color={t.color}/>}
              label={t.label}
            />
          ))}
        </FilterGroup>

        <FilterGroup title="Relationships">
          {REL_FILTERS.map(r => {
            const meta = window.RelMeta[r] || window.RelMeta.Similarity;
            return (
              <FilterRow key={r}
                on={enabledRels.has(r)}
                onClick={() => toggleSet(enabledRels, setEnabledRels, r)}
                swatch={<EdgeSwatch type={r} color={meta.color}/>}
                label={r}
              />
            );
          })}
        </FilterGroup>

        <FilterGroup title="Strength threshold">
          <div className="col gap-2">
            <div className="row justify-between" style={{fontSize:'var(--t-xs)', color:'var(--ink-3)'}}>
              <span>min</span><span className="tnum">{strengthMin.toFixed(2)}</span>
            </div>
            <input type="range" min="0" max="1" step="0.05" value={strengthMin}
                   onChange={(e) => setStrengthMin(+e.target.value)}
                   style={{width:'100%', accentColor:'var(--accent)'}}/>
          </div>
        </FilterGroup>

        <FilterGroup title="Context filters">
          <ContextFilter label="Domain" options={['All','PEM','Membrane','Catalysts','LCA','Curriculum']}/>
          <ContextFilter label="Sector" options={['All','Research','Education','Industry','Public']}/>
          <ContextFilter label="TRL" options={['All','3–4','5–6','7+']}/>
          <ContextFilter label="Region" options={['All','NL','EU','Global']}/>
        </FilterGroup>

        <FilterGroup title="View options">
          <FilterRow on={dimNonAdjacent} onClick={() => setDimNonAdjacent(!dimNonAdjacent)} label="Dim non-adjacent"/>
          <FilterRow label="Curator-reviewed only"/>
          <FilterRow label="Newly added"/>
        </FilterGroup>

        <div className="col gap-2">
          <div className="label-hr">View presets</div>
          <Btn variant="ghost" size="sm" icon="star" style={{justifyContent:'flex-start', width:'100%'}} onClick={() => proto('Preset applied — your ecosystem', { tag:'simulated' })}>My ecosystem</Btn>
          <Btn variant="ghost" size="sm" icon="alert" style={{justifyContent:'flex-start', width:'100%'}} onClick={() => proto('Filtered to anti-duplication clusters', { tag:'simulated' })}>Anti-dup risks</Btn>
          <Btn variant="ghost" size="sm" icon="bridge" style={{justifyContent:'flex-start', width:'100%'}} onClick={() => proto('Filtered to bridge actors', { tag:'simulated' })}>Bridge actors</Btn>
        </div>
      </div>
    );
  };

  const FilterGroup = ({title, children}) => (
    <div className="col gap-2">
      <div className="label-hr">{title}</div>
      <div className="col gap-1">{children}</div>
    </div>
  );

  const FilterRow = ({on=true, onClick, swatch, label}) => (
    <button onClick={onClick} className="row items-center gap-3"
      style={{padding:'5px 6px', borderRadius:'var(--r-1)', textAlign:'left'}}>
      <span className={'switch' + (on ? ' on' : '')}/>
      {swatch}
      <span style={{fontSize:'var(--t-sm)', color: on?'var(--ink)':'var(--ink-3)', fontWeight: on?500:400}}>{label}</span>
    </button>
  );

  const Swatch = ({type, color}) => {
    if (type === 'project') return <span style={{width:14,height:14,background:'#fff',border:`1.6px solid ${color}`, transform:'rotate(30deg)', display:'inline-block'}}/>;
    if (type === 'org') return <span style={{width:14,height:14,background:'#fff',border:`1.6px solid ${color}`, borderRadius:3, display:'inline-block'}}/>;
    return <span style={{width:14,height:14,background:'#fff',border:`1.6px solid ${color}`, borderRadius:'50%', display:'inline-block'}}/>;
  };

  const EdgeSwatch = ({type, color}) => {
    const dash = type === 'Anti-duplication' ? '4 3' : type === 'Shared uncertainty' ? '2 4' : type === 'Method transfer' ? '3 2' : null;
    return (
      <svg width="22" height="14"><line x1="1" y1="7" x2="21" y2="7" stroke={color} strokeWidth="2" strokeDasharray={dash} strokeLinecap="round"/></svg>
    );
  };

  const ContextFilter = ({label, options}) => (
    <div className="row items-center justify-between gap-2" style={{padding:'4px 6px'}}>
      <span style={{fontSize:'var(--t-xs)', color:'var(--ink-3)'}}>{label}</span>
      <select className="select" style={{padding:'2px 22px 2px 8px', fontSize:'var(--t-xs)', width:'auto'}}>
        {options.map(o => <option key={o}>{o}</option>)}
      </select>
    </div>
  );

  // ============ Mode badge ============
  const ModeBadge = ({mode}) => {
    const m = MODES.find(x => x.key === mode);
    return (
      <div style={{position:'absolute', top: 16, left: 16, background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:'var(--r-3)', padding: '8px 12px', boxShadow:'var(--shadow-1)'}}>
        <div className="row items-center gap-2">
          <Icon name={m.icon} size={13} color="var(--accent)"/>
          <div className="col">
            <span style={{fontSize:'var(--t-xs)', color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em'}}>Mode</span>
            <span style={{fontSize:'var(--t-sm)', fontWeight:600}}>{m.label}</span>
          </div>
        </div>
      </div>
    );
  };

  // ============ Legend ============
  const Legend = () => {
    const items = [
      { kind:'Person',    color:'var(--c-person)',  shape:'circle'},
      { kind:'Project',   color:'var(--c-project)', shape:'hex'},
      { kind:'Org',       color:'var(--c-org)',     shape:'square'},
      { kind:'Domain',    color:'var(--c-domain)',  shape:'circle'},
      { kind:'Method',    color:'var(--c-method)',  shape:'circle'},
    ];
    const edges = [
      { type:'Similarity',     color:'var(--e-similar)' },
      { type:'Complementarity',color:'var(--e-comp)' },
      { type:'Anti-dup',       color:'var(--e-antidup)', dash:'4 3' },
      { type:'Bridge',         color:'var(--e-bridge)' },
      { type:'Method',         color:'var(--e-method)', dash:'3 2' },
    ];
    return (
      <div style={{position:'absolute', bottom: 16, left: 16, background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:'var(--r-3)', padding: 12, boxShadow:'var(--shadow-1)', maxWidth: 280}}>
        <div style={{fontSize:'var(--t-xs)', color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em', marginBottom: 6}}>Legend</div>
        <div className="row gap-3 flex-wrap" style={{marginBottom: 8}}>
          {items.map(i => (
            <div key={i.kind} className="row items-center gap-2"><Swatch type={i.kind.toLowerCase()} color={i.color}/><span style={{fontSize:'var(--t-xs)'}}>{i.kind}</span></div>
          ))}
        </div>
        <div className="row gap-3 flex-wrap">
          {edges.map(e => (
            <div key={e.type} className="row items-center gap-2"><EdgeSwatch type={e.type} color={e.color}/><span style={{fontSize:'var(--t-xs)'}}>{e.type}</span></div>
          ))}
        </div>
      </div>
    );
  };

  const GraphStats = ({stats}) => (
    <div style={{position:'absolute', bottom: 16, right: 16, background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:'var(--r-3)', padding: 12, boxShadow:'var(--shadow-1)', minWidth: 220}}>
      <div style={{fontSize:'var(--t-xs)', color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em', marginBottom: 8}}>Graph stats</div>
      <div className="grid cols-2" style={{gap: 8}}>
        <Stat v={stats.nodes} l="nodes"/>
        <Stat v={stats.edges} l="edges"/>
        <Stat v={stats.clusters} l="clusters"/>
        <Stat v={'0.8×'} l="zoom"/>
        <Stat v={stats.recommended} l="recommended" highlight="var(--accent)"/>
        <Stat v={stats.antidup} l="anti-dup" highlight="var(--e-antidup)"/>
      </div>
    </div>
  );
  const Stat = ({v, l, highlight}) => (
    <div className="col">
      <div className="tnum" style={{fontFamily:'var(--font-display)', fontSize: 22, lineHeight: 1, color: highlight || 'var(--ink)'}}>{v}</div>
      <div style={{fontSize: 10.5, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.08em'}}>{l}</div>
    </div>
  );

  const ZoomControls = () => (
    <div style={{position:'absolute', top: 16, right: 16, display:'flex', flexDirection:'column', gap: 4, background:'var(--surface-2)', border:'1px solid var(--line)', borderRadius:'var(--r-2)', boxShadow:'var(--shadow-1)', padding: 4}}>
      <Btn icon="plus" variant="ghost" size="sm" className="icon" onClick={() => proto('Zoom in', { tag:'simulated' })}/>
      <Btn icon="minus" variant="ghost" size="sm" className="icon" onClick={() => proto('Zoom out', { tag:'simulated' })}/>
      <Btn icon="target" variant="ghost" size="sm" className="icon" onClick={() => proto('Centered on your node', { tag:'simulated' })}/>
    </div>
  );

  const AntiDupBanner = () => (
    <div style={{position:'absolute', top: 70, left: '50%', transform:'translateX(-50%)', background:'var(--surface-2)', border:'1px solid rgba(176,58,46,0.3)', borderRadius:'var(--r-3)', padding: '10px 16px', boxShadow:'var(--shadow-2)'}}>
      <div className="row items-center gap-3">
        <Icon name="alert" size={16} color="var(--e-antidup)"/>
        <span style={{fontSize:'var(--t-sm)', color:'var(--e-antidup)', fontWeight: 500}}>3 anti-duplication clusters detected</span>
        <span style={{fontSize:'var(--t-xs)', color:'var(--ink-3)'}}>· membrane protocols ×3 · pilot data ×2 · safety curriculum ×2</span>
        <Btn size="xs" variant="ghost" onClick={() => proto('Anti-dup cluster review — full build', { tag:'placeholder' })}>Review</Btn>
      </div>
    </div>
  );

  // ============ Need-Offer view ============
  const NeedOfferView = ({onMatch}) => {
    const { needs, offers, flows } = L.NEED_OFFER;
    const W = 1200, H = 620;
    const colW = 280;
    const lx = 60, rx = W - colW - 60;
    const yStep = 70, yTop = 100;

    const needPos = needs.reduce((m, n, i) => { m[n.id] = { x: lx + colW, y: yTop + i*yStep }; return m; }, {});
    const offerPos = offers.reduce((m, o, i) => { m[o.id] = { x: rx, y: yTop + i*yStep - 30 }; return m; }, {});

    return (
      <div className="canvas-bg" style={{position:'relative', width:'100%', height: '100%', borderRadius:'var(--r-4)', overflow:'hidden', border:'1px solid var(--line)'}}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%">
          {/* column headers */}
          <text x={lx + colW - 10} y={50} textAnchor="end" fontFamily="Instrument Serif, serif" fontSize="22" fill="var(--c-need)">Needs</text>
          <text x={rx + 10} y={50} textAnchor="start" fontFamily="Instrument Serif, serif" fontSize="22" fill="var(--c-offer)">Offers</text>
          <text x={lx + colW - 10} y={68} textAnchor="end" fontFamily="Inter Tight, sans-serif" fontSize="11" fill="var(--ink-3)" letterSpacing="0.08em">WHO IS LOOKING</text>
          <text x={rx + 10} y={68} textAnchor="start" fontFamily="Inter Tight, sans-serif" fontSize="11" fill="var(--ink-3)" letterSpacing="0.08em">WHO CAN PROVIDE</text>

          {/* flow ribbons */}
          {flows.map((f, i) => {
            const a = needPos[f.from], b = offerPos[f.to];
            if (!a || !b) return null;
            const w = 6 + f.strength * 18;
            const c1x = a.x + 200, c1y = a.y;
            const c2x = b.x - 200, c2y = b.y;
            const isMatch = f.matchId === 'm_01';
            return (
              <g key={i} onClick={() => isMatch && onMatch && onMatch()} style={{cursor: isMatch?'pointer':'default'}}>
                <path d={`M ${a.x} ${a.y} C ${c1x} ${c1y}, ${c2x} ${c2y}, ${b.x} ${b.y}`}
                      stroke={isMatch ? 'var(--accent)' : 'var(--c-offer)'}
                      strokeOpacity={isMatch?0.55:0.3}
                      strokeWidth={w} fill="none" strokeLinecap="round"/>
                {isMatch && (
                  <text x={(a.x + b.x)/2} y={(a.y+b.y)/2 - 4} textAnchor="middle"
                        fontFamily="Inter Tight, sans-serif" fontSize="11" fontWeight="600" fill="var(--accent)">
                    {f.label} · {Math.round(f.strength*100)}%
                  </text>
                )}
              </g>
            );
          })}

          {/* needs (left column) */}
          {needs.map((n, i) => {
            const y = yTop + i * yStep;
            return (
              <g key={n.id}>
                <rect x={lx} y={y - 22} width={colW} height="44" rx="6"
                      fill="var(--surface-2)" stroke="var(--c-need)" strokeWidth="1.2"/>
                <text x={lx + 14} y={y - 4} fontFamily="Inter Tight, sans-serif" fontSize="13" fontWeight="600" fill="var(--ink)">{n.label}</text>
                <text x={lx + 14} y={y + 12} fontFamily="Inter Tight, sans-serif" fontSize="11" fill="var(--ink-3)">{n.who}</text>
                <circle cx={lx + colW} cy={y} r="6" fill="var(--c-need)"/>
              </g>
            );
          })}
          {/* offers (right column) */}
          {offers.map((o, i) => {
            const y = yTop + i * yStep - 30;
            return (
              <g key={o.id}>
                <rect x={rx} y={y - 22} width={colW} height="44" rx="6"
                      fill="var(--surface-2)" stroke="var(--c-offer)" strokeWidth="1.2"/>
                <text x={rx + 14} y={y - 4} fontFamily="Inter Tight, sans-serif" fontSize="13" fontWeight="600" fill="var(--ink)">{o.label}</text>
                <text x={rx + 14} y={y + 12} fontFamily="Inter Tight, sans-serif" fontSize="11" fill="var(--ink-3)">{o.who}</text>
                <circle cx={rx} cy={y} r="6" fill="var(--c-offer)"/>
              </g>
            );
          })}
        </svg>
      </div>
    );
  };

  // ============ Detail drawer (right) ============
  const DetailDrawer = ({view, setView, selectedNode, setSelectedNode, selectedEdge, mode}) => {
    const node = D.byId(selectedNode);
    const kind = D.kindOf(selectedNode || 'p_sara');
    const match = selectedEdge && selectedEdge.matchId ? D.MATCHES.find(m => m.id === selectedEdge.matchId) : null;

    return (
      <div className="drawer" style={{height: '100%'}}>
        <div className="drawer-head col gap-3">
          <div className="row items-center gap-2">
            <button onClick={() => setView('node')} className={'btn ' + (view==='node'?'primary':'ghost') + ' xs'}>Node</button>
            <button onClick={() => setView('edge')} className={'btn ' + (view==='edge'?'primary':'ghost') + ' xs'}>Edge</button>
            <button onClick={() => setView('why')} className={'btn ' + (view==='why'?'primary':'ghost') + ' xs'}>Why?</button>
            <div className="flex-1"/>
            <Btn icon="x" variant="ghost" className="icon sm" onClick={() => proto('Drawer closed (prototype keeps it open for review)', { tag:'simulated' })}/>
          </div>
        </div>

        <div className="drawer-body">
          {view === 'node' && node && <NodeDetail node={node} kind={kind} setView={setView}/>}
          {view === 'edge' && selectedEdge && <EdgeDetail edge={selectedEdge} match={match} setView={setView}/>}
          {view === 'why' && (match || selectedEdge) && <WhyConnected edge={selectedEdge} match={match}/>}
          {view === 'why' && !selectedEdge && !match && (
            <WhyConnected edge={{type:'Complementarity', s:'p_sara', t:'pj_hydronl', strength:0.88}} match={D.MATCHES[0]}/>
          )}
        </div>

        <div className="drawer-foot row gap-2">
          <Btn icon="send" variant="accent" size="sm" style={{flex:1, justifyContent:'center'}} onClick={() => proto('Signal sent', { tag:'simulated' })}>Send signal</Btn>
          <Btn icon="bookmark" variant="ghost" size="sm" className="icon" onClick={() => proto('Saved to shortlist', { tag:'simulated' })}/>
          <Btn icon="arrowUpRight" variant="ghost" size="sm" className="icon" onClick={() => location.hash = 'match'}/>
        </div>
      </div>
    );
  };

  const NodeDetail = ({node, kind, setView}) => (
    <div className="col gap-4 fade-up">
      <div className="row items-center gap-3">
        <Avatar initials={node.initials} kind={kind} size="lg"/>
        <div className="col">
          <div className="eyebrow" style={{fontSize: 10}}>{kind === 'person' ? 'Person' : kind === 'project' ? 'Project' : 'Organization'}</div>
          <div style={{fontFamily:'var(--font-display)', fontSize: 22, lineHeight: 1.1, letterSpacing:'-0.015em'}}>{node.name}</div>
          <div style={{fontSize:'var(--t-sm)', color:'var(--ink-3)', marginTop: 2}}>{node.role || node.type} · {node.org || node.region}</div>
        </div>
      </div>

      {node.bio && <p style={{fontSize:'var(--t-sm)', color:'var(--ink-2)', lineHeight: 1.55, margin:0}}>{node.bio}</p>}

      {/* fingerprint */}
      {node.fingerprint && (
        <div className="col gap-2">
          <div className="label-hr">Expertise fingerprint</div>
          <Fingerprint data={node.fingerprint} compact/>
        </div>
      )}

      {/* project context */}
      {node.trl != null && (
        <div className="col gap-2">
          <div className="label-hr">Project context</div>
          <div className="row gap-2 flex-wrap">
            <Chip variant="outline">Stage: {node.stage}</Chip>
            <Chip variant="outline">TRL {node.trl}</Chip>
            <Chip variant="outline">{node.scale}</Chip>
            <Chip variant="outline">{node.region}</Chip>
          </div>
        </div>
      )}

      {/* needs/offers */}
      {(node.needs || node.offers) && (
        <div className="grid cols-2" style={{gap: 12}}>
          {node.needs && (
            <div className="col gap-2">
              <div className="label-hr">Needs</div>
              <div className="col gap-1">{node.needs.map((n,i) => <Chip key={i} variant="warm" size="lg">{n}</Chip>)}</div>
            </div>
          )}
          {node.offers && (
            <div className="col gap-2">
              <div className="label-hr">Offers</div>
              <div className="col gap-1">{node.offers.map((o,i) => <Chip key={i} variant="moss" size="lg">{o}</Chip>)}</div>
            </div>
          )}
        </div>
      )}

      {/* bottlenecks / uncertainties */}
      {(node.bottlenecks || node.uncertainties) && (
        <div className="col gap-2">
          <div className="label-hr">Blockers & unknowns</div>
          {node.bottlenecks && node.bottlenecks.map((b,i) => (
            <div key={i} className="row items-center justify-between" style={{padding: '8px 10px', background:'rgba(176,58,46,0.06)', borderRadius:'var(--r-2)'}}>
              <div className="row items-center gap-2"><Icon name="alert" size={13} color="var(--e-antidup)"/><span style={{fontSize:'var(--t-sm)'}}>{b.label}</span></div>
              <span style={{fontSize:'var(--t-xs)', color:'var(--e-antidup)', fontWeight:600}}>severity {b.severity}/5</span>
            </div>
          ))}
          {node.uncertainties && node.uncertainties.map((u,i) => (
            <div key={i} className="row items-center justify-between" style={{padding: '8px 10px', background:'rgba(138,74,140,0.06)', borderRadius:'var(--r-2)'}}>
              <div className="row items-center gap-2"><Icon name="compass" size={13} color="var(--e-uncertain)"/><span style={{fontSize:'var(--t-sm)'}}>{u.label}</span></div>
              <span style={{fontSize:'var(--t-xs)', color:'var(--e-uncertain)'}}>{u.horizon}</span>
            </div>
          ))}
        </div>
      )}

      {/* top connections */}
      <div className="col gap-2">
        <div className="label-hr">Top connections</div>
        <div className="col gap-1">
          {[
            {n: D.PEOPLE[1], why:'Similarity · 92%', rel:'Similarity'},
            {n: D.PROJECTS[0], why:'Complementarity · 88%', rel:'Complementarity'},
            {n: D.PEOPLE[3], why:'Shared uncertainty · 71%', rel:'Shared uncertainty'},
          ].map((c,i) => (
            <div key={i} className="row items-center gap-3" style={{padding:'8px 6px', borderRadius:'var(--r-2)'}}>
              <Avatar initials={c.n.initials} kind={c.n.id?.startsWith('pj_')?'project':'person'} size="sm"/>
              <div className="col flex-1">
                <div style={{fontSize:'var(--t-sm)', fontWeight: 500}}>{c.n.name}</div>
                <RelChip type={c.rel} size="xs"/>
              </div>
              <Btn icon="arrowRight" variant="ghost" size="xs" className="icon" onClick={() => proto('Jump to ' + (c.label || 'node'), { tag:'simulated' })}/>
            </div>
          ))}
        </div>
      </div>

      {/* actions */}
      <div className="col gap-2">
        <Btn variant="primary" icon="user" onClick={() => location.hash = 'match'} style={{justifyContent:'center'}}>Open full profile</Btn>
        <div className="row gap-2">
          <Btn variant="ghost" size="sm" icon="layers" style={{flex:1, justifyContent:'center'}} onClick={() => proto('Compare profiles — full build', { tag:'placeholder' })}>Compare</Btn>
          <Btn variant="ghost" size="sm" icon="target" style={{flex:1, justifyContent:'center'}} onClick={() => proto('Re-centered graph on this node', { tag:'simulated' })}>Focus here</Btn>
        </div>
      </div>
    </div>
  );

  const EdgeDetail = ({edge, match, setView}) => {
    if (!edge) return <div className="empty">No edge selected</div>;
    const a = D.byId(edge.s), b = D.byId(edge.t);
    return (
      <div className="col gap-4 fade-up">
        <RelChip type={edge.type}/>
        <div className="row items-center gap-2">
          <Avatar initials={a?.initials || '??'} kind={D.kindOf(edge.s)} size="sm"/>
          <Icon name="git" size={14} color="var(--ink-3)"/>
          <Avatar initials={b?.initials || '??'} kind={D.kindOf(edge.t)} size="sm"/>
        </div>
        <div className="col">
          <div style={{fontFamily:'var(--font-display)', fontSize: 22, letterSpacing:'-0.015em', lineHeight: 1.2}}>
            {a?.name} <span style={{color:'var(--ink-3)'}}>×</span> {b?.name}
          </div>
        </div>

        <div className="row gap-2 flex-wrap">
          <Card variant="tight" style={{padding: 12, flex: 1}}>
            <div className="kpi">
              <div className="l">Strength</div>
              <div className="v">{Math.round((edge.strength || 0)*100)}<span style={{fontSize:14}}>%</span></div>
            </div>
          </Card>
          <Card variant="tight" style={{padding: 12, flex: 1}}>
            <div className="kpi">
              <div className="l">Confidence</div>
              <div className="v">{Math.round((match?.confidence || 0.85)*100)}<span style={{fontSize:14}}>%</span></div>
            </div>
          </Card>
          <Card variant="tight" style={{padding: 12, flex: 1}}>
            <div className="kpi">
              <div className="l">Source</div>
              <div className="v" style={{fontSize: 13, lineHeight:1.2}}>{match?.curated ? 'Curated' : 'System'}</div>
            </div>
          </Card>
        </div>

        {match && (
          <div className="col gap-2">
            <div className="label-hr">Why connected — short</div>
            <div className="card tight" style={{background:'var(--surface-2)'}}>
              <div style={{fontSize:'var(--t-sm)', color:'var(--ink-2)', lineHeight:1.55}}>{match.summary}</div>
            </div>
            <Btn variant="ghost" size="sm" icon="sparkles" onClick={() => setView('why')}>See full explanation</Btn>
          </div>
        )}

        <div className="col gap-2">
          <Btn variant="primary" icon="arrowUpRight" onClick={() => location.hash = 'match'} style={{justifyContent:'center'}}>Open match detail</Btn>
        </div>
      </div>
    );
  };

  const WhyConnected = ({edge, match}) => {
    if (!match) return <div className="empty">Select an edge to see why it exists</div>;
    return (
      <div className="col gap-4 fade-up">
        <div className="col gap-1">
          <RelChip type={match.type}/>
          <div style={{fontFamily:'var(--font-display)', fontSize: 22, letterSpacing:'-0.015em', lineHeight: 1.2, marginTop: 6}}>Why connected?</div>
          <div style={{fontSize:'var(--t-sm)', color:'var(--ink-2)', lineHeight: 1.55, marginTop: 4}}>{match.summary}</div>
        </div>

        <div className="col gap-2">
          <div className="label-hr">Signals · contribution to score</div>
          <div className="col gap-3">
            {match.signals.map((s, i) => (
              <div key={i} className="col gap-1">
                <div className="row justify-between items-center">
                  <span style={{fontSize:'var(--t-sm)', fontWeight: 600}}>{s.name}</span>
                  <span className="tnum" style={{fontSize:'var(--t-sm)', color:'var(--accent)', fontWeight: 600}}>{s.score}%</span>
                </div>
                <div className="bar"><div className="fill" style={{width: s.score + '%'}}/></div>
                <div style={{fontSize:'var(--t-xs)', color:'var(--ink-3)', lineHeight: 1.5}}>{s.expl}</div>
                <div style={{fontSize: 10, color:'var(--muted)', textTransform:'uppercase', letterSpacing:'0.08em'}}>source · {s.source}</div>
              </div>
            ))}
          </div>
        </div>

        <Btn variant="primary" icon="arrowUpRight" onClick={() => location.hash = 'match'} style={{justifyContent:'center'}}>Open full match detail</Btn>
      </div>
    );
  };

  Object.assign(window, { NetworkScreen });
})();
