// StationGraphSection — the draft station graph rendered INSIDE the assembly
// canvas world layer (TimelineSection pattern: position:absolute children, not
// draggable). Node cards reuse the LineCanvas design language; geometry comes
// from window.layoutGraph offset by `origin`, edges from window.edgePath.
// Pure render — the create page owns the graph, spinner flags and callbacks.
//
// Props: { graph, issuesByNode, selectedId, proposalRunning, revising, error,
//          onSelectStation(id), onRetry(), onTargetChat(step), origin {x,y} }
//
// onTargetChat('line') is the SECTION-level chat affordance (14c — chat about any
// step): a "chat about the line" pill in the label chrome, guarded like
// BriefSection (shown only when a handler is supplied). NODES keep their own
// click (onSelectStation → open the station modal); the pill is the ONLY chat
// producer for the 'line' target, mirroring BriefSection's card-click for 'brief'.

const SGS_NODE_W = 208;
const SGS_NODE_H = 76;

const StationGraphSection = ({ graph, issuesByNode = {}, selectedId = null, proposalRunning = false, revising = false, stale = false, error = null, onSelectStation, onRetry, onTargetChat, origin }) => {
  const nodes = (graph && Array.isArray(graph.nodes)) ? graph.nodes : [];
  const edges = (graph && Array.isArray(graph.edges)) ? graph.edges : [];
  const layout = window.layoutGraph(graph || { nodes: [], edges: [] });
  const targetable = typeof onTargetChat === 'function';

  const label = (
    <div
      style={{ position: 'absolute', transform: `translate3d(${origin.x}px, ${origin.y - 36}px, 0)` }}
      className="px-3 py-1.5 text-[10px] uppercase font-bold tracking-widest text-neutral-500 select-none flex items-center gap-2 whitespace-nowrap"
    >
      Stations · the line that builds it
      <window.StaleBadge stale={stale} />
      {targetable && (
        <button
          type="button"
          onClick={(e) => { e.stopPropagation(); onTargetChat('line'); }}
          className="normal-case tracking-normal rounded-full bg-indigo-50 border border-indigo-200 px-2 py-0.5 text-[10px] font-bold text-indigo-700 hover:bg-indigo-100 cursor-pointer"
        >Chat about the line</button>
      )}
      {revising && (
        <span className="normal-case tracking-normal flex items-center gap-1.5 rounded-full bg-indigo-50 border border-indigo-200 px-2 py-0.5 text-[10px] font-bold text-indigo-700">
          <span className="relative flex w-1.5 h-1.5">
            <span className="absolute inline-flex h-full w-full rounded-full bg-indigo-500 opacity-75 animate-ping" />
            <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-indigo-500" />
          </span>
          Revising the line…
        </span>
      )}
    </div>
  );

  if (!nodes.length) {
    return (
      <>
        {label}
        <div style={{ position: 'absolute', transform: `translate3d(${origin.x}px, ${origin.y}px, 0)`, width: 420 }}>
          {error ? (
            <div className="rounded-2xl border-2 border-dashed border-red-300 bg-red-50/60 p-6">
              <div className="text-sm font-semibold text-red-800 mb-3">{error}</div>
              <button onClick={() => onRetry && onRetry()} className="px-3 py-1.5 rounded-lg text-xs font-bold bg-red-600 text-white hover:bg-red-700">Try again</button>
            </div>
          ) : proposalRunning ? (
            <div className="rounded-2xl border-2 border-dashed border-indigo-300 bg-indigo-50/40 p-6 flex items-center gap-3">
              <span className="relative flex w-2.5 h-2.5">
                <span className="absolute inline-flex h-full w-full rounded-full bg-indigo-500 opacity-75 animate-ping" />
                <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-indigo-500" />
              </span>
              <span className="text-sm font-semibold text-indigo-800">Proposing station line…</span>
            </div>
          ) : (
            <div className="rounded-2xl border-2 border-dashed border-neutral-300 p-6 text-sm text-neutral-400">The station line appears here once the plan is approved.</div>
          )}
        </div>
      </>
    );
  }

  return (
    <>
      {label}
      <svg
        width={layout.width} height={layout.height}
        style={{ position: 'absolute', left: origin.x, top: origin.y, overflow: 'visible', pointerEvents: 'none', zIndex: 2 }}
      >
        <defs>
          <marker id="sgs-arrow-flow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
            <path d="M 0 0 L 10 5 L 0 10 z" fill="#94a3b8" />
          </marker>
          <marker id="sgs-arrow-rework" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
            <path d="M 0 0 L 10 5 L 0 10 z" fill="#fb923c" />
          </marker>
        </defs>
        {edges.map((e, i) => {
          const a = layout.positions[e.from], b = layout.positions[e.to];
          if (!a || !b) return null;
          const rework = e.kind === 'rework';
          return (
            <path
              key={`${e.from}->${e.to}:${e.kind || 'flow'}:${i}`}
              d={window.edgePath(a, b, { w: SGS_NODE_W, h: SGS_NODE_H, kind: e.kind })}
              fill="none" stroke={rework ? '#fb923c' : '#94a3b8'} strokeWidth="2" strokeLinecap="round"
              strokeDasharray={rework ? '6 4' : undefined}
              markerEnd={rework ? 'url(#sgs-arrow-rework)' : 'url(#sgs-arrow-flow)'}
              opacity="0.85"
            />
          );
        })}
      </svg>
      {nodes.map((n) => {
        const p = layout.positions[n.id];
        if (!p) return null;
        const selected = n.id === selectedId;
        const count = issuesByNode[n.id] || 0;
        return (
          <div
            key={n.id}
            onClick={(e) => { e.stopPropagation(); onSelectStation && onSelectStation(n.id); }}
            className={`absolute rounded-xl border bg-white shadow-sm cursor-pointer transition-shadow hover:shadow-md ${selected ? 'border-indigo-300 ring-2 ring-indigo-500' : 'border-neutral-200'}`}
            style={{ left: origin.x + p.x, top: origin.y + p.y, width: SGS_NODE_W, zIndex: selected ? 20 : 10 }}
          >
            <div className="p-3">
              <div className="text-[13px] font-bold text-neutral-800 truncate">{n.title || n.id}</div>
              <div className="mt-1.5 flex items-center gap-1.5">
                <span className="text-[10px] font-semibold uppercase tracking-wide bg-neutral-100 text-neutral-500 rounded px-1.5 py-0.5 truncate max-w-[9rem]">{n.templateId || '—'}</span>
                {n.humanReview && <span title="Human review" className="text-[9px] font-bold text-amber-700 bg-amber-100 rounded px-1 py-0.5">HR</span>}
              </div>
            </div>
            {count > 0 && (
              <span className="absolute -top-2 -right-2 min-w-[18px] h-[18px] px-1 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center shadow">{count}</span>
            )}
          </div>
        );
      })}
    </>
  );
};

if (typeof window !== 'undefined') {
  window.StationGraphSection = StationGraphSection;
}
