// Interactive Use Case Explorer — no robot photos, all code-drawn scenes.
// Layout: left rail = case nav with progress bar; right = animated "scene" panel.

function UseCases() {
  const cases = [
    {
      num: "01",
      industry: "Hospitality",
      time: "3-week pilot",
      stack: ["Custom GPT", "n8n", "Xero"],
      title: "The chef who got their nights back",
      desc: "A 14-table restaurant. We replaced 90 minutes of nightly admin — supplier orders, prep lists, roster swaps — with one custom GPT and an n8n workflow that talks to Xero. The owner now closes the kitchen at 9.",
      metric: { value: "90", unit: "min", label: "saved per night" },
      scene: "kitchen",
    },
    {
      num: "02",
      industry: "Professional Services",
      time: "5-week build",
      stack: ["Claude API", "Internal RAG", "Microsoft 365"],
      title: "The accountant who hired a bot",
      desc: "Twelve-person firm. We built an internal assistant trained on their templates and ATO updates. New starters now ask the bot what they used to ask the partner. Onboarding time: cut in half.",
      metric: { value: "50", unit: "%", label: "faster onboarding" },
      scene: "accountant",
    },
    {
      num: "03",
      industry: "Personal Services",
      time: "2-week pilot",
      stack: ["Instagram API", "Twilio", "GPT-4o"],
      title: "The barber with an autopilot DM",
      desc: "Three-chair shop, no website. We set up an Instagram + SMS agent that books, reminds, reschedules, and upsells. Bookings up 28%. No-shows down 60%. Owner now actually cuts hair.",
      metric: { value: "+28", unit: "%", label: "bookings, in 14 days" },
      scene: "barber",
    },
    {
      num: "04",
      industry: "Legal & Compliance",
      time: "4-week build",
      stack: ["Claude Sonnet", "Vector store", "DocuSign"],
      title: "The lawyer's first read",
      desc: "Boutique firm. Contracts now go through a Claude-powered first-pass review that flags risk in plain English, drafts redlines, and points to the exact clause. Lawyers spend their hours on judgement, not red pens.",
      metric: { value: "4×", unit: "", label: "more contracts reviewed weekly" },
      scene: "legal",
    },
  ];

  const [active, setActive] = useState(0);
  const [autoplay, setAutoplay] = useState(true);
  const [progress, setProgress] = useState(0);
  const intervalRef = useRef(null);

  const STEP_MS = 7000;

  useEffect(() => {
    if (!autoplay) return;
    setProgress(0);
    const start = performance.now();
    const tick = () => {
      const t = (performance.now() - start) / STEP_MS;
      if (t >= 1) {
        setActive((i) => (i + 1) % cases.length);
      } else {
        setProgress(t * 100);
        intervalRef.current = requestAnimationFrame(tick);
      }
    };
    intervalRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(intervalRef.current);
  }, [active, autoplay]);

  const pick = (i) => {
    setActive(i);
    setProgress(0);
  };

  const c = cases[active];

  return (
    <section className="use-cases" id="use-cases">
      <div className="uc-bg-grid" />
      <div className="uc-glow uc-glow-1" />
      <div className="uc-glow uc-glow-2" />

      <div className="container">
        <div className="uc-header reveal">
          <div>
            <span className="eyebrow" style={{ color: "var(--color-highlight)" }}>Use cases</span>
            <h2 className="h-section" style={{ marginTop: 16 }}>
              Real businesses.<br/>Real time saved.
            </h2>
          </div>
          <p className="body-lg" style={{ color: "rgba(255,255,255,0.7)" }}>
            Names changed. Outcomes didn't. Four pilots from the last six months —
            none needed a CTO, all of them paid for themselves before the invoice cleared.
          </p>
        </div>

        <div className="uc-explorer reveal">
          {/* LEFT — case rail */}
          <aside className="uc-rail">
            <div className="uc-rail-head">
              <span className="mono">04 / cases</span>
              <button
                className="uc-autoplay"
                onClick={() => setAutoplay((v) => !v)}
                aria-label={autoplay ? "Pause" : "Play"}
              >
                {autoplay ? (
                  <svg width="10" height="12" viewBox="0 0 10 12" fill="currentColor"><rect x="0" y="0" width="3" height="12"/><rect x="7" y="0" width="3" height="12"/></svg>
                ) : (
                  <svg width="10" height="12" viewBox="0 0 10 12" fill="currentColor"><path d="M0 0 L10 6 L0 12 Z"/></svg>
                )}
              </button>
            </div>

            <ul className="uc-list">
              {cases.map((cc, i) => (
                <li key={i} className={"uc-item" + (i === active ? " active" : "")}>
                  <button onClick={() => pick(i)}>
                    <div className="uc-item-progress">
                      <span className="bar" style={{ width: i === active ? `${progress}%` : (i < active ? "100%" : "0%") }} />
                    </div>
                    <div className="uc-item-row">
                      <span className="uc-item-num">{cc.num}</span>
                      <span className="uc-item-industry">{cc.industry}</span>
                      <span className="uc-item-time">{cc.time}</span>
                    </div>
                    <div className="uc-item-title">{cc.title}</div>
                  </button>
                </li>
              ))}
            </ul>
          </aside>

          {/* RIGHT — scene panel */}
          <div className="uc-stage" key={active /* re-mount on change → triggers SVG animations from start */}>
            <div className="uc-stage-corners" aria-hidden>
              <span className="c tl" /><span className="c tr" /><span className="c bl" /><span className="c br" />
            </div>

            <div className="uc-stage-head">
              <span className="uc-tag mono">Case · {c.num}</span>
              <span className="uc-tag mono">{c.time}</span>
            </div>

            <div className="uc-stage-scene">
              <Scene kind={c.scene} />
            </div>

            <div className="uc-stage-footer">
              <div className="uc-stage-text">
                <h3 className="uc-stage-title">{c.title}</h3>
                <p>{c.desc}</p>
                <div className="uc-stack">
                  {c.stack.map((s, i) => <span className="uc-chip" key={i}>{s}</span>)}
                </div>
              </div>

              <div className="uc-stage-metric">
                <div className="uc-metric-val">
                  <AnimatedNumber to={parseFloat(c.metric.value)} duration={1400} />
                  <span className="uc-metric-unit">{c.metric.unit}</span>
                </div>
                <div className="uc-metric-lbl">{c.metric.label}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============================================================
   Scenes — pure SVG/CSS, brand colors only.
   Each scene tells a small story of the problem-to-solution.
   ============================================================ */

function Scene({ kind }) {
  if (kind === "kitchen") return <KitchenScene />;
  if (kind === "accountant") return <AccountantScene />;
  if (kind === "barber") return <BarberScene />;
  if (kind === "legal") return <LegalScene />;
  return null;
}

/* --- 01 KITCHEN: a clock that visibly shrinks 90 minutes off the night --- */
function KitchenScene() {
  return (
    <div className="scene scene-kitchen">
      {/* Big clock */}
      <div className="kitchen-clock">
        <svg viewBox="0 0 240 240">
          <defs>
            <filter id="kglow"><feGaussianBlur stdDeviation="3" /></filter>
          </defs>
          {/* hour markers */}
          {Array.from({length: 60}).map((_, i) => {
            const a = (i / 60) * Math.PI * 2 - Math.PI / 2;
            const r1 = 110, r2 = i % 5 === 0 ? 100 : 105;
            const x1 = 120 + Math.cos(a) * r1, y1 = 120 + Math.sin(a) * r1;
            const x2 = 120 + Math.cos(a) * r2, y2 = 120 + Math.sin(a) * r2;
            return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="rgba(255,255,255,0.25)" strokeWidth={i % 5 === 0 ? 2 : 1}/>;
          })}
          {/* the "saved" arc — sweeps from 9pm (top-3) covering 90 minutes */}
          <circle cx="120" cy="120" r="92" fill="none" stroke="rgba(224,152,57,0.18)" strokeWidth="22" />
          <circle
            cx="120" cy="120" r="92" fill="none"
            stroke="#E09839" strokeWidth="22" strokeLinecap="round"
            strokeDasharray="578" strokeDashoffset="578"
            transform="rotate(-90 120 120)"
            style={{ animation: "drawArc 1.6s 0.2s forwards cubic-bezier(0.2, 0.9, 0.2, 1)" }}
          />
          {/* hands */}
          <g style={{ transformOrigin: "120px 120px", animation: "spinHand 4s linear infinite" }}>
            <line x1="120" y1="120" x2="120" y2="55" stroke="#FBFAF7" strokeWidth="3" strokeLinecap="round"/>
          </g>
          <g style={{ transformOrigin: "120px 120px", animation: "spinHand 0.6s linear infinite" }}>
            <line x1="120" y1="120" x2="120" y2="40" stroke="#E09839" strokeWidth="2" strokeLinecap="round"/>
          </g>
          <circle cx="120" cy="120" r="4" fill="#FBFAF7"/>
        </svg>
        <div className="kitchen-saved">
          <span className="num">−90</span>
          <span className="lbl mono">min / night</span>
        </div>
      </div>

      {/* Floating chits */}
      <div className="kitchen-chit chit-1">
        <span className="chit-head mono">SUPPLIER · ORDER</span>
        <span className="chit-row"><span>Wagyu beef ×2.4kg</span><b>auto</b></span>
        <span className="chit-row"><span>Basil 8 bunches</span><b>auto</b></span>
        <span className="chit-row"><span>Stone fruit ×box</span><b>auto</b></span>
        <span className="chit-stamp">SENT 21:04</span>
      </div>

      <div className="kitchen-chit chit-2">
        <span className="chit-head mono">PREP LIST · TUE</span>
        <span className="chit-row"><span>Stocks</span><b>✓</b></span>
        <span className="chit-row"><span>Sauces</span><b>✓</b></span>
        <span className="chit-row"><span>Pasta</span><b>✓</b></span>
      </div>

      <div className="kitchen-chit chit-3">
        <span className="chit-head mono">XERO · INVOICE</span>
        <span className="chit-row"><span>Acme Meats</span><b>$684.20</b></span>
        <span className="chit-row"><span>Reconciled</span><b>✓</b></span>
      </div>
    </div>
  );
}

/* --- 02 ACCOUNTANT: an animated knowledge-base graph + chat ping --- */
function AccountantScene() {
  // Graph nodes
  const nodes = [
    { id: "ato", x: 50, y: 25, r: 8, label: "ATO updates" },
    { id: "tpl", x: 22, y: 50, r: 7, label: "Templates" },
    { id: "soP", x: 80, y: 52, r: 7, label: "SOPs" },
    { id: "cli", x: 35, y: 78, r: 6, label: "Client docs" },
    { id: "tax", x: 70, y: 80, r: 6, label: "Tax precedent" },
  ];
  const center = { x: 50, y: 50 };

  return (
    <div className="scene scene-accountant">
      <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" className="acc-graph">
        <defs>
          <radialGradient id="accCenter">
            <stop offset="0%" stopColor="#E09839" stopOpacity="1"/>
            <stop offset="100%" stopColor="#E09839" stopOpacity="0"/>
          </radialGradient>
        </defs>
        {/* edges */}
        {nodes.map((n, i) => (
          <line
            key={i}
            x1={center.x} y1={center.y}
            x2={n.x} y2={n.y}
            stroke="rgba(255,255,255,0.18)"
            strokeWidth="0.4"
            strokeDasharray="0.8 1.4"
            style={{ animation: `dashFlow 3s linear infinite`, animationDelay: `${i * 0.2}s` }}
          />
        ))}
        {/* glow ring */}
        <circle cx={center.x} cy={center.y} r="10" fill="url(#accCenter)" opacity="0.5"/>
        {/* center */}
        <circle cx={center.x} cy={center.y} r="5" fill="#E09839">
          <animate attributeName="r" values="5;6;5" dur="2.4s" repeatCount="indefinite"/>
        </circle>
        <text x={center.x} y={center.y + 1.8} textAnchor="middle" fill="#fff" fontSize="3" fontFamily="JetBrains Mono" fontWeight="600">AI</text>
        {/* nodes */}
        {nodes.map((n, i) => (
          <g key={n.id}>
            <circle cx={n.x} cy={n.y} r={n.r * 0.7} fill="rgba(0,87,123,0.4)" stroke="#00577B" strokeWidth="0.3"/>
            <circle cx={n.x} cy={n.y} r={n.r * 0.45} fill="#FBFAF7"/>
            <text x={n.x} y={n.y + n.r + 3} textAnchor="middle" fill="rgba(255,255,255,0.7)" fontSize="2.4" fontFamily="JetBrains Mono">{n.label}</text>
          </g>
        ))}
        {/* travelling pulses on each edge */}
        {nodes.map((n, i) => (
          <circle key={"p"+i} r="0.8" fill="#E09839">
            <animateMotion dur="2.4s" repeatCount="indefinite" begin={`${i * 0.3}s`}
              path={`M ${n.x} ${n.y} L ${center.x} ${center.y}`} />
          </circle>
        ))}
      </svg>

      {/* Chat overlay */}
      <div className="acc-chat">
        <div className="acc-chat-msg incoming">
          <span className="acc-avatar">JM</span>
          <div className="acc-bubble">
            How do I treat a director's loan in the new FY?
            <span className="acc-time mono">9:14</span>
          </div>
        </div>
        <div className="acc-chat-msg outgoing">
          <div className="acc-bubble bot">
            <span className="acc-bot-row">
              <span className="acc-bot-dot" />
              <span className="acc-bot-dot" />
              <span className="acc-bot-dot" />
            </span>
            Per ATO TR 2024/3 — treat as Div 7A unless repaid before lodgement.
            See template <u>DIV-7A-letter.docx</u>.
            <span className="acc-time mono">9:14 · 0.8s</span>
          </div>
          <span className="acc-avatar bot-av">b38</span>
        </div>
      </div>
    </div>
  );
}

/* --- 03 BARBER: animated phone with bookings flowing in + booking heatmap --- */
function BarberScene() {
  const messages = [
    { who: "Jess M.", txt: "Can I do 4pm Thurs?", time: "10:02", reply: "Booked ✓" },
    { who: "Tariq", txt: "fade + beard trim?", time: "10:07", reply: "Sat 11am works" },
    { who: "Liam D.", txt: "running 10 late", time: "10:14", reply: "no worries" },
  ];

  return (
    <div className="scene scene-barber">
      <div className="barber-phone">
        <div className="barber-notch" />
        <div className="barber-screen">
          <div className="barber-app-head">
            <span className="dot dot-g" />
            <span className="mono">DM Autopilot</span>
            <span className="mono live">LIVE</span>
          </div>
          {messages.map((m, i) => (
            <React.Fragment key={i}>
              <div className="msg in" style={{ animationDelay: `${i * 1.4}s` }}>
                <span className="msg-who mono">{m.who} · {m.time}</span>
                <span className="msg-bub">{m.txt}</span>
              </div>
              <div className="msg out" style={{ animationDelay: `${i * 1.4 + 0.6}s` }}>
                <span className="msg-bub bot">{m.reply}</span>
              </div>
            </React.Fragment>
          ))}
          <div className="barber-typing" style={{ animationDelay: `${messages.length * 1.4}s` }}>
            <span/><span/><span/>
          </div>
        </div>
      </div>

      <div className="barber-heatmap">
        <div className="bh-title mono">BOOKINGS · LAST 14 DAYS</div>
        <div className="bh-grid">
          {Array.from({length: 7 * 14}).map((_, i) => {
            const intensity = Math.random();
            return <span key={i} className="bh-cell" style={{ "--o": Math.min(1, 0.15 + intensity * 0.95), animationDelay: `${i * 12}ms` }} />;
          })}
        </div>
        <div className="bh-legend mono">
          <span>less</span>
          <span className="bh-cell sm" style={{"--o": 0.2}}/>
          <span className="bh-cell sm" style={{"--o": 0.45}}/>
          <span className="bh-cell sm" style={{"--o": 0.7}}/>
          <span className="bh-cell sm" style={{"--o": 1}}/>
          <span>more</span>
        </div>
      </div>

      <div className="barber-stat">
        <span className="bs-num">+28%</span>
        <span className="bs-lbl mono">bookings</span>
        <span className="bs-spark">
          <svg viewBox="0 0 80 24"><polyline fill="none" stroke="#E09839" strokeWidth="2" points="0,20 12,16 24,17 36,12 48,13 60,7 72,4 80,2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
      </div>
    </div>
  );
}

/* --- 04 LEGAL: contract page with risk-flag annotations animating in --- */
function LegalScene() {
  const flags = [
    { top: 24, kind: "high", note: "Indemnity is uncapped — recommend mutual cap @ 1× fees", delay: 0.6 },
    { top: 48, kind: "med", note: "IP assignment lacks moral-rights waiver", delay: 1.4 },
    { top: 72, kind: "low", note: "Notice period inconsistent with §11.3", delay: 2.2 },
  ];

  return (
    <div className="scene scene-legal">
      <div className="legal-doc">
        <div className="legal-doc-head">
          <span className="mono">CONTRACT · MSA-2026-0428.pdf</span>
          <span className="mono">8 pages</span>
        </div>
        <div className="legal-doc-body">
          {Array.from({length: 16}).map((_, i) => (
            <div key={i} className="legal-line" style={{ width: `${60 + Math.random() * 35}%`, opacity: 0.18 + Math.random() * 0.4 }}/>
          ))}
          {/* highlight bands behind certain lines */}
          <div className="legal-highlight high" style={{ top: "22%" }}/>
          <div className="legal-highlight med" style={{ top: "46%" }}/>
          <div className="legal-highlight low" style={{ top: "70%" }}/>
        </div>
      </div>

      {/* Floating risk flags */}
      {flags.map((f, i) => (
        <div key={i} className={`legal-flag ${f.kind}`} style={{ top: `${f.top}%`, animationDelay: `${f.delay}s` }}>
          <span className={`legal-pip ${f.kind}`}/>
          <div className="legal-flag-body">
            <span className="legal-flag-tag mono">
              {f.kind === "high" ? "RISK · HIGH" : f.kind === "med" ? "RISK · MED" : "INCONSISTENCY"}
            </span>
            <span className="legal-flag-text">{f.note}</span>
          </div>
        </div>
      ))}

      {/* Bottom verdict bar */}
      <div className="legal-verdict">
        <div className="legal-verdict-row">
          <span className="mono">FIRST-PASS REVIEW</span>
          <span className="legal-time mono">4.2s</span>
        </div>
        <div className="legal-verdict-row">
          <span className="legal-pill">3 flags</span>
          <span className="legal-pill amber">2 redlines drafted</span>
          <span className="legal-pill green">ready for partner</span>
        </div>
      </div>
    </div>
  );
}

window.UseCases = UseCases;
