/* global React, window */
/**
 * visualizations.jsx, SVG- and JSX-based data visualizations.
 *
 * All viz components consume `dark` for their light/dark color resolution and
 * are otherwise standalone (no shared state). Animations use SVG SMIL
 * (<animate>) where possible to keep the bundle script-free.
 *
 * Components:
 * - VizFlow         5-station horizontal pipeline with auto-advancing highlight.
 * - VizGrowthChart  12-month animated bar chart (revenue ramp).
 * - VizCoverageMap  Stylized DACH dot map with pulsing partner pins.
 * - VizModuleStack  Horizontal stacked-bar of operative load modules.
 * - VizTimeShift    Before/after donut comparing handwerk-vs-admin time split.
 *
 * Quirks: VizFlow has a setInterval-driven activeIndex that cycles past N
 * (mod N+1), so all stations briefly light up before the cycle restarts.
 */

const T = window.TOKENS;

// 5-station "Operativer Flow" pipeline. Auto-advances the active step every 1.5s.
window.VizFlow = function VizFlow({ dark }) {
  const INK = dark ? "#fff" : T.color.ink;
  const BG_CARD = dark ? "#0F1422" : "#fff";
  const SUB = dark ? "rgba(255,255,255,0.6)" : T.color.muted;
  const BLUE = T.color.blue;
  const BLUE_SOFT = T.color.blueSoft;
  const DEEP = dark ? "rgba(122,143,255,0.25)" : T.color.blueDeep;
  const stations = [
    ["01", "Anfrage", "Lead-Filter"],
    ["02", "Angebot", "innerhalb 24h"],
    ["03", "Auftrag", "Disposition + Material"],
    ["04", "Einbau", "Du auf der Baustelle"],
    ["05", "Rechnung", "GoBD-konform"],
  ];
  const [active, setActive] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setActive(a => (a + 1) % (stations.length + 1)), 1500);
    return () => clearInterval(id);
  }, []);
  return (
    <div style={{ position: "relative", padding: "40px 0 24px" }}>
      {/* Rail */}
      <div style={{ position: "absolute", top: "calc(50% - 12px)", left: 0, right: 0, height: 4, background: INK, transform: "translateY(-50%)" }} />
      {/* Stations */}
      <div style={{ position: "relative", display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 0 }}>
        {stations.map(([n, t, d], i) => {
          const on = active > i;
          return (
            <div key={n} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
              <div style={{
                background: on ? BLUE : BG_CARD,
                color: on ? "#fff" : INK,
                border: `2px solid ${INK}`,
                padding: "18px 14px",
                textAlign: "center",
                minWidth: 110,
                width: "100%",
                maxWidth: 140,
                boxShadow: on ? `6px 6px 0 ${DEEP}` : "none",
                transform: on ? "translate(-2px, -2px)" : "none",
                transition: "all 0.35s ease"
              }}>
                <div style={{ fontFamily: T.font.mono, fontSize: 9, letterSpacing: "0.22em", color: on ? BLUE_SOFT : BLUE, marginBottom: 4 }}>{n}</div>
                <div style={{ fontFamily: T.font.display, fontSize: 17, fontWeight: 700, letterSpacing: "-0.02em" }}>{t}</div>
              </div>
              <div style={{ fontFamily: T.font.sans, fontSize: 12, color: SUB, textAlign: "center", maxWidth: 140, lineHeight: 1.4 }}>{d}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// VizGrowthChart, 12-month revenue ramp, in €K. Bars animate from 0.
window.VizGrowthChart = function VizGrowthChart({ dark }) {
  const sub = dark ? "rgba(255,255,255,0.5)" : "#888";
  const data = [12, 18, 28, 35, 48, 62, 78, 95, 118, 140, 165, 195];
  const max = 200;
  return (
    <svg viewBox="0 0 800 320" style={{ width: "100%", maxWidth: 800, height: "auto", display: "block" }}>
      <text x="0" y="20" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill={sub}>UMSATZWACHSTUM · MONATLICH (€K)</text>
      <line x1="0" y1="280" x2="800" y2="280" stroke={dark ? "rgba(255,255,255,0.2)" : "rgba(0,0,0,0.18)"} strokeWidth="1" />
      {[50, 100, 150, 200].map(v => (
        <g key={v}>
          <line x1="0" y1={280 - (v/max)*230} x2="800" y2={280 - (v/max)*230} stroke={dark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)"} strokeDasharray="2 4" />
          <text x="0" y={280 - (v/max)*230 - 4} fontFamily="JetBrains Mono" fontSize="9" fill={sub}>€{v}K</text>
        </g>
      ))}
      {data.map((v, i) => {
        const w = 50, gap = 12, x = 50 + i * (w + gap), h = (v / max) * 230;
        return (
          <g key={i}>
            <rect x={x} y={280 - h} width={w} height={h} fill={T.color.blue} opacity={0.3 + (i/12)*0.7}>
              <animate attributeName="height" from="0" to={h} dur="0.8s" begin={`${i*0.06}s`} fill="freeze" />
              <animate attributeName="y" from="280" to={280 - h} dur="0.8s" begin={`${i*0.06}s`} fill="freeze" />
            </rect>
            <text x={x + w/2} y="305" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" fill={sub}>M{i+1}</text>
          </g>
        );
      })}
    </svg>
  );
};

// VizCoverageMap, DACH dot map with random thinning + pulsing partner pins.
window.VizCoverageMap = function VizCoverageMap({ dark }) {
  const sub = dark ? "rgba(255,255,255,0.5)" : "#888";
  const ink = dark ? "#fff" : T.color.ink;
  const dotColor = dark ? "rgba(255,255,255,0.18)" : "rgba(15,79,255,0.20)";
  // Generate dot grid roughly DACH-shaped (random thinning is intentional).
  const cells = [];
  for (let y = 0; y < 24; y++) {
    for (let x = 0; x < 32; x++) {
      const cx = x - 16, cy = y - 12;
      const dist = Math.sqrt(cx*cx + cy*cy*1.2);
      if (dist < 14 && Math.random() > 0.15 && !(cy > 9 && cx < -8)) cells.push([x, y]);
    }
  }
  const partners = [
    { x: 12, y: 8, label: "Berlin" },
    { x: 9, y: 11, label: "Frankfurt" },
    { x: 8, y: 14, label: "München" },
    { x: 6, y: 10, label: "Köln" },
    { x: 14, y: 13, label: "Wien" },
    { x: 6, y: 14, label: "Zürich" },
    { x: 18, y: 6, label: "Hamburg" },
  ];
  return (
    <svg viewBox="0 0 640 480" style={{ width: "100%", maxWidth: 640, height: "auto", display: "block" }}>
      <text x="0" y="20" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill={sub}>30+ PARTNERBETRIEBE · DACH</text>
      {cells.map(([x, y], i) => (
        <circle key={i} cx={40 + x*18} cy={50 + y*16} r="1.6" fill={dotColor} />
      ))}
      {partners.map((p, i) => (
        <g key={p.label}>
          <circle cx={40 + p.x*18} cy={50 + p.y*16} r="6" fill={T.color.blue} opacity="0.3">
            <animate attributeName="r" from="6" to="18" dur="2.4s" begin={`${i*0.3}s`} repeatCount="indefinite" />
            <animate attributeName="opacity" from="0.45" to="0" dur="2.4s" begin={`${i*0.3}s`} repeatCount="indefinite" />
          </circle>
          <circle cx={40 + p.x*18} cy={50 + p.y*16} r="4" fill={T.color.blue} />
          <text x={50 + p.x*18} y={54 + p.y*16} fontFamily="Inter" fontSize="11" fontWeight="500" fill={ink}>{p.label}</text>
        </g>
      ))}
    </svg>
  );
};

// VizModuleStack, horizontal stacked bar showing the 8 modules KlimaOne owns.
window.VizModuleStack = function VizModuleStack({ dark }) {
  const sub = dark ? "rgba(255,255,255,0.5)" : "#888";
  const ink = dark ? "#fff" : T.color.ink;
  const modules = [
    ["Kundendienst", 14],["Angebote", 12],["Software", 10],["Finanzen", 14],
    ["Absicherung", 10],["Fuhrpark", 12],["Ausstattung", 10],["Marketing", 18],
  ];
  let off = 0;
  const total = modules.reduce((a,[,v]) => a+v, 0);
  return (
    <svg viewBox="0 0 800 140" style={{ width: "100%", maxWidth: 800, height: "auto", display: "block" }}>
      <text x="0" y="20" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill={sub}>OPERATIVE LAST · ÜBERNOMMEN VON KLIMAONE</text>
      {modules.map(([name, w], i) => {
        const x = (off / total) * 800;
        const width = (w / total) * 800;
        off += w;
        const op = 0.35 + (i * 0.08);
        return (
          <g key={name}>
            <rect x={x} y="40" width={width - 2} height="40" fill={T.color.blue} opacity={Math.min(op, 1)} />
            <text x={x + width/2} y="64" textAnchor="middle" fontFamily="Inter" fontSize="10" fontWeight="600" fill="#fff">{name}</text>
            <text x={x + 2} y="100" fontFamily="JetBrains Mono" fontSize="9" fill={sub}>{String(i+1).padStart(2,"0")}</text>
          </g>
        );
      })}
      <text x="0" y="125" fontFamily="Inter" fontSize="11" fill={ink} fontWeight="500">Du machst das Handwerk.</text>
      <text x="800" y="125" textAnchor="end" fontFamily="Inter" fontSize="11" fill={T.color.blue} fontWeight="500">Wir den Rest.</text>
    </svg>
  );
};

// VizTimeShift, before/after donut: % of time on craft vs. admin.
window.VizTimeShift = function VizTimeShift({ dark }) {
  const ink = dark ? "#fff" : T.color.ink;
  const sub = dark ? "rgba(255,255,255,0.5)" : "#888";
  const Donut = ({ cx, label, craftPct }) => {
    const r = 70, c = 2 * Math.PI * r;
    const craftLen = (craftPct / 100) * c;
    return (
      <g>
        <circle cx={cx} cy="120" r={r} fill="none" stroke={dark ? "rgba(255,255,255,0.12)" : "rgba(0,0,0,0.10)"} strokeWidth="22" />
        <circle cx={cx} cy="120" r={r} fill="none" stroke={T.color.blue} strokeWidth="22" strokeDasharray={`${craftLen} ${c}`} transform={`rotate(-90 ${cx} 120)`} strokeLinecap="butt" />
        <text x={cx} y="115" textAnchor="middle" fontFamily="Space Grotesk" fontWeight="700" fontSize="34" fill={ink} letterSpacing="-1">{craftPct}%</text>
        <text x={cx} y="135" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" fill={sub} letterSpacing="2">HANDWERK</text>
        <text x={cx} y="225" textAnchor="middle" fontFamily="Inter" fontSize="13" fontWeight="600" fill={ink}>{label}</text>
      </g>
    );
  };
  return (
    <svg viewBox="0 0 600 260" style={{ width: "100%", maxWidth: 600, height: "auto", display: "block" }}>
      <text x="300" y="20" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="2" fill={sub}>WO DEINE ZEIT HINGEHT</text>
      <Donut cx={160} label="Vorher" craftPct={45} />
      <Donut cx={440} label="Mit KlimaOne" craftPct={88} />
      <path d="M260,120 L340,120" stroke={T.color.blue} strokeWidth="2" markerEnd="url(#arr2)" />
      <defs>
        <marker id="arr2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto">
          <path d="M0,0 L10,5 L0,10 Z" fill={T.color.blue} />
        </marker>
      </defs>
    </svg>
  );
};
