// Endpoints table
const { useMemo: useTblMemo, useState: useTblState } = React;

function NodesTable({ nodes, onSelect, selectedId }) {
  const [sort, setSort] = useTblState({ key: 'hostname', dir: 1 });
  const [groupBy, setGroupBy] = useTblState('group');

  const sorted = useTblMemo(() => {
    const arr = [...nodes];
    arr.sort((a, b) => {
      const k = sort.key;
      const av = a[k], bv = b[k];
      if (typeof av === 'number') return (av - bv) * sort.dir;
      return String(av).localeCompare(String(bv)) * sort.dir;
    });
    return arr;
  }, [nodes, sort]);

  const groups = useTblMemo(() => {
    if (groupBy === 'none') return [{ label: null, items: sorted }];
    const map = {};
    for (const n of sorted) {
      const k = n[groupBy];
      if (!map[k]) map[k] = [];
      map[k].push(n);
    }
    return Object.entries(map).map(([label, items]) => ({ label, items }));
  }, [sorted, groupBy]);

  function toggleSort(key) {
    setSort(s => s.key === key ? { key, dir: -s.dir } : { key, dir: 1 });
  }
  const SortHdr = ({ k, children, className }) => (
    <th className={className} onClick={() => toggleSort(k)} style={{cursor:'pointer'}}>
      {children} {sort.key === k ? (sort.dir > 0 ? '↑' : '↓') : ''}
    </th>
  );

  return (
    <div>
      <div style={{display:'flex', alignItems:'center', gap: 12, padding: '8px 16px', borderBottom:'1px solid var(--border)', background: 'var(--bg-1)', fontSize: 11}}>
        <span style={{color:'var(--text-faint)', letterSpacing:'0.08em', textTransform:'uppercase'}}>Group by</span>
        <div className="pill-toggle">
          {['none','group','status','protocol'].map(g => (
            <button key={g} className={groupBy === g ? 'on' : ''} onClick={() => setGroupBy(g)}>{g}</button>
          ))}
        </div>
        <span style={{marginLeft:'auto', color:'var(--text-faint)'}}>{nodes.length} endpoints</span>
      </div>
      <table className="tbl">
        <thead>
          <tr>
            <th style={{width: 12}}></th>
            <SortHdr k="hostname">Endpoint</SortHdr>
            <SortHdr k="status">Status</SortHdr>
            <SortHdr k="group">Group</SortHdr>
            <th>Proto</th>
            <th>Path</th>
            <SortHdr k="httpCode" className="num">HTTP</SortHdr>
            <SortHdr k="latency" className="num">RT</SortHdr>
            <SortHdr k="netIn" className="num">Net In</SortHdr>
            <SortHdr k="netOut" className="num">Net Out</SortHdr>
            <SortHdr k="sslDaysLeft" className="num">TLS</SortHdr>
            <SortHdr k="uptime" className="num">Uptime</SortHdr>
          </tr>
        </thead>
        <tbody>
          {groups.map(g => (
            <React.Fragment key={g.label || 'ungrouped'}>
              {g.label && (
                <tr style={{background:'var(--surface-2)'}}>
                  <td colSpan="12" style={{fontSize:10, letterSpacing:'0.1em', color:'var(--text-faint)', textTransform:'uppercase', padding:'5px 12px', borderBottom:'1px solid var(--border-2)'}}>
                    {groupBy} · {g.label} · {g.items.length}
                  </td>
                </tr>
              )}
              {g.items.map(n => (
                <tr key={n.id}
                    className={selectedId === n.id ? 'selected' : ''}
                    onClick={() => onSelect(n)}>
                  <td><span className={`dot ${n.status}`}/></td>
                  <td style={{fontWeight:500}}>{n.hostname}</td>
                  <td><span className={`chip ${n.status}`}>{n.status === 'ok' ? 'up' : n.status === 'off' ? 'offline' : n.status === 'maint' ? 'maint' : n.status === 'warn' ? 'warn' : 'down'}</span></td>
                  <td className="mute">{n.group}</td>
                  <td className="mute">{n.protocol}:{n.port}</td>
                  <td className="mute" style={{maxWidth: 180, overflow:'hidden', textOverflow:'ellipsis'}}>{n.path}</td>
                  <td className="num" style={{color: n.httpCode === 0 ? 'var(--text-mute)' : n.httpCode >= 500 ? 'var(--crit)' : n.httpCode >= 400 ? 'var(--warn)' : 'var(--ok)'}}>
                    {n.httpCode === 0 ? '—' : n.httpCode}
                  </td>
                  <td className="num" style={{color: n.status === 'off' ? 'var(--text-mute)' : n.latency > 800 ? 'var(--crit)' : n.latency > 300 ? 'var(--warn)' : 'var(--text)'}}>
                    {n.status === 'off' ? '—' : `${n.latency.toFixed(0)}ms`}
                  </td>
                  <td className="num mute">{n.status === 'off' ? '—' : `${n.netIn.toFixed(0)}`}</td>
                  <td className="num mute">{n.status === 'off' ? '—' : `${n.netOut.toFixed(0)}`}</td>
                  <td className="num" style={{color: n.sslDaysLeft < 14 ? 'var(--crit)' : n.sslDaysLeft < 30 ? 'var(--warn)' : 'var(--text-dim)'}}>
                    {n.sslDaysLeft}d
                  </td>
                  <td className="num mute">{n.status === 'off' ? '—' : window.fmtUptime(n.uptime)}</td>
                </tr>
              ))}
            </React.Fragment>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { NodesTable });
