// ViG Command Center — Alliance Diplomacy Graph (relationship network)
const { useState: useStateDP, useEffect: useEffectDP, useMemo: useMemoDP } = React;

const DP_RELS = [
  ['ally', 'Ally', '#34d399'],
  ['nap', 'Non-aggression', '#22d3ee'],
  ['neutral', 'Neutral', '#64748b'],
  ['rival', 'Rival', '#fbbf24'],
  ['enemy', 'Enemy', '#fb7185'],
  ['war', 'At war', '#ef4444'],
];
const DP_REL_MAP = Object.fromEntries(DP_RELS.map(r => [r[0], { label: r[1], color: r[2] }]));
const DP_NEXT = { neutral: 'ally', ally: 'nap', nap: 'rival', rival: 'enemy', enemy: 'war', war: 'neutral' };

function dpDefault() {
  const seed = [];
  try { (window.ALLIANCE?.alliances || []).forEach(a => seed.push({ id: a.id, color: a.accent, power: a.power, own: a.id === 'VIG' })); } catch (e) {}
  if (!seed.length) { ['VIG', 'RSP', 'NEF'].forEach((id, i) => seed.push({ id, color: ['#FF6B00', '#3B82F6', '#A855F7'][i], own: id === 'VIG' })); }
  return { nodes: seed, rels: { 'RSP|NEF': 'ally', 'VIG|RSP': 'rival', 'VIG|NEF': 'enemy' } };
}

function DiplomacyPage() {
  const [state, setState] = useStateDP(() => LS.get('vig2_diplomacy', null) || dpDefault());
  const [sel, setSel] = useStateDP(null);
  const [adding, setAdding] = useStateDP('');
  useEffectDP(() => { LS.set('vig2_diplomacy', state); }, [state]);

  const nodes = state.nodes;
  const key = (a, b) => [a, b].sort().join('|');
  const relOf = (a, b) => state.rels[key(a, b)] || 'neutral';

  const setRel = (a, b, rel) => setState(s => ({ ...s, rels: { ...s.rels, [key(a, b)]: rel } }));
  const cycleRel = (a, b) => setRel(a, b, DP_NEXT[relOf(a, b)] || 'ally');
  const addNode = () => {
    const id = adding.trim().toUpperCase().slice(0, 4);
    if (!id || nodes.some(n => n.id === id)) { setAdding(''); return; }
    const palette = ['#f97316', '#06b6d4', '#a855f7', '#ec4899', '#84cc16', '#eab308', '#14b8a6'];
    setState(s => ({ ...s, nodes: [...s.nodes, { id, color: palette[s.nodes.length % palette.length] }] }));
    setAdding('');
  };
  const removeNode = (id) => setState(s => {
    const rels = { ...s.rels }; Object.keys(rels).forEach(k => { if (k.split('|').includes(id)) delete rels[k]; });
    return { nodes: s.nodes.filter(n => n.id !== id), rels };
  });

  // circle layout
  const W = 560, H = 420, cx = W / 2, cy = H / 2, R = Math.min(W, H) / 2 - 70;
  const pos = useMemoDP(() => {
    const m = {}; const n = nodes.length;
    nodes.forEach((nd, i) => { const ang = -Math.PI / 2 + (i / n) * Math.PI * 2; m[nd.id] = { x: cx + R * Math.cos(ang), y: cy + R * Math.sin(ang) }; });
    return m;
  }, [nodes]);

  const edges = [];
  for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) {
    const a = nodes[i].id, b = nodes[j].id, rel = relOf(a, b);
    edges.push({ a, b, rel, color: DP_REL_MAP[rel].color });
  }

  // counts from VIG's perspective
  const vig = nodes.find(n => n.own) || nodes[0];
  const summary = vig ? DP_RELS.map(([id, label, color]) => ({ label, color, n: nodes.filter(o => o.id !== vig.id && relOf(vig.id, o.id) === id).length })).filter(x => x.n > 0) : [];

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        {/* graph */}
        <Card className="overflow-hidden lg:col-span-2">
          <div className="flex items-center gap-2 border-b border-zinc-100 px-4 py-3 dark:border-zinc-800">
            <Icon name="link" size={16} className="text-brand" />
            <span className="text-[13px] font-bold uppercase tracking-wide text-zinc-900 dark:text-white">Diplomacy network</span>
            <span className="text-[11px] text-zinc-400">tap two alliances to set their relationship</span>
          </div>
          <div className="cyber-scan p-2">
            <svg viewBox={`0 0 ${W} ${H}`} className="w-full" style={{ maxHeight: 440 }}>
              {/* edges */}
              {edges.map((e, i) => {
                const p1 = pos[e.a], p2 = pos[e.b];
                const active = sel && (sel === e.a || sel === e.b);
                const dim = sel && !active;
                return (
                  <g key={i} opacity={dim ? 0.12 : 1} style={{ cursor: 'pointer' }} onClick={() => cycleRel(e.a, e.b)}>
                    <line x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke={e.color} strokeWidth={e.rel === 'war' ? 3 : e.rel === 'ally' ? 2.5 : 1.5} strokeDasharray={e.rel === 'neutral' || e.rel === 'nap' ? '4 4' : 'none'} opacity={e.rel === 'neutral' ? 0.4 : 0.85}>
                      {e.rel === 'war' && <animate attributeName="opacity" values="0.4;1;0.4" dur="1.4s" repeatCount="indefinite" />}
                    </line>
                  </g>
                );
              })}
              {/* nodes */}
              {nodes.map(nd => {
                const p = pos[nd.id]; const isSel = sel === nd.id;
                return (
                  <g key={nd.id} style={{ cursor: 'pointer' }} onClick={() => setSel(isSel ? null : (sel && sel !== nd.id ? (cycleRel(sel, nd.id), null) : nd.id))}>
                    <circle cx={p.x} cy={p.y} r={isSel ? 30 : 26} fill={nd.color} opacity={isSel ? 1 : 0.92} stroke={isSel ? '#fff' : nd.own ? '#fff' : 'transparent'} strokeWidth={isSel ? 3 : nd.own ? 2 : 0} />
                    {nd.own && <circle cx={p.x} cy={p.y} r={33} fill="none" stroke={nd.color} strokeWidth="1.5" opacity="0.5" />}
                    <text x={p.x} y={p.y} textAnchor="middle" dominantBaseline="central" fontSize="13" fontWeight="800" fill="#fff">{nd.id}</text>
                  </g>
                );
              })}
            </svg>
            {sel && <div className="px-3 pb-2 text-center text-[12px] text-brand">Tap another alliance to set its relationship with <b>{sel}</b>, or tap {sel} again to cancel.</div>}
          </div>
        </Card>

        {/* side panel */}
        <div className="space-y-4">
          <Card className="p-4">
            <div className="mb-2 text-[12px] font-bold uppercase tracking-wide text-zinc-400">{vig ? vig.id : 'Your'} standing</div>
            {summary.length ? <div className="space-y-1.5">{summary.map(s => (
              <div key={s.label} className="flex items-center gap-2"><span className="h-2.5 w-2.5 rounded-full" style={{ background: s.color }}></span><span className="flex-1 text-[12.5px] text-zinc-600 dark:text-zinc-300">{s.label}</span><span className="text-[13px] font-bold tabular-nums" style={{ color: s.color }}>{s.n}</span></div>
            ))}</div> : <div className="text-[12px] text-zinc-400">Set relationships on the graph.</div>}
          </Card>
          <Card className="p-4">
            <div className="mb-2 text-[12px] font-bold uppercase tracking-wide text-zinc-400">Legend</div>
            <div className="grid grid-cols-2 gap-1.5">
              {DP_RELS.map(([id, label, color]) => <div key={id} className="flex items-center gap-1.5"><span className="h-2 w-4 rounded-full" style={{ background: color }}></span><span className="text-[11.5px] text-zinc-500 dark:text-zinc-400">{label}</span></div>)}
            </div>
          </Card>
          <Card className="p-4">
            <div className="mb-2 text-[12px] font-bold uppercase tracking-wide text-zinc-400">Alliances</div>
            <div className="space-y-1.5">
              {nodes.map(nd => (
                <div key={nd.id} className="flex items-center gap-2">
                  <span className="flex h-6 w-6 items-center justify-center rounded-md text-[11px] font-bold text-white" style={{ background: nd.color }}>{nd.id}</span>
                  <span className="flex-1 text-[12.5px] text-zinc-600 dark:text-zinc-300">{nd.own ? 'Your alliance' : nd.id}</span>
                  {!nd.own && <button onClick={() => removeNode(nd.id)} className="rounded p-1 text-zinc-400 hover:text-rose-500" title="Remove"><Icon name="x" size={13} /></button>}
                </div>
              ))}
            </div>
            <div className="mt-2.5 flex gap-1.5">
              <input value={adding} onChange={e => setAdding(e.target.value)} onKeyDown={e => e.key === 'Enter' && addNode()} placeholder="Add alliance tag" maxLength={4} className="h-8 flex-1 rounded-lg border border-zinc-200 bg-white px-2.5 text-[12px] uppercase outline-none focus:border-brand dark:border-zinc-700 dark:bg-zinc-900" />
              <button onClick={addNode} className="rounded-lg bg-brand px-2.5 text-[12px] font-semibold text-white">Add</button>
            </div>
          </Card>
        </div>
      </div>
      <p className="px-1 text-[11.5px] text-zinc-400">Map your server's politics: add every alliance, then tap any two to cycle their relationship (neutral → ally → NAP → rival → enemy → war). Your alliance is ringed. "At war" edges pulse. Saved on this device — share a screenshot in your R4/R5 channel.</p>
    </div>
  );
}
window.DiplomacyPage = DiplomacyPage;
