// ──────────────────────────────────────────────────────────────
// Experience Viz — animated card for the Experience section.
// Alternates: big INDUSTRY NAME (title card) → animated bar chart
// about that industry → next industry → its chart → ... on a loop.
// Solid navy card with amber bars, sized to sit in the amber
// Experience section's right column (4:3).
// ──────────────────────────────────────────────────────────────
const { useEffect: useEVEffect, useRef: useEVRef, useState: useEVState } = React;

/* Phase timing (variable per kind). */
const EV_FADE = 0.5;
const EV_BUILD = 1.6;
const EV_TITLE_DUR = 3.8;
const EV_CHART_DUR = 6.2;

/* 4:3 viewBox + single spacing unit. */
const EV_VB_W = 480, EV_VB_H = 360, EV_P = 26;

const evEaseOut = (t) => 1 - Math.pow(1 - Math.max(0, Math.min(1, t)), 3);
const evClamp01 = (t) => Math.max(0, Math.min(1, t));
const evFmt = (n) => n.toLocaleString("en-US");

/* The industries the visual rotates through. value = weekly scans. */
const EV_INDUSTRIES = [
  {
    name: ["In-Store", "Marketing"],
    chartTitle: "Engagement by Asset",
    items: [
      { label: "Endcaps", value: 4820 },
      { label: "Displays", value: 3960 },
      { label: "Shelf", value: 2940 },
      { label: "Decals", value: 2110 },
      { label: "Banners", value: 1450 },
    ],
  },
  {
    name: ["Product", "Packaging"],
    chartTitle: "Engagement by Product",
    items: [
      { label: "Beverage", value: 5210 },
      { label: "Snacks", value: 4080 },
      { label: "Care", value: 3120 },
      { label: "Home", value: 2260 },
      { label: "Frozen", value: 1490 },
    ],
  },
  {
    name: ["Print", "Advertising"],
    chartTitle: "Engagement by Placement",
    items: [
      { label: "Magazine", value: 3640 },
      { label: "Inserts", value: 2880 },
      { label: "Mail", value: 2210 },
      { label: "Catalog", value: 1530 },
      { label: "Flyers", value: 980 },
    ],
  },
];

/* Build the flat phase timeline: title, chart, title, chart, ... */
const EV_PHASES = (() => {
  const list = [];
  let start = 0;
  EV_INDUSTRIES.forEach((ind, idx) => {
    list.push({ kind: "title", ind: idx, start, dur: EV_TITLE_DUR });
    start += EV_TITLE_DUR;
    list.push({ kind: "chart", ind: idx, start, dur: EV_CHART_DUR });
    start += EV_CHART_DUR;
  });
  return { list, loop: start };
})();

function evPhaseState(start, dur, t, loop) {
  let dt = t - start;
  dt = (((dt % loop) + loop + loop / 2) % loop) - loop / 2;
  if (dt < -EV_FADE || dt > dur + EV_FADE) return { opacity: 0, build: 0 };
  if (dt < EV_FADE) return { opacity: (dt + EV_FADE) / (EV_FADE * 2), build: 0 };
  if (dt < EV_FADE + EV_BUILD) return { opacity: 1, build: (dt - EV_FADE) / EV_BUILD };
  if (dt < dur - EV_FADE) return { opacity: 1, build: 1 };
  return { opacity: (dur + EV_FADE - dt) / (EV_FADE * 2), build: 1 };
}

function useEVLoopTime(reduced) {
  const [t, setT] = useEVState(0);
  useEVEffect(() => {
    if (reduced) return;
    let raf, startT = performance.now();
    const tick = (now) => {
      setT(((now - startT) / 1000) % EV_PHASES.loop);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [reduced]);
  return t;
}

/* ───── Title card ───── */
function EVTitleState({ ind, build }) {
  const industry = EV_INDUSTRIES[ind];
  const eyebrowOp = evEaseOut(evClamp01(build / 0.4));
  const lineGap = 54;
  const blockH = (industry.name.length - 1) * lineGap;
  const cx = EV_VB_W / 2;
  const cy = EV_VB_H / 2;
  const firstY = cy - blockH / 2 + 6;
  const ruleW = 56;
  const ruleGrow = evEaseOut(evClamp01((build - 0.35) / 0.5));

  return (
    <svg viewBox={`0 0 ${EV_VB_W} ${EV_VB_H}`} preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      {industry.name.map((ln, i) => {
        const stagger = 0.18 + i * 0.16;
        const op = evEaseOut(evClamp01((build - stagger) / 0.45));
        const slide = (1 - op) * 18;
        return (
          <text key={i} x={cx} y={firstY + i * lineGap + slide}
                textAnchor="middle"
                fontSize="46" fontWeight="600" letterSpacing="-0.02em"
                fill="#E07C00" opacity={op}>{ln}</text>
        );
      })}

      <rect x={cx - (ruleW * ruleGrow) / 2} y={cy + blockH / 2 + 30}
            width={ruleW * ruleGrow} height="4" rx="2" fill="#E07C00" />
    </svg>
  );
}

/* ───── Chart card ───── */
function EVChartState({ ind, build }) {
  const industry = EV_INDUSTRIES[ind];
  const items = industry.items;
  const maxV = Math.max(...items.map((d) => d.value));

  const headerOp = evEaseOut(evClamp01(build / 0.3));
  const eyebrowOp = evEaseOut(evClamp01(build / 0.45));

  const xLabelH = 22;
  const valLabelH = 22;
  const chartTop = EV_P + 56 + valLabelH;
  const baseline = EV_VB_H - EV_P - xLabelH;
  const barsH = baseline - chartTop;
  const barsX0 = EV_P;
  const barsW = EV_VB_W - 2 * EV_P;
  const barW = (barsW - EV_P * 0.7 * (items.length - 1)) / items.length;

  return (
    <svg viewBox={`0 0 ${EV_VB_W} ${EV_VB_H}`} preserveAspectRatio="xMidYMid meet" aria-hidden="true">
      <text x={EV_P} y={EV_P + 16}
            fontSize="12" fontWeight="700" letterSpacing="0.2em"
            fill="rgba(224,124,0,0.7)" opacity={eyebrowOp}>{industry.name.join(" ").toUpperCase()}</text>
      <text x={EV_P} y={EV_P + 42}
            fontSize="22" fontWeight="700"
            fill="#E07C00" opacity={headerOp}>{industry.chartTitle}</text>

      <line x1={barsX0} y1={baseline} x2={barsX0 + barsW} y2={baseline}
            stroke="rgba(224,124,0,0.22)" strokeWidth="1" opacity={headerOp} />

      {items.map((d, i) => {
        const stagger = i * 0.12;
        const grow = evEaseOut(evClamp01((build - stagger) / 0.5));
        const fullH = (d.value / maxV) * barsH;
        const h = fullH * grow;
        const bx = barsX0 + i * (barW + EV_P * 0.7);
        const by = baseline - h;
        const labelOp = evEaseOut(evClamp01((build - stagger - 0.15) / 0.4));
        return (
          <g key={d.label}>
            <rect x={bx} y={by} width={barW} height={Math.max(0.001, h)}
                  rx="5" fill="#E07C00" opacity={0.5 + 0.5 * (d.value / maxV)} />
            <text x={bx + barW / 2} y={by - 8}
                  textAnchor="middle" fontSize="13" fontWeight="700"
                  fill="rgba(224,124,0,0.85)" opacity={labelOp}>{evFmt(d.value)}</text>
            <text x={bx + barW / 2} y={baseline + 17}
                  textAnchor="middle" fontSize="12.5" fontWeight="600"
                  fill="rgba(224,124,0,0.9)" opacity={headerOp}>{d.label}</text>
          </g>
        );
      })}
    </svg>
  );
}

/* ───── Top-level component ───── */
function ExperienceViz() {
  const [reduced, setReduced] = useEVState(() => {
    if (typeof window === "undefined" || !window.matchMedia) return false;
    return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  });
  useEVEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const handler = (e) => setReduced(e.matches);
    mq.addEventListener?.("change", handler);
    return () => mq.removeEventListener?.("change", handler);
  }, []);

  useEVEffect(() => {
    if (document.getElementById("ts-experience-viz-css")) return;
    const s = document.createElement("style");
    s.id = "ts-experience-viz-css";
    s.textContent = `
      .ts-experience-viz {
        position: relative;
        width: 100%;
        aspect-ratio: 4 / 3;
        border-radius: 20px;
        overflow: hidden;
        background: #FCE0B8;
        border: 1px solid rgba(224,124,0,0.14);
        isolation: isolate;
        color: #E07C00;
        font-family: "Montserrat", system-ui, sans-serif;
        box-shadow: 0 24px 50px -24px rgba(224,124,0,0.35);
      }
      .ts-experience-viz .ts-ev-layer {
        position: absolute; inset: 0;
        will-change: opacity, filter;
      }
      .ts-experience-viz svg { display: block; width: 100%; height: 100%; }
      .ts-experience-viz text { font-family: inherit; }
      @media (prefers-reduced-motion: reduce) {
        .ts-experience-viz .ts-ev-layer { transition: none !important; }
      }
    `;
    document.head.appendChild(s);
  }, []);

  const t = useEVLoopTime(reduced);

  if (reduced) {
    return (
      <div className="ts-experience-viz" role="img"
           aria-label="Performance chart for in-store marketing assets.">
        <div className="ts-ev-layer" style={{ opacity: 1 }}>
          <EVChartState ind={0} build={1} />
        </div>
      </div>
    );
  }

  return (
    <div className="ts-experience-viz" role="img"
         aria-label="Animated card cycling through industries and their TapScan engagement charts.">
      {EV_PHASES.list.map((ph, i) => {
        const st = evPhaseState(ph.start, ph.dur, t, EV_PHASES.loop);
        if (st.opacity <= 0.001) return null;
        return (
          <div key={i} className="ts-ev-layer" style={{
            opacity: st.opacity,
            filter: st.opacity < 1 ? `blur(${(1 - st.opacity) * 4}px)` : "none",
          }}>
            {ph.kind === "title"
              ? <EVTitleState ind={ph.ind} build={st.build} />
              : <EVChartState ind={ph.ind} build={st.build} />}
          </div>
        );
      })}
    </div>
  );
}

window.ExperienceViz = ExperienceViz;
