// ─── Strategy — a hand-drawn ("excalidraw") scroll walkthrough of the growth game plan ───
const { useRef, useState, useEffect, useLayoutEffect } = React;

// Real, verifiable numbers pulled from the live catalog + ads data (no invented metrics).
function stratNumbers() {
  const cat = window.CATALOG, ads = window.ADS, L = window.LISTINGS || [];
  const mk = L.filter((x) => x.makeover);
  const sum = (k) => mk.reduce((a, x) => a + ((x.counts && x.counts[k]) || 0), 0);
  return {
    listings: (cat && cat.totals && cat.totals.listings) || mk.length,
    deliverables: (cat && cat.totals && cat.totals.deliverables) || 0,
    images: sum("images"), videos: sum("videos"), aplus: sum("aplus"),
    platforms: ads ? Object.keys(ads.meta.platforms).length : 0,
    adCreatives: ads ? ads.creatives.length : 0,
    price: (cat && cat.totals && cat.totals.price) || 0,
  };
}

// ── rough.js helpers ──
const INK = "#1c1d22", GREEN = "#15a34a", AMBER = "#d68310", BLUE = "#1f6fd6", PAPER = "#fbfaf6";
const RO = (o = {}) => Object.assign({ roughness: 1.55, bowing: 1.3, stroke: INK, strokeWidth: 2.1, seed: 7 }, o);
const FILL = (c, o = {}) => Object.assign({ fill: c, fillStyle: "hachure", fillWeight: 2.2, hachureGap: 6.5, roughness: 1.4, bowing: 1, stroke: c, strokeWidth: 2.1, seed: 7 }, o);

// Draw using rough into the svg's <g class="rl"> layer; redraws on mount/resize.
function useSketch(drawFn, deps = []) {
  const ref = useRef(null);
  useLayoutEffect(() => {
    const svg = ref.current; if (!svg) return;
    const layer = svg.querySelector(".rl"); if (!layer) return;
    while (layer.firstChild) layer.removeChild(layer.firstChild);
    if (!window.rough) return; // graceful: text labels still render without sketch strokes
    try { drawFn(window.rough.svg(svg), layer); } catch (e) { /* keep content visible */ }
  }, deps);
  return ref;
}
function add(layer, node) { if (node) layer.appendChild(node); }
function arrow(rc, layer, x1, y1, x2, y2, o = {}) {
  add(layer, rc.line(x1, y1, x2, y2, RO(o)));
  const a = Math.atan2(y2 - y1, x2 - x1), s = 13;
  add(layer, rc.line(x2, y2, x2 - s * Math.cos(a - 0.5), y2 - s * Math.sin(a - 0.5), RO(o)));
  add(layer, rc.line(x2, y2, x2 - s * Math.cos(a + 0.5), y2 - s * Math.sin(a + 0.5), RO(o)));
}
function ringArrow(rc, layer, cx, cy, R, dA, dB, o = {}) {
  const r = (d) => d * Math.PI / 180;
  const ax = cx + R * Math.cos(r(dA)), ay = cy + R * Math.sin(r(dA));
  const bx = cx + R * Math.cos(r(dB)), by = cy + R * Math.sin(r(dB));
  add(layer, rc.path(`M ${ax} ${ay} A ${R} ${R} 0 0 1 ${bx} ${by}`, RO(o)));
  const t = r(dB + 90), s = 15;
  add(layer, rc.line(bx, by, bx - s * Math.cos(t - 0.5), by - s * Math.sin(t - 0.5), RO(o)));
  add(layer, rc.line(bx, by, bx - s * Math.cos(t + 0.5), by - s * Math.sin(t + 0.5), RO(o)));
}

// ── Diagrams ──
function FunnelSketch() {
  const ref = useSketch((rc, l) => {
    // narrowing funnel; awareness (top) faded/amber = the gap, conversion (bottom) solid green = strong
    add(l, rc.polygon([[80, 56], [540, 56], [470, 168], [150, 168]], FILL(AMBER, { hachureGap: 11, strokeWidth: 1.8, fillWeight: 1.6 })));
    add(l, rc.polygon([[150, 180], [470, 180], [405, 292], [215, 292]], RO({ strokeWidth: 1.9 })));
    add(l, rc.polygon([[215, 304], [405, 304], [350, 420], [270, 420]], FILL(GREEN, { hachureGap: 5, fillWeight: 2.6 })));
    // sparse "limited reach" dots above
    [[180, 30], [250, 22], [330, 28], [400, 20], [450, 34]].forEach((p, i) => add(l, rc.circle(p[0], p[1], 7 + (i % 2) * 4, RO({ stroke: AMBER, strokeWidth: 1.6 }))));
    // side annotations
    add(l, rc.line(548, 96, 600, 78, RO({ stroke: AMBER, strokeWidth: 1.7 })));
    arrow(rc, l, 360, 362, 470, 372, { stroke: GREEN });
  }, []);
  return (
    <svg ref={ref} viewBox="0 0 640 470" className="sk" role="img" aria-label="Funnel: weak awareness at top, strong conversion at bottom">
      <g className="rl"></g>
      <text x="310" y="120" className="sk-l" fill={AMBER} textAnchor="middle">AWARENESS</text>
      <text x="310" y="242" className="sk-l" fill={INK} textAnchor="middle">CLICKS</text>
      <text x="310" y="372" className="sk-l" fill="#0c7a37" textAnchor="middle">CONVERT ✓</text>
      <text x="606" y="74" className="sk-s" fill={AMBER}>too few ever see us</text>
      <text x="478" y="378" className="sk-s" fill="#0c7a37">already elite</text>
    </svg>
  );
}

function FlywheelSketch() {
  const cx = 290, cy = 290, R = 200;
  const ref = useSketch((rc, l) => {
    add(l, rc.circle(cx, cy, R * 2, RO({ strokeWidth: 2.4 })));
    add(l, rc.circle(cx, cy, 246, FILL(PAPER, { fillStyle: "solid", stroke: INK, strokeWidth: 2.2 })));
    ringArrow(rc, l, cx, cy, 238, 285, 345);
    ringArrow(rc, l, cx, cy, 238, 15, 75);
    ringArrow(rc, l, cx, cy, 238, 105, 165);
    ringArrow(rc, l, cx, cy, 238, 195, 255);
    const node = (x, y, c) => add(l, rc.circle(x, y, 96, FILL(c, { fillStyle: "solid", stroke: INK, strokeWidth: 2.3, fillWeight: 1 })));
    node(cx, cy - R, "#eaf7ef"); node(cx + R, cy, "#eef3fb"); node(cx, cy + R, "#fdf1e2"); node(cx - R, cy, "#f3eefb");
  }, []);
  return (
    <svg ref={ref} viewBox="0 0 580 580" className="sk" role="img" aria-label="Creative flywheel: generate, launch, measure, learn">
      <g className="rl"></g>
      <circle className="fly-march" cx={cx} cy={cy} r="200"></circle>
      <text x={cx} y={cy - R - 6} className="sk-l" textAnchor="middle">GENERATE</text>
      <text x={cx} y={cy - R + 16} className="sk-s" textAnchor="middle" fill={AMBER}>24–48h</text>
      <text x={cx + R} y={cy + 5} className="sk-l" textAnchor="middle">LAUNCH</text>
      <text x={cx} y={cy + R + 2} className="sk-l" textAnchor="middle">MEASURE</text>
      <text x={cx - R} y={cy + 5} className="sk-l" textAnchor="middle">LEARN</text>
      <text x={cx} y={cy - 12} className="sk-h" textAnchor="middle">Vivunt</text>
      <text x={cx} y={cy + 22} className="sk-mini" textAnchor="middle">Creative Studio</text>
    </svg>
  );
}

function ChannelsSketch() {
  const ref = useSketch((rc, l) => {
    add(l, rc.rectangle(36, 196, 168, 96, FILL(PAPER, { fillStyle: "solid", strokeWidth: 2.3 })));
    const chip = (y, c) => add(l, rc.rectangle(272, y, 188, 70, FILL("#ffffff", { fillStyle: "solid", stroke: c, strokeWidth: 2.4 })));
    chip(70, "#0866ff"); chip(204, "#111111"); chip(338, "#ff0000");
    // studio -> channels
    arrow(rc, l, 208, 232, 268, 104);
    arrow(rc, l, 208, 244, 268, 238);
    arrow(rc, l, 208, 256, 268, 372);
    // big Amazon node
    add(l, rc.rectangle(560, 168, 200, 168, FILL("#fff6e9", { fillStyle: "solid", stroke: "#e0850c", strokeWidth: 2.6 })));
    arrow(rc, l, 464, 104, 556, 214);
    arrow(rc, l, 464, 238, 556, 252);
    arrow(rc, l, 464, 372, 556, 296);
    // outputs
    add(l, rc.rectangle(812, 150, 196, 64, FILL("#eaf7ef", { fillStyle: "solid", stroke: GREEN, strokeWidth: 2.3 })));
    add(l, rc.rectangle(812, 262, 196, 64, FILL("#eef3fb", { fillStyle: "solid", stroke: BLUE, strokeWidth: 2.3 })));
    arrow(rc, l, 762, 226, 808, 184);
    arrow(rc, l, 762, 278, 808, 292);
    // compounding loop back to channels (dashed)
    add(l, rc.path("M 1006 150 C 1040 40 360 -16 366 60", RO({ strokeLineDash: [9, 11], stroke: AMBER, strokeWidth: 2 })));
    arrow(rc, l, 396, 48, 368, 64, { stroke: AMBER });
  }, []);
  return (
    <svg ref={ref} viewBox="0 0 1040 430" className="sk sk-wide" role="img" aria-label="Studio produces creatives, launched across channels, funneling traffic to Amazon">
      <g className="rl"></g>
      <text x="120" y="238" className="sk-l" textAnchor="middle">VIVUNT</text>
      <text x="120" y="262" className="sk-mini" textAnchor="middle">Studio</text>
      <text x="366" y="112" className="sk-l" textAnchor="middle" fill="#0866ff">Meta</text>
      <text x="366" y="246" className="sk-l" textAnchor="middle" fill="#111">TikTok</text>
      <text x="366" y="380" className="sk-l" textAnchor="middle" fill="#ff0000">YouTube</text>
      <text x="660" y="244" className="sk-h" textAnchor="middle" fill="#c5740a">AMAZON</text>
      <text x="660" y="276" className="sk-mini" textAnchor="middle">where we convert</text>
      <text x="910" y="188" className="sk-mini" textAnchor="middle" fill="#0c7a37">Organic sales ↑</text>
      <text x="910" y="300" className="sk-mini" textAnchor="middle" fill={BLUE}>Remarketing pool ↑</text>
      <text x="690" y="38" className="sk-s" fill={AMBER}>awareness compounds ↺</text>
    </svg>
  );
}

function GoalSketch() {
  const ref = useSketch((rc, l) => {
    add(l, rc.ellipse(300, 86, 500, 142, FILL("#fff7ea", { fillStyle: "solid", stroke: "#e0850c", strokeWidth: 2.6 })));
    for (let i = 0; i < 14; i++) { const a = i * Math.PI / 7; add(l, rc.line(300 + 256 * Math.cos(a), 86 + 86 * Math.sin(a), 300 + 292 * Math.cos(a), 86 + 100 * Math.sin(a), RO({ stroke: AMBER, strokeWidth: 1.6 }))); }
    const card = (x, c) => add(l, rc.rectangle(x, 214, 168, 168, FILL("#ffffff", { fillStyle: "solid", stroke: c, strokeWidth: 2.4 })));
    card(24, GREEN); card(216, BLUE); card(408, "#7a45c7");
  }, []);
  return (
    <svg ref={ref} viewBox="0 0 600 416" className="sk" role="img" aria-label="Goal: millions of impressions per month feeding organic sales, remarketing, and profitable scale">
      <g className="rl"></g>
      <text x="300" y="78" className="sk-big" textAnchor="middle" fill="#c5740a">MILLIONS</text>
      <text x="300" y="116" className="sk-mini" textAnchor="middle">of impressions / month · the target</text>
      <text x="108" y="292" className="sk-l" textAnchor="middle" fill="#0c7a37">Organic</text>
      <text x="108" y="316" className="sk-mini" textAnchor="middle">sales lift</text>
      <text x="300" y="292" className="sk-l" textAnchor="middle" fill={BLUE}>Remarketing</text>
      <text x="300" y="316" className="sk-mini" textAnchor="middle">pool grows</text>
      <text x="492" y="292" className="sk-l" textAnchor="middle" fill="#6c3bb8">Profitable</text>
      <text x="492" y="316" className="sk-mini" textAnchor="middle">scale</text>
    </svg>
  );
}

function StatusSketch({ n }) {
  const rows = [
    ["done", `Creative flywheel built — Vivunt Studio is live`],
    ["done", `${n.listings} listing sets produced · ${n.deliverables} deliverables ready`],
    ["done", `${n.images} images · ${n.videos} videos · ${n.aplus} A+ sets`],
    ["done", `Social ad previews ready across ${n.platforms} platforms`],
    ["wait", `Awaiting green light → pay → download → upload → live in days`],
  ];
  const ref = useSketch((rc, l) => {
    add(l, rc.rectangle(24, 18, 812, 392, FILL(PAPER, { fillStyle: "solid", strokeWidth: 2.4 })));
    rows.forEach((r, i) => {
      const y = 66 + i * 70, done = r[0] === "done";
      add(l, rc.rectangle(60, y - 24, 36, 36, RO({ stroke: done ? GREEN : AMBER, strokeWidth: 2.3 })));
      if (done) { add(l, rc.line(67, y - 6, 76, y + 4, RO({ stroke: GREEN, strokeWidth: 2.6 }))); add(l, rc.line(76, y + 4, 92, y - 18, RO({ stroke: GREEN, strokeWidth: 2.6 }))); }
      else { add(l, rc.line(70, y - 16, 86, y - 16, RO({ stroke: AMBER, strokeWidth: 2.2 }))); add(l, rc.line(70, y + 8, 86, y + 8, RO({ stroke: AMBER, strokeWidth: 2.2 }))); add(l, rc.path(`M 70 -16 L 86 8`, RO({ stroke: AMBER }))); add(l, rc.line(71, y - 14, 85, y + 6, RO({ stroke: AMBER, strokeWidth: 1.8 }))); add(l, rc.line(85, y - 14, 71, y + 6, RO({ stroke: AMBER, strokeWidth: 1.8 }))); }
    });
  }, [n.listings, n.deliverables]);
  return (
    <svg ref={ref} viewBox="0 0 860 428" className="sk sk-wide" role="img" aria-label="Status checklist">
      <g className="rl"></g>
      {rows.map((r, i) => (
        <text key={i} x="122" y={72 + i * 70} className="sk-row" fill={r[0] === "done" ? INK : "#9a6a06"}>{r[1]}</text>
      ))}
    </svg>
  );
}

// ── Measurement: a "lite" Amazon A/B results card + an omnichannel scoreboard (the Measure/Learn step, made concrete) ──
function ABCard() {
  return (
    <div className="ab-card">
      <span className="ab-pin"></span>
      <div className="ab-src">Amazon · Manage Your Experiments</div>
      <div className="ab-prob">There’s a <b>63%</b> probability <span className="ab-a">Version A</span> is better.</div>
      <div className="ab-bar"><span style={{ width: "63%" }}></span></div>
      <div className="ab-ev">Weak evidence so far · <em>illustrative example</em></div>
      <table className="ab-tbl">
        <thead><tr><th>Metric</th><th className="win">Ver. A ✓</th><th>Ver. B</th><th>Δ</th></tr></thead>
        <tbody>
          <tr><td>Conversion</td><td className="win">0.187%</td><td>0.065%</td><td className="up">+0.122%</td></tr>
          <tr><td>Units / visitor</td><td className="win">0.002</td><td>0.001</td><td className="up">+0.001</td></tr>
          <tr><td>Sales</td><td className="win">$25</td><td>$8</td><td className="up">+$17</td></tr>
          <tr><td>Sample size</td><td>1,607</td><td>1,547</td><td>+60</td></tr>
        </tbody>
      </table>
    </div>
  );
}

const OMNI = [
  ["CTR", "click-through rate"],
  ["CVR", "conversion rate"],
  ["View-thru", "video watch duration"],
  ["CPM", "cost / 1,000 impressions"],
  ["Impressions", "total reach per campaign"],
  ["Traffic", "clicks driven to Amazon"],
];
function OmniBoard() {
  return (
    <div className="omni">
      <div className="omni-h">Same rigor, every channel — each creative scored on:</div>
      <div className="omni-grid">
        {OMNI.map(([k, l]) => (
          <div key={k} className="omni-card"><div className="omni-k">{k}</div><div className="omni-l">{l}</div></div>
        ))}
      </div>
      <div className="omni-foot">v1 → v2 → v3 — keep what wins, iterate what doesn’t.</div>
    </div>
  );
}

// ── Panel scaffold ──
function Panel({ id, ch, kicker, title, children, sketch, flip, wide }) {
  return (
    <section className="strat-panel" id={"p-" + id} data-ch={ch || ""}>
      <div className={"strat-row" + (flip ? " flip" : "") + (wide ? " wide" : "")}>
        <div className="strat-copy">
          {kicker && <div className="strat-kick">{kicker}</div>}
          {title && <h2 className="strat-h">{title}</h2>}
          {children}
        </div>
        {sketch && <div className="strat-art">{sketch}</div>}
      </div>
    </section>
  );
}

function Strategy({ go, onCheckout }) {
  const n = stratNumbers();
  const [active, setActive] = useState("insight");
  const CH = [["insight", "Insight"], ["flywheel", "Flywheel"], ["channels", "Channels"], ["method", "Method"], ["goal", "Goal"], ["status", "Status"], ["ask", "Launch"]];
  useEffect(() => {
    const panels = Array.from(document.querySelectorAll(".strat-panel"));
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          if (e.intersectionRatio > 0.45 && e.target.dataset.ch) setActive(e.target.dataset.ch);
        }
      });
    }, { threshold: [0.18, 0.5] });
    panels.forEach((p) => io.observe(p));
    return () => io.disconnect();
  }, []);
  const jump = (k) => { const el = document.getElementById("p-" + k); if (el) el.scrollIntoView({ behavior: "smooth", block: "start" }); };

  return (
    <main className="strat">
      <nav className="strat-rail" aria-label="Sections">
        {CH.map(([k, label]) => (
          <button key={k} className={active === k ? "on" : ""} onClick={() => jump(k)}>
            <span className="dot"></span><span className="lbl">{label}</span>
          </button>
        ))}
      </nav>

      <section className="strat-panel strat-hero in" id="p-hero">
        <div className="hero-grid">
          <div className="eyebrow">Vivunt · Growth strategy</div>
          <h1 className="strat-hero-h">From great conversion<br/>to great <span className="mk">demand</span>.</h1>
          <p className="strat-hero-sub">We already convert. Now we’ve built the engine that gets millions of the right people to see us — and sends them straight to where we win.</p>
          <button className="strat-scroll" onClick={() => jump("insight")}>read the plan ↓</button>
        </div>
      </section>

      <Panel id="insight" ch="insight" flip
        kicker="01 · Why now"
        title={<>We win at the bottom.<br/>We’re <span className="mk mk-a">starving at the top</span>.</>}
        sketch={<FunnelSketch/>}>
        <p>On Amazon our conversion is excellent — even with creative that was thin or missing. Closing the sale was never the problem. The problem is that <strong>too few people ever reach the page</strong>.</p>
        <p>Fix the top of the funnel and every strong number beneath it compounds.</p>
      </Panel>

      <Panel id="flywheel" ch="flywheel"
        kicker="02 · What we built"
        title={<>A creative flywheel<br/>that never stops <span className="mk">spinning</span>.</>}
        sketch={<FlywheelSketch/>}>
        <p>Vivunt Creative Studio turns an idea into test-ready ads in <strong>24–48 hours</strong>. We launch, measure what lands, keep the winners, and feed the learnings straight back in.</p>
        <p>More speed → more shots on goal → <strong>more winners, every week</strong>.</p>
      </Panel>

      <Panel id="channels" ch="channels" wide
        kicker="03 · How it works"
        title={<>Launch everywhere. Funnel everything to <span className="mk">where we win</span>.</>}
        sketch={<ChannelsSketch/>}>
        <p>Waqar puts those creatives to work across <strong>Meta, TikTok and YouTube</strong> — plus select Amazon placements. All of that traffic points to <strong>Amazon</strong>, where our conversion already shines, and every campaign grows our remarketing pool so the next one starts ahead.</p>
      </Panel>

      <Panel id="method" ch="method" wide
        kicker="04 · How we’ll know it’s working"
        title={<>We <span className="mk">measure</span>. We don’t guess.</>}
        sketch={<div className="method-art"><ABCard/><OmniBoard/></div>}>
        <p>Amazon’s built-in A/B testing tells us — with real statistical confidence — which creative actually wins. We bring that same discipline to social: every video and image is scored on the metrics that matter, so we can see, version over version, whether it’s genuinely <strong>getting better</strong> — not just guess.</p>
      </Panel>

      <Panel id="goal" ch="goal" flip
        kicker="05 · Where this goes"
        title={<>Top-of-funnel demand →<br/><span className="mk">bottom-of-funnel profit</span>.</>}
        sketch={<GoalSketch/>}>
        <p>The target: <strong>millions of impressions a month</strong>. That awareness lifts organic Amazon sales, compounds our remarketing audience, and lets us scale both brands profitably.</p>
        <p className="muted-note">“Millions / month” is the stated goal — not a current figure.</p>
      </Panel>

      <Panel id="status" ch="status" wide
        kicker="06 · Where we are"
        title={<>Everything’s built.<br/>We’re <span className="mk">one decision</span> from launch.</>}
        sketch={<StatusSketch n={n}/>}>
        <p>The flywheel is spinning and the creative is in hand. All that’s left is the go-ahead — then download, upload, and the first campaigns are live within days.</p>
        <div className="strat-links">
          <button onClick={() => go && go("listings")}>See the listings →</button>
          <button onClick={() => go && go("social")}>See the social ads →</button>
        </div>
      </Panel>

      <section className="strat-panel strat-ask" id="p-ask" data-ch="ask">
        <div className="ask-inner">
          <div className="strat-kick">The ask</div>
          <h2 className="strat-ask-h">Give the <span className="mk">green light</span>.</h2>
          <p>Approve the package and the first campaigns go live within days. The flywheel does the rest — testing fast, finding winners, and scaling the brands.</p>
          {onCheckout && <button className="strat-cta" onClick={onCheckout}>Acquire the package →</button>}
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { Strategy });
