// visuals.jsx — Inline SVG illustrations & animated step visuals for the LP.

// ────────────────────────────────────────────────────────────────────────────
// CSS for step animations — injected once at mount.
// ────────────────────────────────────────────────────────────────────────────
const STEP_CSS = `
/* Step 1 — flow map: light beams along paths */
@keyframes s1BeamDash{to{stroke-dashoffset:-200}}
.s1-beam{stroke:var(--accent);stroke-width:2;fill:none;stroke-linecap:round;
  stroke-dasharray:14 200;filter:drop-shadow(0 0 6px var(--accent-glow));
  animation:s1BeamDash 1.8s linear infinite}
.s1-node-pulse{animation:s1NodePulse 2.4s ease-in-out infinite}
@keyframes s1NodePulse{0%,100%{filter:drop-shadow(0 0 0 transparent)}
  50%{filter:drop-shadow(0 0 10px var(--accent-glow))}}

/* Step 2 — kanban moving card */
.s2-card{transition:left .9s cubic-bezier(.7,0,.2,1),top .9s cubic-bezier(.7,0,.2,1),background .35s,border-color .35s,box-shadow .35s}
.s2-card.won{background:rgba(34,197,94,.12)!important;border-color:rgba(34,197,94,.55)!important;
  box-shadow:0 0 18px rgba(34,197,94,.32)}
.s2-card.won .s2-bar{background:#22c55e!important}
.s2-card.won .s2-tag{background:rgba(34,197,94,.18);color:#5ee08a;border-color:rgba(34,197,94,.4)}
@keyframes s2WonPop{0%{transform:translateX(-50%) scale(.92)}60%{transform:translateX(-50%) scale(1.06)}100%{transform:translateX(-50%) scale(1)}}
.s2-card.won-pop{animation:s2WonPop .5s ease-out}

/* Step 3 — radar sweep */
@keyframes s3Sweep{to{transform:rotate(360deg)}}
.s3-sweep{transform-origin:0 0;animation:s3Sweep 8s linear infinite}
@keyframes s3DotPulse{0%,100%{r:3;opacity:.55}50%{r:5;opacity:1}}
.s3-dot{animation:s3DotPulse 2s ease-in-out infinite}
.s3-log-row{transition:opacity .5s,transform .5s}

/* Step 4 — dashboard */
@keyframes s4ChartDraw{from{stroke-dashoffset:600}to{stroke-dashoffset:0}}
.s4-line{stroke-dasharray:600;animation:s4ChartDraw 3.2s ease-out forwards}
@keyframes s4Pulse{0%,100%{r:2.5}50%{r:4.5}}
.s4-tip{animation:s4Pulse 1.6s ease-in-out infinite}
@keyframes s4FillIn{from{opacity:0}to{opacity:1}}
.s4-fill{opacity:0;animation:s4FillIn 1s ease-out 1.5s forwards}
`;

(function injectStepCSS(){
  if (typeof document === "undefined") return;
  if (document.getElementById("step-anim-css")) return;
  const s = document.createElement("style");
  s.id = "step-anim-css";
  s.textContent = STEP_CSS;
  document.head.appendChild(s);
})();

// ────────────────────────────────────────────────────────────────────────────
// Generic decorative components (unchanged)
// ────────────────────────────────────────────────────────────────────────────
const ScriptFlourish = ({ style }) => (
  <svg width="180" height="80" viewBox="0 0 180 80" fill="none" style={style}>
    <path d="M5 55 C 30 30, 60 20, 95 25 S 155 50, 168 35 Q 174 28, 168 22 Q 162 18, 155 28"
      stroke="var(--accent)" strokeWidth="2" strokeLinecap="round" fill="none" />
    <circle cx="168" cy="22" r="2.5" fill="var(--accent)" />
  </svg>
);

const ImageSlot = ({ label, aspect = "4/3", style = {} }) => (
  <div className="image-slot image-slot--stripes" style={{ aspectRatio: aspect, width: "100%", ...style }}>
    <div className="image-slot-label">{label}</div>
  </div>
);

// ────────────────────────────────────────────────────────────────────────────
// Step 1 — Diagnóstico: flow map with light beams traveling along the arrows
// ────────────────────────────────────────────────────────────────────────────
const Step1Visual = () => {
  // Each path travels in sequence: lead → atende/qualifica → follow → reunião → contrato
  const paths = [
    "M150 84 C 175 68, 180 64, 200 60",      // lead → qualifica
    "M150 90 C 175 110, 180 145, 200 155",   // lead → atende
    "M320 60 C 350 70, 360 85, 370 100",     // qualifica → follow
    "M320 155 C 350 145, 360 135, 370 125",  // atende → follow
    "M425 141 C 425 175, 380 195, 320 198",  // follow → reunião
    "M260 186 L260 218",                     // qualifica → reunião
    "M260 276 L260 308",                     // reunião → contrato
  ];
  return (
    <div className="step-visual">
      <div className="pv">
        <div className="pv-grid" />
        <svg viewBox="0 0 500 400" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
          <defs>
            <marker id="arr" markerWidth="6" markerHeight="6" refX="3" refY="3" orient="auto">
              <path d="M0 0 L6 3 L0 6 z" fill="rgba(255,255,255,.4)" />
            </marker>
          </defs>

          {/* base arrows (faint) */}
          <g stroke="rgba(255,255,255,.18)" strokeWidth="1" fill="none">
            {paths.map((d, i) => <path key={i} d={d} />)}
          </g>

          {/* animated light beams traveling along the same paths */}
          <g>
            {paths.map((d, i) => (
              <path
                key={i}
                d={d}
                className="s1-beam"
                style={{ animationDelay: `${i * 0.25}s` }}
              />
            ))}
          </g>

          {/* nodes */}
          <g fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,0.66)" letterSpacing=".08em">
            <g className="s1-node-pulse">
              <rect x="40" y="60" width="110" height="56" rx="10" fill="#0a0f1e" stroke="rgba(2,162,255,.45)" strokeWidth="1" />
              <text x="95" y="84" textAnchor="middle" fill="#02a2ff">LEAD</text>
              <text x="95" y="100" textAnchor="middle" fontSize="9">entrada</text>
            </g>
            <rect x="200" y="40" width="120" height="56" rx="10" fill="#0a0f1e" stroke="rgba(255,255,255,.16)" />
            <text x="260" y="64" textAnchor="middle" fill="#ffffff" fontSize="10.5">QUALIFICA</text>
            <text x="260" y="82" textAnchor="middle" fontSize="9">caso / nicho</text>

            <rect x="200" y="130" width="120" height="56" rx="10" fill="#0a0f1e" stroke="rgba(255,255,255,.16)" />
            <text x="260" y="154" textAnchor="middle" fill="#ffffff" fontSize="10.5">ATENDE</text>
            <text x="260" y="172" textAnchor="middle" fontSize="9">resposta &lt; 5min</text>

            <rect x="370" y="85" width="110" height="56" rx="10" fill="#0a0f1e" stroke="rgba(255,255,255,.16)" />
            <text x="425" y="109" textAnchor="middle" fill="#ffffff" fontSize="10.5">FOLLOW-UP</text>
            <text x="425" y="125" textAnchor="middle" fontSize="9">cadência</text>

            <rect x="200" y="220" width="120" height="56" rx="10" fill="#0a0f1e" stroke="rgba(255,255,255,.16)" />
            <text x="260" y="244" textAnchor="middle" fill="#ffffff" fontSize="10.5">REUNIÃO</text>
            <text x="260" y="260" textAnchor="middle" fontSize="9">com sócio</text>

            <g className="s1-node-pulse" style={{ animationDelay: "1s" }}>
              <rect x="200" y="310" width="120" height="56" rx="10" fill="#0a0f1e" stroke="rgba(2,162,255,.45)" strokeWidth="1" />
              <text x="260" y="334" textAnchor="middle" fill="#02a2ff" fontSize="10.5">CONTRATO</text>
              <text x="260" y="350" textAnchor="middle" fontSize="9">fechado</text>
            </g>
          </g>

          {/* hand-drawn accent */}
          <path d="M40 380 Q 200 360, 200 320" stroke="#02a2ff" strokeWidth="1.4" fill="none" strokeDasharray="3 4" strokeLinecap="round" opacity=".6" />
          <text x="38" y="376" fontFamily="Instrument Serif, serif" fontStyle="italic" fontSize="20" fill="#02a2ff">do caos ao previsível</text>
        </svg>
      </div>
    </div>
  );
};

// ────────────────────────────────────────────────────────────────────────────
// Step 2 — Pipeline kanban. Card A: "Novo lead" → "Qualificado".
// Card B: "Reunião" → "Contrato" (turns green/won).
// Moving cards are positioned by measuring real column centers via refs.
// ────────────────────────────────────────────────────────────────────────────
const Step2Visual = () => {
  const cols = ["Novo lead", "Qualificado", "Reunião", "Contrato"];

  const [aPhase, setAPhase] = React.useState(0);
  const [bPhase, setBPhase] = React.useState(0);
  const [colBoxes, setColBoxes] = React.useState(null); // [{left, width, top}]

  const pvRef = React.useRef(null);
  const colRefs = React.useRef([]);
  const slotRefsA = React.useRef([]); // ref to placeholder slot for card A in each col
  const slotRefsB = React.useRef([]);

  // Measure column slot centers on mount + resize
  React.useEffect(() => {
    function measure() {
      if (!pvRef.current) return;
      const root = pvRef.current.getBoundingClientRect();
      const boxes = colRefs.current.map((el, i) => {
        if (!el) return null;
        const r = el.getBoundingClientRect();
        const slotA = slotRefsA.current[i];
        const slotB = slotRefsB.current[i];
        return {
          left: r.left - root.left + r.width / 2,
          width: r.width - 4,
          topA: slotA ? slotA.getBoundingClientRect().top - root.top : 0,
          topB: slotB ? slotB.getBoundingClientRect().top - root.top : 0,
        };
      });
      setColBoxes(boxes);
    }
    measure();
    const ro = new ResizeObserver(measure);
    if (pvRef.current) ro.observe(pvRef.current);
    window.addEventListener("resize", measure);
    // Re-measure after first paint to ensure layout is settled
    const t = setTimeout(measure, 100);
    return () => { ro.disconnect(); window.removeEventListener("resize", measure); clearTimeout(t); };
  }, []);

  React.useEffect(() => {
    const idA = setInterval(() => setAPhase(p => (p + 1) % 3), 2400);
    const startB = setTimeout(() => {
      setBPhase(1);
      window.__s2idB = setInterval(() => setBPhase(p => (p + 1) % 3), 2400);
    }, 1200);
    return () => {
      clearInterval(idA);
      clearTimeout(startB);
      if (window.__s2idB) clearInterval(window.__s2idB);
    };
  }, []);

  // Static placeholders per column
  const staticCards = [
    [{ name: "Maria S.", t: "Trab." }, { name: "João R.", t: "Prev." }],
    [{ name: "Ana C.", t: "Imig." }],
    [{ name: "Pedro L.", t: "Trib." }],
    [{ name: "Beatriz K.", t: "Trab." }],
  ];

  // Compute moving card positions from refs
  const cardA = (() => {
    if (!colBoxes) return null;
    const colIdx = aPhase === 0 ? 0 : 1;
    const box = colBoxes[colIdx];
    if (!box) return null;
    return { left: box.left, top: box.topA, width: box.width, visible: aPhase !== 2 };
  })();
  const cardB = (() => {
    if (!colBoxes) return null;
    const colIdx = bPhase === 0 ? 2 : 3;
    const box = colBoxes[colIdx];
    if (!box) return null;
    return { left: box.left, top: box.topB, width: box.width, visible: bPhase !== 2 };
  })();

  const MovingCard = ({ pos, name, type, won }) => {
    if (!pos) return null;
    return (
      <div
        className={"s2-card" + (won ? " won won-pop" : "")}
        style={{
          position: "absolute",
          left: pos.left,
          top: pos.top,
          width: Math.min(pos.width - 8, 180),
          transform: "translateX(-50%)",
          background: "#000",
          border: "1.5px solid rgba(2,162,255,.6)",
          borderRadius: 8,
          padding: "9px 11px 9px",
          display: pos.visible ? "flex" : "none",
          flexDirection: "column",
          gap: 6,
          boxShadow: "0 6px 24px rgba(0,0,0,.6),0 0 18px rgba(2,162,255,.25)",
          zIndex: 5,
          opacity: pos.visible ? 1 : 0,
          pointerEvents: "none",
        }}
      >
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div className="s2-bar" style={{ height: 6, background: "#02a2ff", width: "65%", borderRadius: 3 }} />
          <span className="s2-tag" style={{
            fontFamily: "Geist Mono, monospace", fontSize: 8, letterSpacing: ".08em",
            padding: "2px 5px", borderRadius: 4, background: "rgba(2,162,255,.14)",
            color: "#7ec4ff", border: "1px solid rgba(2,162,255,.35)",
            transition: "background .3s,color .3s,border-color .3s"
          }}>{type}</span>
        </div>
        <div style={{ height: 5, background: "rgba(255,255,255,.18)", width: "82%", borderRadius: 3 }} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 2 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
            <div style={{ width: 14, height: 14, borderRadius: "50%", background: "rgba(2,162,255,.2)", border: "1px solid rgba(2,162,255,.35)" }} />
            <span style={{ fontFamily: "Geist Mono, monospace", fontSize: 8.5, color: "rgba(255,255,255,.85)" }}>{name}</span>
          </div>
          {won && (
            <span style={{ color: "#5ee08a", fontSize: 9, fontWeight: 700, fontFamily: "Geist Mono, monospace", letterSpacing: ".08em" }}>✓ GANHO</span>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="step-visual">
      <div ref={pvRef} className="pv" style={{ padding: 22, position: "absolute", inset: 0 }}>
        <div style={{
          display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 8,
          position: "relative", height: "100%"
        }}>
          {cols.map((c, i) => {
            const aHere = (i === 0 && aPhase === 0) || (i === 1 && aPhase === 1);
            const bHere = (i === 2 && bPhase === 0) || (i === 3 && bPhase === 1);
            const total = staticCards[i].length + (aHere ? 1 : 0) + (bHere ? 1 : 0);
            // Decide which slots in this column need a placeholder for moving cards
            const showSlotA = i === 0 || i === 1;
            const showSlotB = i === 2 || i === 3;
            return (
              <div
                key={i}
                ref={(el) => (colRefs.current[i] = el)}
                style={{
                  background: "rgba(255,255,255,.02)",
                  border: "1px solid rgba(255,255,255,.08)",
                  borderRadius: 10, padding: 12,
                  display: "flex", flexDirection: "column", gap: 8,
                }}
              >
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                  <span style={{ fontFamily: "Geist Mono, monospace", fontSize: 9.5, letterSpacing: ".12em", textTransform: "uppercase", color: "rgba(255,255,255,0.66)" }}>{c}</span>
                  <span style={{
                    width: 18, height: 18, borderRadius: 6,
                    background: i === 3 ? "rgba(34,197,94,.18)" : "rgba(255,255,255,.04)",
                    color: i === 3 ? "#5ee08a" : "#02a2ff",
                    display: "inline-flex", alignItems: "center", justifyContent: "center",
                    fontSize: 10, transition: "color .3s",
                    fontFamily: "Geist Mono, monospace"
                  }}>{total}</span>
                </div>
                {staticCards[i].map((card, j) => (
                  <div key={j} style={{
                    background: "#000",
                    border: "1px solid rgba(255,255,255,.08)",
                    borderRadius: 8,
                    padding: "10px 10px 8px",
                    display: "flex", flexDirection: "column", gap: 6
                  }}>
                    <div style={{ height: 6, background: "rgba(255,255,255,.18)", width: "70%", borderRadius: 3 }} />
                    <div style={{ height: 5, background: "rgba(255,255,255,.08)", width: "55%", borderRadius: 3 }} />
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 4 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                        <div style={{ width: 14, height: 14, borderRadius: "50%", background: "rgba(255,255,255,.06)", border: "1px solid rgba(255,255,255,.1)" }} />
                        <span style={{ fontFamily: "Geist Mono, monospace", fontSize: 8.5, color: "rgba(255,255,255,.5)" }}>{card.name}</span>
                      </div>
                      <span style={{ fontFamily: "Geist Mono, monospace", fontSize: 8, color: "rgba(255,255,255,.4)" }}>{card.t}</span>
                    </div>
                  </div>
                ))}
                {/* Invisible placeholder slots that reserve vertical space for the moving cards.
                    These guarantee the moving card position == real column layout position. */}
                {showSlotA && (
                  <div ref={(el) => (slotRefsA.current[i] = el)}
                       style={{ height: 64, visibility: "hidden" }} />
                )}
                {showSlotB && (
                  <div ref={(el) => (slotRefsB.current[i] = el)}
                       style={{ height: 64, visibility: "hidden" }} />
                )}
              </div>
            );
          })}
        </div>
        <MovingCard pos={cardA} name="Lucas P." type="Trab." won={false} />
        <MovingCard pos={cardB} name="Carla M." type="Prev." won={bPhase === 1} />
      </div>
    </div>
  );
};

// ────────────────────────────────────────────────────────────────────────────
// Step 3 — 24h radar clock with sweeping line + dynamic activity log
// ────────────────────────────────────────────────────────────────────────────
const Step3Visual = () => {
  const allEvents = [
    ["02:14", "Lead Maria S.", "atendido"],
    ["04:47", "Lead João R.", "qualificado"],
    ["07:30", "Cliente B.", "follow-up"],
    ["11:02", "Reunião conf.", "agendada"],
    ["15:18", "Lead Ana C.", "atendido"],
    ["21:55", "Contrato", "fechado"],
    ["23:08", "Lead Pedro L.", "atendido"],
    ["01:30", "Reunião conf.", "agendada"],
  ];
  const [head, setHead] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setHead(h => (h + 1) % allEvents.length), 2200);
    return () => clearInterval(id);
  }, []);

  // Show last 6 events ending at head (newest at top)
  const visible = Array.from({ length: 6 }, (_, i) => allEvents[(head - i + allEvents.length) % allEvents.length]);

  return (
    <div className="step-visual">
      <div className="pv" style={{ display: "flex", alignItems: "center", justifyContent: "center", overflow: "hidden" }}>
        <svg viewBox="0 0 500 400" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
          <defs>
            <linearGradient id="s3SweepGrad" x1="0" x2="1" y1="0" y2="0">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity=".7" />
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
            </linearGradient>
          </defs>

          {/* clock at left */}
          <g transform="translate(150 200)">
            <circle r="120" stroke="rgba(255,255,255,.08)" strokeWidth="1" fill="none" />
            <circle r="100" stroke="rgba(255,255,255,.05)" strokeWidth="1" fill="none" />
            <circle r="80" stroke="rgba(255,255,255,.04)" strokeWidth="1" fill="none" />

            {/* hour ticks */}
            {Array.from({ length: 24 }).map((_, i) => {
              const a = (i / 24) * Math.PI * 2 - Math.PI / 2;
              const r1 = i % 6 === 0 ? 100 : 106;
              const r2 = 112;
              return <line key={i} x1={Math.cos(a) * r1} y1={Math.sin(a) * r1}
                            x2={Math.cos(a) * r2} y2={Math.sin(a) * r2}
                            stroke="rgba(255,255,255,.25)" strokeWidth="1" />;
            })}
            <text y="-78" textAnchor="middle" fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,.5)" letterSpacing=".12em">00</text>
            <text x="78" y="4" textAnchor="middle" fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,.5)" letterSpacing=".12em">06</text>
            <text y="86" textAnchor="middle" fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,.5)" letterSpacing=".12em">12</text>
            <text x="-78" y="4" textAnchor="middle" fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,.5)" letterSpacing=".12em">18</text>

            {/* radar sweep — pie slice rotating */}
            <g className="s3-sweep">
              <path d="M 0 0 L 120 0 A 120 120 0 0 1 84 84 Z" fill="url(#s3SweepGrad)" />
              <line x1="0" y1="0" x2="120" y2="0" stroke="var(--accent)" strokeWidth="1.5" />
            </g>

            <text y="-4" textAnchor="middle" fontFamily="Instrument Serif, serif" fontStyle="italic" fontSize="48" fill="#ffffff">24h</text>
            <text y="22" textAnchor="middle" fontFamily="Geist Mono, monospace" fontSize="9" fill="rgba(255,255,255,.66)" letterSpacing=".18em">SEM PAUSA</text>

            {/* event dots, pulsing */}
            {[3, 7, 11, 14, 18, 21, 23, 1].map((h, i) => {
              const a = (h / 24) * Math.PI * 2 - Math.PI / 2;
              const x = Math.cos(a) * 120;
              const y = Math.sin(a) * 120;
              return <circle key={i} cx={x} cy={y} r="3" fill="var(--accent)"
                             className="s3-dot" style={{ animationDelay: `${i * 0.25}s` }} />;
            })}
          </g>

          {/* activity log */}
          <g transform="translate(310 70)" fontFamily="Geist Mono, monospace" fontSize="10" fill="rgba(255,255,255,.66)" letterSpacing=".06em">
            <text x="0" y="-8" fill="rgba(255,255,255,.4)" fontSize="9" letterSpacing=".14em">LIVE · OPERAÇÃO</text>
            {visible.map((row, i) => {
              if (!row) return null;
              const opacity = 1 - (i / 7);
              const isFresh = i === 0;
              return (
                <g key={`${head}-${i}`} className="s3-log-row" transform={`translate(0 ${i * 38})`} style={{ opacity }}>
                  <circle cx="6" cy="8" r={isFresh ? 4 : 3} fill={isFresh ? "var(--accent)" : "rgba(255,255,255,.4)"}>
                    {isFresh && <animate attributeName="r" values="3;6;3" dur="1.4s" repeatCount="indefinite" />}
                  </circle>
                  <text x="20" y="12" fill="rgba(255,255,255,.5)">{row[0]}</text>
                  <text x="70" y="12" fill={isFresh ? "#ffffff" : "rgba(255,255,255,.85)"}>{row[1]}</text>
                  <text x="20" y="26" fill={isFresh ? "var(--accent)" : "rgba(255,255,255,.6)"} fontSize="9">→ {row[2]}</text>
                  <line x1="0" y1="34" x2="160" y2="34" stroke="rgba(255,255,255,.06)" />
                </g>
              );
            })}
          </g>
        </svg>
      </div>
    </div>
  );
};

// ────────────────────────────────────────────────────────────────────────────
// Step 4 — Dashboard with animated number tickers + drawing chart line
// ────────────────────────────────────────────────────────────────────────────
function useTicker(target, opts = {}) {
  const { duration = 1800, format = (v) => Math.round(v).toLocaleString("pt-BR") } = opts;
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    let raf, start;
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(eased * target);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);
  return format(val);
}

const Step4Visual = () => {
  const leads = useTicker(1284);
  const conv  = useTicker(31, { format: (v) => `${Math.round(v)}%` });
  const tk    = useTicker(8.4, { format: (v) => `R$ ${v.toFixed(1)}k` });
  const rev   = useTicker(247800, { format: (v) => `R$ ${Math.round(v).toLocaleString("pt-BR")}` });

  // Chart key cycles every 12s to re-trigger draw animation
  const [chartKey, setChartKey] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setChartKey(k => k + 1), 12000);
    return () => clearInterval(id);
  }, []);

  return (
    <div className="step-visual">
      <div className="pv" style={{ padding: 24, position: "absolute", inset: 0 }}>
        {/* top stats */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 12, marginBottom: 18 }}>
          {[
            { lbl: "Leads/mês", val: leads, delta: "+18%" },
            { lbl: "Conversão", val: conv, delta: "+9pp" },
            { lbl: "Ticket méd.", val: tk, delta: "+12%" },
          ].map((s, i) => (
            <div key={i} style={{ background: "#000", border: "1px solid rgba(255,255,255,.08)", borderRadius: 10, padding: "12px 14px" }}>
              <div style={{ fontFamily: "Geist Mono, monospace", fontSize: 9, letterSpacing: ".12em", textTransform: "uppercase", color: "rgba(255,255,255,.42)" }}>{s.lbl}</div>
              <div style={{ fontFamily: "Instrument Serif, serif", fontStyle: "italic", fontSize: 28, color: "#ffffff", marginTop: 4, fontVariantNumeric: "tabular-nums" }}>{s.val}</div>
              <div style={{ fontSize: 10.5, color: "var(--accent)", fontFamily: "Geist Mono, monospace" }}>{s.delta}</div>
            </div>
          ))}
        </div>

        {/* chart */}
        <div style={{ background: "#000", border: "1px solid rgba(255,255,255,.08)", borderRadius: 10, padding: 16, height: "calc(100% - 130px)", position: "relative" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
            <span style={{ fontFamily: "Geist Mono, monospace", fontSize: 9.5, letterSpacing: ".12em", textTransform: "uppercase", color: "rgba(255,255,255,.66)" }}>Receita prevista — próximos 30 dias</span>
            <span style={{ fontFamily: "Geist Mono, monospace", fontSize: 9.5, color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>{rev}</span>
          </div>
          <svg key={chartKey} viewBox="0 0 400 130" style={{ width: "100%", height: "calc(100% - 28px)" }}>
            <defs>
              <linearGradient id="chartFill" x1="0" x2="0" y1="0" y2="1">
                <stop offset="0%" stopColor="var(--accent)" stopOpacity=".4" />
                <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
              </linearGradient>
            </defs>
            {[20, 50, 80, 110].map((y) => (
              <line key={y} x1="0" y1={y} x2="400" y2={y} stroke="rgba(255,255,255,.05)" />
            ))}
            <path className="s4-fill" d="M0 100 L40 85 L80 90 L120 70 L160 75 L200 55 L240 60 L280 40 L320 45 L360 25 L400 30 L400 130 L0 130 Z" fill="url(#chartFill)" />
            <path className="s4-line" d="M0 100 L40 85 L80 90 L120 70 L160 75 L200 55 L240 60 L280 40 L320 45 L360 25 L400 30" stroke="var(--accent)" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
            {[[40,85],[120,70],[200,55],[280,40],[360,25]].map(([x,y],i)=>(
              <circle key={i} cx={x} cy={y} r="2.5" fill="#000" stroke="var(--accent)" strokeWidth="1.4"
                      className={i === 4 ? "s4-tip" : undefined}
                      opacity="0">
                <animate attributeName="opacity" from="0" to="1" begin={`${0.5 + i * 0.2}s`} dur="0.3s" fill="freeze" />
              </circle>
            ))}
          </svg>
        </div>
      </div>
    </div>
  );
};

// ────────────────────────────────────────────────────────────────────────────
// Generic icons
// ────────────────────────────────────────────────────────────────────────────
const PainIcon = ({ kind }) => {
  const props = { width: 18, height: 18, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (kind) {
    case "target": return <svg {...props}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>;
    case "magnet": return <svg {...props}><path d="M5 4v8a7 7 0 0 0 14 0V4"/><path d="M5 4h4v4H5"/><path d="M15 4h4v4h-4"/></svg>;
    case "chart": return <svg {...props}><path d="M3 17l5-6 4 4 8-9"/><path d="M14 6h6v6"/></svg>;
    case "hourglass": return <svg {...props}><path d="M6 3h12"/><path d="M6 21h12"/><path d="M6 3c0 4 6 5 6 9s-6 5-6 9"/><path d="M18 3c0 4-6 5-6 9s6 5 6 9"/></svg>;
    case "megaphone": return <svg {...props}><path d="M3 11v2a1 1 0 0 0 1 1h2l5 4V6L6 10H4a1 1 0 0 0-1 1z"/><path d="M15 8a4 4 0 0 1 0 8"/></svg>;
    case "bolt": return <svg {...props}><path d="M13 2 4 14h7l-1 8 9-12h-7z"/></svg>;
    default: return null;
  }
};

const CheckMark = () => (
  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M2 6 L5 9 L10 3" />
  </svg>
);

const Plus = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
    <path d="M7 2v10M2 7h10" />
  </svg>
);

Object.assign(window, {
  ScriptFlourish, ImageSlot,
  Step1Visual, Step2Visual, Step3Visual, Step4Visual,
  PainIcon, CheckMark, Plus,
});
