/* ENKII — animated SVG visualizations. Exposes window.Viz */
/* global React */
const { useState, useEffect, useRef } = React;

function useTick(active, speed = 1) {
  const [t, setT] = useState(0);
  useEffect(() => {
    let raf, start = performance.now();
    const loop = (now) => {
      setT((now - start) / 1000 * speed);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [speed]);
  return t;
}

/* ---------- BARS (web platforms) ---------- */
function VizBars({ a, a2, active }) {
  const t = useTick(active);
  const n = 22;
  const bars = Array.from({ length: n }, (_, i) => {
    const base = 18 + 60 * Math.abs(Math.sin(i * 0.7 + 1.3));
    const wob = active ? Math.sin(t * 2 + i * 0.6) * 10 : Math.sin(i) * 3;
    return Math.max(10, Math.min(96, base + wob));
  });
  const hi = active ? (Math.floor(t * 1.6) % n) : 9;
  return (
    <svg viewBox="0 0 320 130" preserveAspectRatio="none" className="viz-svg">
      <defs>
        <linearGradient id="bg1" x1="0" y1="1" x2="0" y2="0">
          <stop offset="0" stopColor={a} stopOpacity="0.25" />
          <stop offset="1" stopColor={a2} stopOpacity="1" />
        </linearGradient>
      </defs>
      {bars.map((h, i) => {
        const x = 6 + i * 14;
        return (
          <rect key={i} x={x} y={120 - h} width="8" height={h} rx="3"
            fill={i === hi ? a2 : "url(#bg1)"}
            opacity={i === hi ? 1 : 0.85}
            style={{ filter: i === hi ? `drop-shadow(0 0 6px ${a2})` : "none" }} />
        );
      })}
    </svg>
  );
}

/* ---------- RINGS (mobile dual donut) ---------- */
function Donut({ cx, cy, r, pct, a, a2, t, dur }) {
  const C = 2 * Math.PI * r;
  const target = pct / 100;
  const grow = Math.min(1, t / dur);
  const off = C * (1 - target * grow);
  return (
    <g>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="currentColor" strokeOpacity="0.12" strokeWidth="9" />
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={a} strokeWidth="9" strokeLinecap="round"
        strokeDasharray={C} strokeDashoffset={off} transform={`rotate(-90 ${cx} ${cy})`}
        style={{ filter: `drop-shadow(0 0 5px ${a})` }} />
      <text x={cx} y={cy + 5} textAnchor="middle" fontSize="20" fontWeight="700" fill="currentColor">
        {Math.round(pct * grow)}<tspan fontSize="11">%</tspan>
      </text>
    </g>
  );
}
function VizRings({ a, a2, active }) {
  const t = useTick(active);
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      <Donut cx={86} cy={65} r={42} pct={84} a={a} a2={a2} t={t} dur={1.1} />
      <Donut cx={234} cy={65} r={42} pct={73} a={a2} a2={a} t={t} dur={1.4} />
      <text x={86} y={122} textAnchor="middle" fontSize="10" fill="currentColor" opacity="0.5" letterSpacing="1">iOS</text>
      <text x={234} y={122} textAnchor="middle" fontSize="10" fill="currentColor" opacity="0.5" letterSpacing="1">ANDROID</text>
    </svg>
  );
}

/* ---------- NETWORK (AI agents) ---------- */
function VizNetwork({ a, a2, active }) {
  const t = useTick(active);
  const nodes = useRef(Array.from({ length: 11 }, (_, i) => ({
    bx: 30 + Math.random() * 260, by: 20 + Math.random() * 90,
    ph: Math.random() * 6.28, sp: 0.6 + Math.random() * 0.8, amp: 4 + Math.random() * 6,
    hub: i === 0,
  }))).current;
  const pos = nodes.map(n => ({
    x: n.bx + Math.cos(t * n.sp + n.ph) * n.amp,
    y: n.by + Math.sin(t * n.sp + n.ph) * n.amp,
    hub: n.hub,
  }));
  const edges = [];
  for (let i = 1; i < pos.length; i++) {
    edges.push([0, i]);
    if (i < pos.length - 1 && i % 2 === 0) edges.push([i, i + 1]);
  }
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      {edges.map(([i, j], k) => {
        const pulse = active ? (0.2 + 0.5 * (0.5 + 0.5 * Math.sin(t * 3 - k))) : 0.25;
        return <line key={k} x1={pos[i].x} y1={pos[i].y} x2={pos[j].x} y2={pos[j].y}
          stroke={a} strokeOpacity={pulse} strokeWidth="1" />;
      })}
      {pos.map((p, i) => (
        <circle key={i} cx={p.x} cy={p.y} r={p.hub ? 7 : 3.4} fill={p.hub ? a2 : a}
          style={{ filter: `drop-shadow(0 0 ${p.hub ? 8 : 4}px ${p.hub ? a2 : a})` }} />
      ))}
    </svg>
  );
}

/* ---------- FLOW (automation pipeline) ---------- */
function VizFlow({ a, a2, active }) {
  const t = useTick(active);
  const stops = [40, 110, 180, 250];
  const y = 65;
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      <line x1="40" y1={y} x2="280" y2={y} stroke="currentColor" strokeOpacity="0.15" strokeWidth="2" />
      {[0, 1, 2].map(s => {
        const prog = active ? ((t * 0.6 + s * 0.33) % 1) : (0.3 + s * 0.25);
        const x = 40 + prog * 240;
        return <circle key={s} cx={x} cy={y} r="4" fill={a2} style={{ filter: `drop-shadow(0 0 6px ${a2})` }} />;
      })}
      {stops.map((x, i) => (
        <g key={i}>
          <rect x={x - 14} y={y - 16} width="28" height="32" rx="7" fill="currentColor" fillOpacity="0.06"
            stroke={a} strokeOpacity="0.5" />
          <circle cx={x} cy={y} r="3.2" fill={a} />
        </g>
      ))}
      <rect x={266} y={y - 16} width="28" height="32" rx="7" fill={a} fillOpacity="0.18" stroke={a2} />
    </svg>
  );
}

/* ---------- AREA (backend throughput) ---------- */
function VizArea({ a, a2, active }) {
  const t = useTick(active);
  const N = 40, W = 320, H = 130;
  let d = `M0 ${H} `, dl = "";
  for (let i = 0; i <= N; i++) {
    const x = (i / N) * W;
    const v = 0.5 + 0.32 * Math.sin(i * 0.45 + t * (active ? 2 : 0.4)) + 0.12 * Math.sin(i * 1.3 + t);
    const y = H - v * (H - 18) - 6;
    d += `L${x.toFixed(1)} ${y.toFixed(1)} `;
    dl += (i === 0 ? "M" : "L") + x.toFixed(1) + " " + y.toFixed(1) + " ";
  }
  d += `L${W} ${H} Z`;
  return (
    <svg viewBox="0 0 320 130" preserveAspectRatio="none" className="viz-svg">
      <defs>
        <linearGradient id="ar1" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor={a2} stopOpacity="0.45" />
          <stop offset="1" stopColor={a} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={d} fill="url(#ar1)" />
      <path d={dl} fill="none" stroke={a2} strokeWidth="2" style={{ filter: `drop-shadow(0 0 5px ${a2})` }} />
    </svg>
  );
}

/* ---------- ORBIT (scalable architecture) ---------- */
function VizOrbit({ a, a2, active }) {
  const t = useTick(active);
  const cx = 160, cy = 65;
  const rings = [22, 38, 54];
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      {rings.map((r, i) => (
        <ellipse key={i} cx={cx} cy={cy} rx={r * 1.9} ry={r * 0.66} fill="none"
          stroke={i % 2 ? a2 : a} strokeOpacity="0.3" strokeWidth="1" />
      ))}
      {rings.map((r, i) => {
        const ang = t * (active ? 1 : 0.3) * (i % 2 ? -1 : 1) + i * 2;
        const x = cx + Math.cos(ang) * r * 1.9;
        const y = cy + Math.sin(ang) * r * 0.66;
        return <circle key={i} cx={x} cy={y} r="4" fill={i % 2 ? a2 : a}
          style={{ filter: `drop-shadow(0 0 6px ${i % 2 ? a2 : a})` }} />;
      })}
      <circle cx={cx} cy={cy} r="9" fill={a} style={{ filter: `drop-shadow(0 0 10px ${a})` }} />
      <circle cx={cx} cy={cy} r="14" fill="none" stroke={a2} strokeOpacity={0.4 + 0.4 * Math.sin(t * 3)} />
    </svg>
  );
}

/* ---------- COUNTERS (case studies) ---------- */
function Counter({ to, suffix, dur = 1.4 }) {
  const [v, setV] = useState(0);
  useEffect(() => {
    let raf, s = performance.now();
    const tgt = parseFloat(to) || 0;
    const loop = (n) => {
      const p = Math.min(1, (n - s) / (dur * 1000));
      const e = 1 - Math.pow(1 - p, 3);
      setV(tgt * e);
      if (p < 1) raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [to]);
  const dec = String(to).includes(".") ? 1 : 0;
  return <span>{v.toFixed(dec)}{suffix}</span>;
}
function VizCounters({ a, a2, active }) {
  const t = useTick(active);
  const items = [["120", "+", "PROJECTS"], ["4.2", "×", "ROI"], ["98", "%", "CSAT"]];
  return (
    <div className="viz-counters" style={{ color: a2 }}>
      {items.map(([n, s, l], i) => (
        <div key={i} className="vc-item">
          <div className="vc-num"><Counter to={n} suffix={s} /></div>
          <div className="vc-lbl">{l}</div>
        </div>
      ))}
    </div>
  );
}

/* ---------- TIMELINE (process) ---------- */
function VizTimeline({ a, a2, active }) {
  const t = useTick(active);
  const steps = ["DISC", "ARCH", "DSGN", "DEV", "TEST", "SHIP", "GROW"];
  const cur = active ? Math.floor(t * 0.9) % steps.length : 3;
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      <line x1="22" y1="65" x2="298" y2="65" stroke="currentColor" strokeOpacity="0.15" strokeWidth="2" />
      <line x1="22" y1="65" x2={22 + (cur / (steps.length - 1)) * 276} y2="65" stroke={a2} strokeWidth="2"
        style={{ filter: `drop-shadow(0 0 5px ${a2})` }} />
      {steps.map((s, i) => {
        const x = 22 + (i / (steps.length - 1)) * 276;
        const on = i <= cur;
        return (
          <g key={i}>
            <circle cx={x} cy={65} r={i === cur ? 7 : 4.5} fill={on ? a2 : "currentColor"} fillOpacity={on ? 1 : 0.25}
              style={{ filter: i === cur ? `drop-shadow(0 0 8px ${a2})` : "none" }} />
            <text x={x} y={92} textAnchor="middle" fontSize="8" letterSpacing="1"
              fill="currentColor" opacity={on ? 0.8 : 0.35}>{s}</text>
          </g>
        );
      })}
    </svg>
  );
}

/* ---------- RADAR (team) ---------- */
function VizRadar({ a, a2, active }) {
  const t = useTick(active);
  const cx = 160, cy = 65, R = 48;
  const axes = 6;
  const vals = [0.9, 0.82, 0.95, 0.7, 0.88, 0.78];
  const pt = (i, r) => {
    const ang = -Math.PI / 2 + (i / axes) * Math.PI * 2;
    return [cx + Math.cos(ang) * r, cy + Math.sin(ang) * r];
  };
  const grow = active ? (0.6 + 0.4 * (0.5 + 0.5 * Math.sin(t * 1.5))) : 1;
  const poly = vals.map((v, i) => pt(i, v * R * grow).join(",")).join(" ");
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      {[0.33, 0.66, 1].map((g, i) => (
        <polygon key={i} points={Array.from({ length: axes }, (_, j) => pt(j, R * g).join(",")).join(" ")}
          fill="none" stroke="currentColor" strokeOpacity="0.12" />
      ))}
      {Array.from({ length: axes }, (_, i) => {
        const [x, y] = pt(i, R);
        return <line key={i} x1={cx} y1={cy} x2={x} y2={y} stroke="currentColor" strokeOpacity="0.12" />;
      })}
      <polygon points={poly} fill={a} fillOpacity="0.25" stroke={a2} strokeWidth="2"
        style={{ filter: `drop-shadow(0 0 6px ${a})` }} />
    </svg>
  );
}

/* ---------- CONTACT ---------- */
function VizContact({ a, a2, active }) {
  const t = useTick(active);
  return (
    <svg viewBox="0 0 320 130" className="viz-svg">
      <circle cx={160} cy={65} r={34} fill="none" stroke={a} strokeOpacity="0.3" strokeWidth="1" />
      <circle cx={160} cy={65} r={34} fill="none" stroke={a2} strokeWidth="2"
        strokeDasharray="213" strokeDashoffset={213 * (1 - (active ? (t * 0.4 % 1) : 0.66))}
        transform="rotate(-90 160 65)" strokeLinecap="round" style={{ filter: `drop-shadow(0 0 6px ${a2})` }} />
      <text x="160" y="60" textAnchor="middle" fontSize="22" fontWeight="700" fill="currentColor">24h</text>
      <text x="160" y="78" textAnchor="middle" fontSize="9" letterSpacing="2" fill="currentColor" opacity="0.5">REPLY</text>
      {[0, 1, 2].map(i => {
        const ang = t * 1.2 + i * 2.09;
        return <circle key={i} cx={160 + Math.cos(ang) * 46} cy={65 + Math.sin(ang) * 46} r="3" fill={a2}
          style={{ filter: `drop-shadow(0 0 5px ${a2})` }} />;
      })}
    </svg>
  );
}

/* ---------- PROJECTS ticker (case studies card) ---------- */
function VizProjects({ a, a2, active }) {
  const t = useTick(active);
  const P = (window.ENKII_PROJECTS && window.ENKII_PROJECTS.PROJECTS) || [];
  const show = P.slice(0, 4);
  return (
    <div className="viz-projects">
      {show.map((p, i) => {
        const target = p.status.type === "live" ? 100 : p.status.value;
        const grow = active ? Math.min(1, Math.max(0, t * 1.1 - i * 0.12)) : 1;
        const w = target * grow;
        return (
          <div className="vp-row" key={p.id}>
            <span className="vp-name" style={{ color: p.accent2 }}>{p.name}</span>
            <span className="vp-bar"><span className="vp-fill" style={{ width: w + "%", background: `linear-gradient(90deg, ${p.accent}, ${p.accent2})` }} /></span>
            <span className="vp-val">{p.status.type === "live" ? "LIVE" : Math.round(w) + "%"}</span>
          </div>
        );
      })}
    </div>
  );
}

/* ---------- MVP promo (Build / Ship / Scale pipeline) ---------- */
function VizMvp({ a, a2, active, lang }) {
  const t = useTick(active);
  const steps = [
    { l: "BUILD", g: ["#3b6ef5", "#22d3ee"], end: "#22d3ee", tip: { fr: "CODE", en: "CODE", pt: "CÓDIGO", es: "CÓDIGO" } },
    { l: "SHIP", g: ["#8b5cf6", "#ec4899"], end: "#ec4899", tip: { fr: "STORES", en: "STORES", pt: "LOJAS", es: "TIENDAS" } },
    { l: "SCALE", g: ["#f59e0b", "#fbbf24"], end: "#fbbf24", tip: { fr: "GROWTH", en: "GROWTH", pt: "ESCALA", es: "ESCALA" } },
  ];
  const prog = active ? Math.min(1, t * 0.45) : 1;
  const caption = ({
    fr: "Prêt pour la production · En ligne en 2–4 semaines · Code 100% à vous",
    en: "Production-ready · Live in 2–4 weeks · Code 100% yours",
    pt: "Pronto para produção · No ar em 2–4 semanas · Código 100% teu",
    es: "Listo para producción · En línea en 2–4 semanas · Código 100% tuyo",
  })[lang || "pt"];
  return (
    <div className="viz-mvp">
      <div className="vm-bars">
        {steps.map((s, i) => {
          const w = Math.min(100, Math.max(0, (prog - i * 0.16) * 240));
          const done = w > 99;
          return (
            <div className="vm-row" key={i}>
              <span className="vm-num" style={{ color: s.end }}>{"0" + (i + 1)}</span>
              <span className="vm-l">{s.l}</span>
              <span className="vm-track">
                <span className="vm-fill" style={{ width: w + "%", background: `linear-gradient(90deg, ${s.g[0]}, ${s.g[1]})`, boxShadow: `0 0 12px -2px ${s.end}` }}>
                  <span className="vm-shimmer" />
                </span>
                {w > 2 && <span className="vm-dot" style={{ left: "calc(" + w + "% - 3px)", background: s.end, boxShadow: `0 0 8px 1px ${s.end}` }} />}
              </span>
              <span className="vm-tip" style={{ color: done ? s.end : "var(--text-faint)" }}>{done
                ? <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>
                : s.tip[lang || "pt"]}</span>
            </div>
          );
        })}
      </div>
      <p className="vm-caption">{caption}</p>
    </div>
  );
}

const VIZ_MAP = {
  bars: VizBars, rings: VizRings, network: VizNetwork, flow: VizFlow,
  area: VizArea, orbit: VizOrbit, counters: VizCounters, timeline: VizTimeline,
  radar: VizRadar, contact: VizContact, projects: VizProjects, mvp: VizMvp,
};

function Viz({ type, a, a2, active, lang }) {
  const C = VIZ_MAP[type] || VizBars;
  return <C a={a} a2={a2} active={active} lang={lang} />;
}

window.Viz = Viz;
window.VizCounter = Counter;
