// portgrid.jsx — animated port-grid hero

const PORT_DATA = [
  // gridX, gridY (0-9), name, port
  { x:1, y:1, n:'jobs-board',   p:7400, group:'jobs' },
  { x:2, y:1, n:'jobs-server',  p:7401, group:'jobs' },
  { x:3, y:1, n:'jobs-worker',  p:7402, group:'jobs' },
  { x:5, y:1, n:'admin',        p:8032, group:'admin', running:true },
  { x:6, y:1, n:'admin-api',    p:8033, group:'admin', running:true },
  { x:1, y:3, n:'postiz',       p:3002 },
  { x:3, y:3, n:'skylar',       p:5454 },
  { x:5, y:3, n:'pgsql',        p:5432, running:true },
  { x:7, y:3, n:'redis',        p:6379, running:true },
  { x:1, y:5, n:'site',         p:6001 },
  { x:3, y:5, n:'docs',         p:6000 },
  { x:5, y:5, n:'studio',       p:9000 },
  { x:7, y:5, n:'mailpit',      p:1025 },
  { x:2, y:7, n:'vite',         p:5173 },
  { x:4, y:7, n:'next',         p:3000 },
  { x:6, y:7, n:'storybook',    p:6006 },
  { x:8, y:7, n:'playwright',   p:9323 },
];

function PortGrid(){
  const [tick, setTick] = React.useState(0);
  const [hover, setHover] = React.useState(null);
  const [running, setRunning] = React.useState(() =>
    new Set(PORT_DATA.filter(p=>p.running).map(p=>p.p))
  );

  // Pulse cadence — flip a random service every ~1.6s
  React.useEffect(()=>{
    const id = setInterval(()=>{
      setRunning(prev => {
        const next = new Set(prev);
        const candidates = PORT_DATA;
        const target = candidates[Math.floor(Math.random()*candidates.length)];
        if(next.has(target.p)) next.delete(target.p);
        else next.add(target.p);
        return next;
      });
      setTick(t=>t+1);
    }, 1600);
    return ()=>clearInterval(id);
  },[]);

  const cell = 50;       // cell size in svg units
  const offset = 40;
  const W = 500, H = 500;

  return (
    <div className="portgrid-wrap">
      <span className="portgrid-corner tl">● LIVE · pa.local/grid</span>
      <span className="portgrid-corner tr mono">{running.size} active / {PORT_DATA.length}</span>
      <span className="portgrid-corner bl">tcp/127.0.0.1</span>
      <span className="portgrid-corner br">scan {String(tick).padStart(4,'0')}</span>

      <div className="scanline" />

      <svg className="portgrid-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
        <defs>
          <radialGradient id="cellGlow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.55"/>
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
          </radialGradient>
          <linearGradient id="connLine" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%"   stopColor="var(--accent)" stopOpacity="0"/>
            <stop offset="50%"  stopColor="var(--accent)" stopOpacity=".7"/>
            <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
          </linearGradient>
        </defs>

        {/* Connections between running services in same group */}
        {PORT_DATA.filter(p=>running.has(p.p) && p.group).map((p,i,arr)=>{
          const partners = arr.filter(o=>o!==p && o.group===p.group);
          return partners.map((o,j)=>{
            const x1 = offset + p.x*cell, y1 = offset + p.y*cell;
            const x2 = offset + o.x*cell, y2 = offset + o.y*cell;
            return <line key={`${p.p}-${o.p}-${j}`} x1={x1} y1={y1} x2={x2} y2={y2}
              stroke="url(#connLine)" strokeWidth="1.2" />
          });
        })}

        {PORT_DATA.map((p)=>{
          const cx = offset + p.x*cell;
          const cy = offset + p.y*cell;
          const isRun = running.has(p.p);
          const isHover = hover === p.p;
          return (
            <g key={p.p} onMouseEnter={()=>setHover(p.p)} onMouseLeave={()=>setHover(null)} style={{cursor:'default'}}>
              {/* glow */}
              {isRun && <circle cx={cx} cy={cy} r="22" fill="url(#cellGlow)"/>}
              {/* outer pulse */}
              {isRun && <circle className="port-pulse" cx={cx} cy={cy} r="3" fill="none" stroke="var(--accent)" strokeWidth="1.2" style={{animationDelay:`${(p.x+p.y)*0.18}s`}}/>}
              {/* hex/square cell */}
              <rect
                x={cx-9} y={cy-9} width="18" height="18" rx="3"
                fill={isRun ? 'var(--accent)' : 'var(--bg-2)'}
                stroke={isRun ? 'var(--accent)' : (isHover?'var(--ink-2)':'var(--line-2)')}
                strokeWidth="1"
                className="port-cell"
              />
              {/* port number */}
              <text x={cx} y={cy+24} textAnchor="middle" className="port-label">
                {p.p}
              </text>
              {/* hover tooltip */}
              {isHover && (
                <g transform={`translate(${cx},${cy-14})`}>
                  <rect x="-44" y="-22" width="88" height="20" rx="4" fill="var(--bg)" stroke="var(--line-2)"/>
                  <text x="0" y="-8" textAnchor="middle" fontFamily="var(--mono)" fontSize="9.5" fill="var(--ink)">{p.n}</text>
                </g>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

Object.assign(window, { PortGrid });
