"use client";

import { useLayoutEffect, useRef, useState } from "react";
import "./power-grid.css";

const sources = [
  { col: 0, name: "Banks", icon: "bank" },
  { col: 0, name: "Brokers", icon: "broker" },
  { col: 1, name: "Custodians", icon: "custody" },
  { col: 1, name: "Exchanges", icon: "exchange" },
  { col: 1, name: "Fund admins", icon: "fund" },
  { col: 2, name: "Market data", icon: "market" },
  { col: 2, name: "Reports", icon: "report" },
] as const;

type Line = { id: string; d: string; delay: string };

/* Line icons at the same weight as the platform-module and security sets, so
   the diagram reads as one system rather than a wall of third-party marks. */
function SourceIcon({ icon }: { icon: (typeof sources)[number]["icon"] }) {
  const common = {
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 1.6,
    strokeLinecap: "round",
    strokeLinejoin: "round",
  } as const;

  switch (icon) {
    case "bank":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <path d="M3.6 8.6L12 4.2l8.4 4.4" {...common} />
          <path d="M5.8 10.2v7.4M9.9 10.2v7.4M14.1 10.2v7.4M18.2 10.2v7.4" {...common} />
          <path d="M3.6 19.8h16.8" {...common} />
        </svg>
      );
    case "broker":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <rect x="4.4" y="8.6" width="4.4" height="7.2" rx="1.2" {...common} />
          <path d="M6.6 5.4v3.2M6.6 15.8v3" {...common} />
          <rect x="15.2" y="6.4" width="4.4" height="6.2" rx="1.2" {...common} />
          <path d="M17.4 3.4v3M17.4 12.6v3" {...common} />
        </svg>
      );
    case "custody":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <rect x="3.6" y="4.6" width="16.8" height="14.8" rx="2.4" {...common} />
          <circle cx="12" cy="12" r="3.5" {...common} />
          <path d="M12 8.5V6.9M12 15.5v1.6M8.5 12H6.9M15.5 12h1.6" {...common} />
        </svg>
      );
    case "exchange":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <path d="M4 8.8h13.2l-3.2-3.2" {...common} />
          <path d="M20 15.2H6.8l3.2 3.2" {...common} />
        </svg>
      );
    case "fund":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <path d="M12 3.6l8.4 3.9-8.4 3.9-8.4-3.9z" {...common} />
          <path d="M3.6 12l8.4 3.9 8.4-3.9" {...common} />
          <path d="M3.6 16.5l8.4 3.9 8.4-3.9" {...common} />
        </svg>
      );
    case "market":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <path d="M5.6 5.8a8.6 8.6 0 0 0 0 12.4M8.7 8.8a4.4 4.4 0 0 0 0 6.4" {...common} />
          <path d="M18.4 5.8a8.6 8.6 0 0 1 0 12.4M15.3 8.8a4.4 4.4 0 0 1 0 6.4" {...common} />
          <circle cx="12" cy="12" r="1.9" {...common} />
        </svg>
      );
    case "report":
      return (
        <svg viewBox="0 0 24 24" aria-hidden>
          <rect x="5.2" y="3.6" width="13.6" height="16.8" rx="1.8" {...common} />
          <path d="M9 15.8v-3.2M12 15.8v-6M15 15.8v-4.4" {...common} />
        </svg>
      );
  }
}

function point(el: Element, wrap: DOMRect, edge: "left" | "right" | "top" | "bottom") {
  const r = el.getBoundingClientRect();
  const x =
    edge === "left" ? r.left - wrap.left : edge === "right" ? r.right - wrap.left : r.left - wrap.left + r.width / 2;
  const y =
    edge === "top" ? r.top - wrap.top : edge === "bottom" ? r.bottom - wrap.top : r.top - wrap.top + r.height / 2;
  return { x, y };
}

function curve(from: { x: number; y: number }, to: { x: number; y: number }, vertical: boolean) {
  if (vertical) {
    const midY = (from.y + to.y) / 2;
    return `M ${from.x} ${from.y} C ${from.x} ${midY} ${to.x} ${midY} ${to.x} ${to.y}`;
  }
  const span = to.x - from.x;
  const mergeX = from.x + Math.min(Math.max(span * 0.45, 20), Math.max(span - 28, 20));
  return `M ${from.x} ${from.y} C ${mergeX} ${from.y} ${to.x - 28} ${to.y} ${to.x} ${to.y}`;
}

function PowerGridDiagram() {
  const wrapRef = useRef<HTMLDivElement>(null);
  const [lines, setLines] = useState<Line[]>([]);

  useLayoutEffect(() => {
    const wrap = wrapRef.current;
    if (!wrap) return;

    const draw = () => {
      const box = wrap.getBoundingClientRect();
      if (box.width === 0) return;
      const vertical = box.width < 992;
      const hub = wrap.querySelector("[data-pg='hub']");
      const dest = wrap.querySelector("[data-pg='dest']");
      const sourceEls = wrap.querySelectorAll("[data-pg='source']");
      if (!hub || !dest) return;

      const hubIn = point(hub, box, vertical ? "top" : "left");
      const hubOut = point(hub, box, vertical ? "bottom" : "right");
      const destIn = point(dest, box, vertical ? "top" : "left");
      const next: Line[] = [];

      sourceEls.forEach((el, i) => {
        const from = point(el, box, vertical ? "bottom" : "right");
        next.push({
          id: `pg-source-${i}`,
          d: curve(from, hubIn, vertical),
          delay: `${i * 0.22}s`,
        });
      });

      next.push({
        id: "pg-out",
        d: curve(hubOut, destIn, vertical),
        delay: `${sourceEls.length * 0.22}s`,
      });

      setLines(next);
    };

    draw();
    const ro = new ResizeObserver(draw);
    ro.observe(wrap);
    window.addEventListener("resize", draw);
    return () => {
      ro.disconnect();
      window.removeEventListener("resize", draw);
    };
  }, []);

  const columns = [0, 1, 2].map((col) => sources.filter((source) => source.col === col));

  return (
    <div className="pg-diagram" ref={wrapRef}>
      <svg className="pg-lines" aria-hidden>
        {lines.map((line) => (
          <path key={`${line.id}-base`} className="pg-line-base" d={line.d} />
        ))}
        {lines.map((line) => (
          <path
            key={`${line.id}-flow`}
            id={line.id}
            className="pg-line-flow"
            d={line.d}
            style={{ animationDelay: line.delay }}
          />
        ))}
        {lines.map((line, i) => (
          <circle key={`${line.id}-dot`} className="pg-dot" r={4}>
            <animateMotion dur={`${2.2 + (i % 3) * 0.35}s`} repeatCount="indefinite" begin={line.delay}>
              <mpath href={`#${line.id}`} />
            </animateMotion>
          </circle>
        ))}
      </svg>

      <div className="pg-nodes">
        {columns.map((colSources, col) => (
          <div className="pg-node-col" key={col}>
            {colSources.map((source) => (
              <div className="pg-node" data-pg="source" key={source.name}>
                <span className="pg-node-mark">
                  <SourceIcon icon={source.icon} />
                </span>
                <span className="pg-node-name">{source.name}</span>
              </div>
            ))}
          </div>
        ))}
      </div>

      <div className="pg-hub-wrap">
        <div className="pg-hub" data-pg="hub">
          <img className="pg-hub-mark" src="/icons/oxyfinz-512.png" alt="Oxyfinz" />
        </div>
      </div>

      <div className="pg-outcome">
        <div className="pg-product" data-pg="dest">
          <div className="pg-product-media">
            <img
              src="/dash8.png"
              alt="Oxyfinz client dashboard"
            />
          </div>
          <div className="pg-product-body">
            <p className="pg-product-label">Client book</p>
            <p className="pg-product-value">€ 24.80M</p>
            <button className="pg-product-btn" type="button">
              Open dashboard
            </button>
          </div>
        </div>
        <aside className="pg-success">
          <svg className="pg-check" viewBox="0 0 42 42" aria-hidden>
            <circle className="pg-check-ring" cx="21" cy="21" r="17" />
            <path className="pg-check-mark" d="M13 21.5l5.2 5.2L29 16" />
          </svg>
          <p className="pg-success-title">Portfolio in sync</p>
          <div className="pg-success-pill">
            <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden>
              <path d="M2 6h8M7 3l3 3-3 3" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
            </svg>
            Holdings are up to date
          </div>
        </aside>
      </div>
    </div>
  );
}

export function PowerGrid() {
  return (
    <section className="wwd-section wwd-section--follow" id="how-it-works">
      <div className="wwd-inner">
        <div className="wwd-top-row">
          <span className="wwd-eyebrow">How it works</span>
        </div>
        <div className="wwd-header-row">
          <h2 className="wwd-headline pg-headline">
            One portfolio power{" "}
            <span className="pg-spark">
              <span className="pg-spark-marks" aria-hidden>
                <i />
                <i />
                <i />
              </span>
              grid
            </span>
          </h2>
        </div>
        <PowerGridDiagram />
      </div>
    </section>
  );
}
