// 14-day Gantt timeline — clickable days with phase color bands.

const DAYS = [
  { d: 1,  w: 1, ph: "Kick-off", t: "Monday call",        body: "90 minutes. Brand, audience, page list, no-go list. You leave with the schedule and the Slack." },
  { d: 2,  w: 1, ph: "Kick-off", t: "Voice + content map",body: "We draft your homepage in your voice. Sentence patterns, triplet headlines, what the buttons say." },
  { d: 3,  w: 1, ph: "Design",   t: "Moodboard + tokens", body: "Colors, type, motion. One screenshot deck. You pick a direction by 5pm." },
  { d: 4,  w: 1, ph: "Design",   t: "Home + key page",    body: "Hi-fi homepage and your most critical product / services page, in Figma." },
  { d: 5,  w: 1, ph: "Design",   t: "System rollout",     body: "Every other page templated off the home. Friday review call." },
  { d: 6,  w: 1, ph: "Build",    t: "Component build",    body: "Saturday — components built in Framer / Next.js. You won't see us; you'll see the staging URL Monday." },
  { d: 7,  w: 1, ph: "Build",    t: "Page assembly",      body: "Pages assembled. Real copy in place. First click-through on Sunday night." },
  { d: 8,  w: 2, ph: "Build",    t: "Forms + CMS",        body: "Blog CMS loaded. Every form points at a real automation. Internal tools wired up." },
  { d: 9,  w: 2, ph: "Automate", t: "Workflows",          body: "Forms → CRM → Slack. Booking + reminder flows. Receipt + thank-you sequences. All tested with live data." },
  { d: 10, w: 2, ph: "Automate", t: "Analytics + UTMs",   body: "GA4 / Plausible / PostHog installed. UTMs mapped to every channel. Dashboard built." },
  { d: 11, w: 2, ph: "Polish",   t: "QA pass + perf",     body: "Lighthouse 95+, axe-clean, every link checked, every state designed. We delete the rough edges." },
  { d: 12, w: 2, ph: "Polish",   t: "Social hand-off",    body: "Profile design lands. Launch content kit drops in your Drive. VA on-boarded if you're using that." },
  { d: 13, w: 2, ph: "Launch",   t: "Dress rehearsal",    body: "Full walkthrough on staging. Sign-off form. We freeze." },
  { d: 14, w: 2, ph: "Launch",   t: "Live",               body: "DNS swap before lunch. Loom walkthrough by 5pm. You're shipping by Friday evening." },
];

const PHASE_COLORS = {
  "Kick-off": "#A78BFA",
  "Design":   "#8A5CFF",
  "Build":    "#6C3BFF",
  "Automate": "#5A2EE6",
  "Polish":   "#A78BFA",
  "Launch":   "var(--accent-faint)",
};

function ProcessSection() {
  const isMobile = useIsMobile();
  const [activeDay, setActiveDay] = React.useState(1);
  const [playing, setPlaying] = React.useState(false);
  const tRef = React.useRef(null);

  React.useEffect(() => {
    if (!playing) return;
    tRef.current = setInterval(() => {
      setActiveDay((d) => (d >= 14 ? (setPlaying(false), 14) : d + 1));
    }, 900);
    return () => clearInterval(tRef.current);
  }, [playing]);

  const cur = DAYS[activeDay - 1];
  const phaseColor = PHASE_COLORS[cur.ph];

  return (
    <section id="process" data-screen-label="03 14-day process" className="shefa-pad" style={{
      padding: isMobile ? "80px 20px" : "120px 32px", background: "var(--page)",
      borderTop: "1px solid var(--line)", position: "relative", overflow: "hidden",
    }}>
      <div style={{
        position: "absolute", inset: "auto 0 0 0", height: "60%",
        background: "radial-gradient(60% 80% at 50% 100%, rgba(108,59,255,0.10), transparent 70%)",
        pointerEvents: "none",
      }}></div>

      <div style={{ maxWidth: 1280, margin: "0 auto", position: "relative" }}>
        <Reveal>
          <div style={{ marginBottom: isMobile ? 32 : 56, display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 24, flexWrap: "wrap" }}>
            <div style={{ maxWidth: 720 }}>
              <Eyebrow>The 14 days</Eyebrow>
              <h2 style={{
                fontFamily: "var(--font-display)", fontSize: isMobile ? 36 : 52, lineHeight: 1.05, color: "var(--text-strong)",
                letterSpacing: "-0.025em", fontWeight: 700, margin: 0, marginBottom: 14,
              }}>
                Two weeks. <span style={{ color: "var(--text-muted)" }}>One launch.</span>
              </h2>
              <p style={{ fontSize: isMobile ? 15 : 17, color: "var(--text-muted)", lineHeight: 1.6, margin: 0 }}>
                Every day is on the schedule before we start. Hover any day to see what we're doing — or hit play to watch the two weeks unfold.
              </p>
            </div>
            <button onClick={() => { if (activeDay >= 14) setActiveDay(1); setPlaying((p) => !p); }} style={{
              background: playing ? "rgba(138,92,255,0.18)" : "rgba(108,59,255,0.10)",
              border: "1px solid rgba(138,92,255,0.4)",
              color: "var(--accent-faint)", cursor: "pointer",
              padding: "10px 18px", borderRadius: 999, fontFamily: "inherit",
              fontWeight: 600, fontSize: 13, display: "inline-flex", alignItems: "center", gap: 10,
              transition: "all 200ms",
            }}>
              <span style={{ width: 8, height: 8, borderRadius: 99, background: playing ? "#FF8B8E" : "#8A5CFF", boxShadow: playing ? "0 0 10px rgba(255,139,142,0.7)" : "0 0 10px rgba(138,92,255,0.7)" }}></span>
              {playing ? "Pause sequence" : (activeDay >= 14 ? "Replay sequence" : "Play sequence")}
            </button>
          </div>
        </Reveal>

        <Reveal delay={120}>
          <div style={{
            background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 20,
            padding: isMobile ? 16 : 28, marginBottom: 28,
          }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 14 }}>
              {[1, 2].map((w) => (
                <div key={w} style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", padding: "0 4px" }}>
                  <span className="accent-color" style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "#A78BFA", fontWeight: 700 }}>
                    Week {w}
                  </span>
                  <span style={{ fontSize: 11, color: "var(--text-faint)", fontFamily: "var(--font-mono)" }}>
                    {w === 1 ? "Mon — Sun" : "Mon — Fri"}
                  </span>
                </div>
              ))}
            </div>

            <div style={{ overflowX: isMobile ? "auto" : "visible", marginLeft: isMobile ? -16 : 0, marginRight: isMobile ? -16 : 0, paddingLeft: isMobile ? 16 : 0, paddingRight: isMobile ? 16 : 0, paddingBottom: isMobile ? 8 : 0 }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(14, 1fr)", gap: 6, minWidth: isMobile ? 700 : "auto" }}>
              {DAYS.map((d) => {
                const isActive = d.d === activeDay;
                const color = PHASE_COLORS[d.ph];
                return (
                  <button key={d.d}
                    onClick={() => { setPlaying(false); setActiveDay(d.d); }}
                    onMouseEnter={() => { if (!playing) setActiveDay(d.d); }}
                    style={{
                      background: isActive
                        ? `linear-gradient(180deg, ${color} 0%, ${color}aa 100%)`
                        : `${color}26`,
                      border: isActive ? `1px solid ${color}` : `1px solid ${color}44`,
                      borderRadius: 10,
                      padding: "14px 8px",
                      cursor: "pointer",
                      color: isActive ? "var(--on-accent)" : "var(--accent-faint)",
                      fontFamily: "var(--font-display)",
                      transition: "all 200ms var(--ease-std)",
                      transform: isActive ? "translateY(-3px)" : "translateY(0)",
                      boxShadow: isActive ? `0 0 24px ${color}66` : "none",
                      display: "flex", flexDirection: "column", alignItems: "center", gap: 4,
                    }}>
                    <span style={{ fontSize: 10, opacity: 0.7, letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 600 }}>Day</span>
                    <span style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{d.d}</span>
                  </button>
                );
              })}
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(14, 1fr)", gap: 6, marginTop: 8, minWidth: isMobile ? 700 : "auto" }}>
              {DAYS.map((d) => (
                <div key={d.d} style={{ height: 4, borderRadius: 999, background: PHASE_COLORS[d.ph], opacity: 0.45 }}></div>
              ))}
            </div>
            </div>{/* end scroll wrapper */}

            <div style={{
              marginTop: 28, padding: "24px 26px",
              background: "linear-gradient(180deg, rgba(108,59,255,0.10), rgba(108,59,255,0))",
              border: "1px solid rgba(138,92,255,0.28)", borderRadius: 14,
              display: "grid", gridTemplateColumns: isMobile ? "1fr" : "110px 1fr auto", gap: isMobile ? 14 : 28, alignItems: "center",
            }}>
              <div>
                <div className="accent-color" style={{ fontSize: 10, color: "#A78BFA", letterSpacing: "0.18em", textTransform: "uppercase", fontWeight: 700, marginBottom: 6 }}>
                  Day {cur.d}
                </div>
                <div style={{
                  display: "inline-block",
                  padding: "4px 10px", borderRadius: 999,
                  background: `${phaseColor}33`,
                  border: `1px solid ${phaseColor}66`,
                  color: phaseColor,
                  fontSize: 10, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase",
                }}>
                  {cur.ph}
                </div>
              </div>
              <div>
                <h3 style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700, color: "var(--text-strong)", margin: 0, marginBottom: 6, letterSpacing: "-0.01em" }}>
                  {cur.t}
                </h3>
                <p style={{ fontSize: 14, lineHeight: 1.55, color: "var(--accent-faint)", margin: 0, textWrap: "pretty" }}>
                  {cur.body}
                </p>
              </div>
              <div style={{ display: "flex", gap: 6 }}>
                <button onClick={() => { setPlaying(false); setActiveDay(Math.max(1, activeDay - 1)); }} style={navBtn}>‹</button>
                <button onClick={() => { setPlaying(false); setActiveDay(Math.min(14, activeDay + 1)); }} style={navBtn}>›</button>
              </div>
            </div>
          </div>
        </Reveal>

        <Reveal delay={180}>
          <div style={{ display: "flex", gap: 24, flexWrap: "wrap", justifyContent: "center" }}>
            {Object.keys(PHASE_COLORS).map((p) => (
              <div key={p} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 10, height: 10, borderRadius: 99, background: PHASE_COLORS[p] }}></span>
                <span style={{ fontSize: 12, color: "var(--text-muted)", letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 600 }}>
                  {p}
                </span>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

const navBtn = {
  width: 36, height: 36, borderRadius: 10,
  background: "rgba(108,59,255,0.10)",
  border: "1px solid var(--line)",
  color: "var(--accent-faint)",
  fontSize: 18, cursor: "pointer", fontFamily: "inherit",
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  transition: "all 160ms",
};

Object.assign(window, { ProcessSection });

// Automation graph — click a trigger, watch a packet traverse the workflow,
// see realistic events appear in the event log on the right.

// Node layout in an 880×420 viewBox
const A_NODES = {
  trigger:  { x: 70,  y: 210, w: 150, h: 64, label: "Trigger",  sub: "(choose →)",        kind: "trigger" },
  validate: { x: 290, y: 130, w: 140, h: 58, label: "Validate", sub: "schema + dupe",     kind: "step" },
  enrich:   { x: 290, y: 290, w: 140, h: 58, label: "Enrich",   sub: "Clearbit + UTM",    kind: "step" },
  crm:      { x: 520, y: 70,  w: 168, h: 54, label: "HubSpot",  sub: "CRM record",        kind: "out", icon: "▦" },
  slack:    { x: 520, y: 165, w: 168, h: 54, label: "Slack",    sub: "#leads channel",    kind: "out", icon: "#" },
  email:    { x: 520, y: 260, w: 168, h: 54, label: "Resend",   sub: "Auto-responder",    kind: "out", icon: "✉" },
  sheet:    { x: 520, y: 355, w: 168, h: 54, label: "Sheets",   sub: "Pipeline log",      kind: "out", icon: "▤" },
};

const A_EDGES = [
  { from: "trigger",  to: "validate" },
  { from: "trigger",  to: "enrich"   },
  { from: "validate", to: "crm"      },
  { from: "validate", to: "slack"    },
  { from: "enrich",   to: "email"    },
  { from: "enrich",   to: "sheet"    },
];

// Realistic sample data per trigger
const TRIGGERS = [
  {
    key: "form",
    label: "Form submit",
    sub: "Contact form on /pricing",
    sample: () => ({
      who: pick(["Maya Okafor", "Daniel Reyes", "Priya Shah", "Jordan Vega", "Sofia Greene", "Adam Mott"]),
      brand: pick(["Northwind", "Lumen Coffee", "Axis Health", "Forma", "Kindred", "Pace"]),
      page: "/pricing",
      utm: pick(["organic / google", "li / launch-post", "newsletter / 24", "referral / mott"]),
      value: null,
    }),
    events: (d) => [
      { who: "Form", msg: `${d.who} (${d.brand}) submitted contact form`, kind: "trigger" },
      { who: "Validate", msg: "Email format ✓ · No duplicate in last 30 days", kind: "ok" },
      { who: "Enrich", msg: `Clearbit: ${d.brand} · 12 employees · NYC`, kind: "info" },
      { who: "HubSpot", msg: `Deal created · stage: "Discovery call" · $14,000`, kind: "ok" },
      { who: "Slack", msg: `Posted to #leads · "New lead from ${d.brand}"`, kind: "ok" },
      { who: "Resend", msg: `Sent "Thanks — we'll be in touch" to ${d.who.split(" ")[0].toLowerCase()}@${d.brand.toLowerCase().replace(/\s/g,"")}.com`, kind: "ok" },
      { who: "Sheets", msg: `Row appended · utm: ${d.utm}`, kind: "ok" },
    ],
  },
  {
    key: "stripe",
    label: "Stripe charge",
    sub: "Care plan, $1,800 / month",
    sample: () => ({
      who: pick(["Northwind Studio", "Lumen Coffee", "Axis Health", "Forma Labs"]),
      brand: "",
      page: "Stripe webhook",
      utm: "",
      value: 1800,
    }),
    events: (d) => [
      { who: "Stripe", msg: `Invoice paid · $${d.value.toLocaleString()} from ${d.who}`, kind: "trigger" },
      { who: "Validate", msg: "Customer matched · subscription active", kind: "ok" },
      { who: "Enrich", msg: "Care plan month-of-service tagged", kind: "info" },
      { who: "HubSpot", msg: `Deal moved to "Active care" · ARR updated`, kind: "ok" },
      { who: "Slack", msg: `Posted to #revenue · "💜 Care plan renewed: ${d.who}"`, kind: "ok" },
      { who: "Resend", msg: `Receipt PDF emailed to billing@${d.who.toLowerCase().split(" ")[0]}.com`, kind: "ok" },
      { who: "Sheets", msg: "MRR row updated · monthly cohort tagged", kind: "ok" },
    ],
  },
  {
    key: "booking",
    label: "Calendar booking",
    sub: "Kick-off call on Cal.com",
    sample: () => ({
      who: pick(["Priya Shah", "Sofia Greene", "Adam Mott", "Jordan Vega"]),
      brand: pick(["Axis Health", "Halcyon", "Kindred", "Pace"]),
      page: "/book",
      utm: pick(["organic / google", "post / case-study", "newsletter / 25"]),
      value: null,
    }),
    events: (d) => [
      { who: "Cal.com", msg: `${d.who} booked Monday kick-off · 90 min`, kind: "trigger" },
      { who: "Validate", msg: "Slot held · no team conflicts", kind: "ok" },
      { who: "Enrich", msg: `Brand: ${d.brand} · Notion brief draft seeded`, kind: "info" },
      { who: "HubSpot", msg: `Deal stage: "Scheduled kick-off"`, kind: "ok" },
      { who: "Slack", msg: `Posted to #kickoffs · "${d.brand} on the calendar Mon 10a"`, kind: "ok" },
      { who: "Resend", msg: `Confirmation + pre-call checklist sent to ${d.who.split(" ")[0].toLowerCase()}@${d.brand.toLowerCase().replace(/\s/g,"")}.com`, kind: "ok" },
      { who: "Sheets", msg: `Capacity sheet · week of Jun 22 incremented`, kind: "ok" },
    ],
  },
];

function pick(arr) { return arr[Math.floor(Math.random() * arr.length)]; }

function AutomationSection() {
  const isMobile = useIsMobile();
  const [triggerKey, setTriggerKey] = React.useState("form");
  const [run, setRun] = React.useState(0); // increments to start a new packet animation
  const [activeNodes, setActiveNodes] = React.useState(new Set());
  const [activeEdges, setActiveEdges] = React.useState(new Set());
  const [log, setLog] = React.useState([]); // newest first
  const [running, setRunning] = React.useState(false);

  // Compute edge path for any edge — straight line with rounded mid
  const edgePath = (from, to) => {
    const a = A_NODES[from], b = A_NODES[to];
    const x1 = a.x + a.w, y1 = a.y + a.h / 2;
    const x2 = b.x,       y2 = b.y + b.h / 2;
    const mx = (x1 + x2) / 2;
    return `M ${x1},${y1} C ${mx},${y1} ${mx},${y2} ${x2},${y2}`;
  };

  // Fire a run
  const fire = React.useCallback(() => {
    if (running) return;
    setRunning(true);
    setActiveNodes(new Set());
    setActiveEdges(new Set());

    const trig = TRIGGERS.find((t) => t.key === triggerKey);
    const data = trig.sample();
    const events = trig.events(data);

    // Sequence: trigger node lights → 2 parallel edges → validate + enrich light → 4 output edges → 4 outputs light.
    const ts = [];
    let t = 0;

    // step 1: trigger on
    ts.push(setTimeout(() => {
      setActiveNodes(new Set(["trigger"]));
      pushLog(events[0]);
    }, t));
    t += 600;

    // step 2: edges to validate + enrich
    ts.push(setTimeout(() => {
      setActiveEdges(new Set(["trigger->validate", "trigger->enrich"]));
    }, t));
    t += 700;

    // step 3: validate + enrich on
    ts.push(setTimeout(() => {
      setActiveNodes((s) => new Set([...s, "validate", "enrich"]));
      pushLog(events[1]);
    }, t));
    t += 350;
    ts.push(setTimeout(() => pushLog(events[2]), t));
    t += 500;

    // step 4: edges to outputs
    ts.push(setTimeout(() => {
      setActiveEdges((s) => new Set([...s, "validate->crm", "validate->slack", "enrich->email", "enrich->sheet"]));
    }, t));
    t += 700;

    // step 5: outputs on (sequenced)
    ["crm", "slack", "email", "sheet"].forEach((n, i) => {
      ts.push(setTimeout(() => {
        setActiveNodes((s) => new Set([...s, n]));
        pushLog(events[3 + i]);
      }, t + i * 180));
    });
    t += 720;

    // done
    ts.push(setTimeout(() => setRunning(false), t + 600));

    return () => ts.forEach(clearTimeout);
  }, [triggerKey, running]);

  function pushLog(ev) {
    setLog((l) => [{ ...ev, time: nowStamp(), id: Math.random() }, ...l].slice(0, 12));
  }

  // Autorun on first mount
  const rootRef = React.useRef(null);
  React.useEffect(() => {
    if (!rootRef.current) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && log.length === 0 && !running) {
          setTimeout(fire, 400);
        }
      });
    }, { threshold: 0.35 });
    obs.observe(rootRef.current);
    return () => obs.disconnect();
  }, [fire, log.length, running]);

  return (
    <section id="automation" data-screen-label="04 Automation graph" className="shefa-pad" style={{
      padding: isMobile ? "80px 20px" : "120px 32px", background: "var(--page)",
      borderTop: "1px solid var(--line)", position: "relative", overflow: "hidden",
    }}>
      {/* faint nodes bg */}
      <div style={{
        position: "absolute", inset: 0,
        background: "radial-gradient(60% 60% at 30% 50%, rgba(108,59,255,0.08), transparent 70%)",
        pointerEvents: "none",
      }}></div>

      <div ref={rootRef} style={{ maxWidth: 1280, margin: "0 auto", position: "relative" }}>
        <Reveal>
          <div style={{ marginBottom: isMobile ? 32 : 56, display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.3fr 1fr", gap: isMobile ? 16 : 32, alignItems: "flex-end" }}>
            <div>
              <Eyebrow>Automation layer</Eyebrow>
              <h2 style={{
                fontFamily: "var(--font-display)", fontSize: isMobile ? 32 : 52, lineHeight: 1.05, color: "var(--text-strong)",
                letterSpacing: "-0.025em", fontWeight: 700, margin: 0, maxWidth: 760,
              }}>
                Every form fires a system. <span style={{ color: "var(--text-muted)" }}>Not a follow-up.</span>
              </h2>
            </div>
            <p style={{ fontSize: 15, color: "var(--text-muted)", margin: 0, lineHeight: 1.6 }}>
              By day 12, every form, charge, and booking on your site routes through a workflow you can see, audit, and edit. This is a live example — pick a trigger and watch it run.
            </p>
          </div>
        </Reveal>

        <Reveal delay={120}>
          <div style={{
            background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 22,
            overflow: "hidden", display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.55fr 1fr", minHeight: isMobile ? "auto" : 540,
          }}>
            {/* LEFT: graph */}
            <div style={{ position: "relative", padding: 28, borderRight: "1px solid var(--line)", background: "linear-gradient(180deg, rgba(108,59,255,0.04), rgba(108,59,255,0))" }}>
              {/* Trigger picker */}
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: 18, flexWrap: "wrap" }}>
                <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                  {TRIGGERS.map((t) => {
                    const active = t.key === triggerKey;
                    return (
                      <button key={t.key} onClick={() => !running && setTriggerKey(t.key)} disabled={running}
                        style={{
                          background: active ? "linear-gradient(135deg,#6C3BFF,#8A5CFF)" : "rgba(108,59,255,0.10)",
                          border: active ? "1px solid transparent" : "1px solid rgba(138,92,255,0.32)",
                          color: active ? "var(--on-accent)" : "var(--accent-faint)",
                          padding: "9px 14px", borderRadius: 999,
                          fontFamily: "inherit", fontSize: 12.5, fontWeight: 600,
                          cursor: running ? "default" : "pointer", opacity: running && !active ? 0.5 : 1,
                          transition: "all 200ms",
                          letterSpacing: "0.02em",
                        }}>
                        {t.label}
                      </button>
                    );
                  })}
                </div>
                <button onClick={fire} disabled={running}
                  className="accent-grad" style={{
                    background: "linear-gradient(135deg,#6C3BFF,#8A5CFF)",
                    color: "var(--text-strong)", border: 0,
                    padding: "10px 18px", borderRadius: 999,
                    fontFamily: "inherit", fontWeight: 700, fontSize: 12.5,
                    cursor: running ? "default" : "pointer", opacity: running ? 0.6 : 1,
                    transition: "all 200ms",
                    display: "inline-flex", alignItems: "center", gap: 8,
                    letterSpacing: "0.05em", textTransform: "uppercase",
                  }}
                  onMouseEnter={(e) => { if (!running) e.currentTarget.style.boxShadow = "0 0 24px rgba(108,59,255,0.5)"; }}
                  onMouseLeave={(e) => e.currentTarget.style.boxShadow = "none"}>
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none" aria-hidden="true">
                    <polygon points="2,1 11,6 2,11" fill="#fff"/>
                  </svg>
                  {running ? "Running…" : "Fire test event"}
                </button>
              </div>

              {/* SVG graph */}
              <svg viewBox="0 0 760 460" width="100%" style={{ display: "block", maxHeight: 460 }}>
                <defs>
                  <linearGradient id="aedge" x1="0" y1="0" x2="1" y2="0">
                    <stop offset="0" stopColor="#6C3BFF" />
                    <stop offset="1" stopColor="#A78BFA" />
                  </linearGradient>
                  <filter id="aglow" x="-50%" y="-50%" width="200%" height="200%">
                    <feGaussianBlur stdDeviation="3" result="b"/>
                    <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
                  </filter>
                </defs>

                {/* edges */}
                {A_EDGES.map((e) => {
                  const id = `${e.from}->${e.to}`;
                  const active = activeEdges.has(id);
                  return (
                    <g key={id}>
                      <path d={edgePath(e.from, e.to)}
                        stroke={active ? "url(#aedge)" : "var(--line)"}
                        strokeWidth={active ? 2 : 1.5}
                        fill="none"
                        strokeDasharray={active ? "none" : "3 4"}
                        style={{ transition: "stroke 200ms" }}
                      />
                      {active && (
                        <circle r="4" fill="#fff" filter="url(#aglow)">
                          <animateMotion dur="0.7s" fill="freeze" repeatCount="1">
                            <mpath href={`#path-${id}`} />
                          </animateMotion>
                        </circle>
                      )}
                      <path id={`path-${id}`} d={edgePath(e.from, e.to)} fill="none" stroke="none" />
                    </g>
                  );
                })}

                {/* nodes */}
                {Object.entries(A_NODES).map(([k, n]) => {
                  const active = activeNodes.has(k);
                  const trig = TRIGGERS.find((t) => t.key === triggerKey);
                  const isTriggerNode = n.kind === "trigger";
                  return (
                    <g key={k}>
                      {/* glow ring when active */}
                      {active && (
                        <rect x={n.x - 4} y={n.y - 4} width={n.w + 8} height={n.h + 8} rx={14}
                          fill="none" stroke="#8A5CFF" strokeOpacity="0.4" strokeWidth="2"
                          style={{ filter: "blur(2px)" }} />
                      )}
                      <rect x={n.x} y={n.y} width={n.w} height={n.h} rx={12}
                        fill={active ? "rgba(108,59,255,0.18)" : "var(--page)"}
                        stroke={active ? "#8A5CFF" : "var(--line)"}
                        strokeWidth={active ? 1.5 : 1}
                        style={{ transition: "all 240ms var(--ease-std)" }}
                      />
                      {/* corner node dot */}
                      <circle cx={n.x + 6} cy={n.y + 6} r="2.5" fill={active ? "#A78BFA" : "var(--line-strong)"} />
                      <circle cx={n.x + n.w - 6} cy={n.y + 6} r="2.5" fill={active ? "#A78BFA" : "var(--line-strong)"} />
                      <circle cx={n.x + 6} cy={n.y + n.h - 6} r="2.5" fill={active ? "#A78BFA" : "var(--line-strong)"} />
                      <circle cx={n.x + n.w - 6} cy={n.y + n.h - 6} r="2.5" fill={active ? "#A78BFA" : "var(--line-strong)"} />

                      {/* labels */}
                      <text x={n.x + 16} y={n.y + 24}
                        fontFamily="var(--font-display)" fontSize="14" fontWeight="700"
                        fill={active ? "#fff" : "var(--line)"} letterSpacing="-0.01em">
                        {isTriggerNode ? trig.label : n.label}
                      </text>
                      <text x={n.x + 16} y={n.y + 42}
                        fontFamily="var(--font-body)" fontSize="11"
                        fill={active ? "var(--accent-faint)" : "var(--text-faint)"}>
                        {isTriggerNode ? trig.sub : n.sub}
                      </text>

                      {/* small icon for outputs */}
                      {n.kind === "out" && (
                        <g>
                          <circle cx={n.x + n.w - 18} cy={n.y + n.h / 2} r="11"
                            fill={active ? "rgba(138,92,255,0.32)" : "rgba(255,255,255,0.04)"}
                            stroke={active ? "#A78BFA" : "var(--line-strong)"} />
                          <text x={n.x + n.w - 18} y={n.y + n.h / 2 + 4}
                            textAnchor="middle"
                            fontSize="11" fontFamily="var(--font-mono)"
                            fill={active ? "#fff" : "var(--text-muted)"}>
                            {n.icon}
                          </text>
                        </g>
                      )}
                    </g>
                  );
                })}
              </svg>

              {/* legend strip below */}
              <div style={{
                marginTop: 4, paddingTop: 16, borderTop: "1px solid var(--line)",
                display: "flex", gap: 22, fontSize: 11, color: "var(--text-faint)",
                letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 600,
                flexWrap: "wrap",
              }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 12, height: 1.5, background: "var(--line)" }}></span>
                  Idle path
                </span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <span className="accent-grad" style={{ width: 12, height: 1.5, background: "linear-gradient(90deg,#6C3BFF,#A78BFA)" }}></span>
                  Live execution
                </span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 8, marginLeft: "auto" }}>
                  <span style={{ width: 7, height: 7, borderRadius: 99, background: running ? "#A78BFA" : "var(--line-strong)",
                                 boxShadow: running ? "0 0 8px rgba(167,139,250,0.7)" : "none",
                                 animation: running ? "shefaPulseGlow 1.4s infinite" : "none" }}></span>
                  {running ? "Workflow executing" : "Ready"}
                </span>
              </div>
            </div>

            {/* RIGHT: event log */}
            <div style={{ padding: 28, display: "flex", flexDirection: "column" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                <div className="accent-color" style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "#A78BFA", fontWeight: 700 }}>
                  Event log
                </div>
                <div style={{ fontSize: 11, color: "var(--text-faint)", fontFamily: "var(--font-mono)" }}>
                  {log.length} events
                </div>
              </div>

              <div style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 8, maxHeight: 460, paddingRight: 4 }}>
                {log.length === 0 && (
                  <div style={{
                    border: "1px dashed var(--line)", borderRadius: 12, padding: 22,
                    color: "var(--text-faint)", fontSize: 13, lineHeight: 1.5,
                    textAlign: "center",
                  }}>
                    Pick a trigger and hit <b style={{ color: "#A78BFA" }}>Fire test event</b> to see the workflow execute.
                  </div>
                )}
                {log.map((ev) => (
                  <div key={ev.id} style={{
                    background: ev.kind === "trigger" ? "rgba(138,92,255,0.10)" : "var(--page)",
                    border: "1px solid " + (ev.kind === "trigger" ? "rgba(138,92,255,0.32)" : "var(--line)"),
                    borderRadius: 10,
                    padding: "10px 14px",
                    display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, alignItems: "center",
                    animation: "shefaFloatIn 320ms var(--ease-std)",
                  }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: 99,
                      background: ev.kind === "trigger" ? "#A78BFA" : (ev.kind === "info" ? "#6C3BFF" : "#5A2EE6"),
                      boxShadow: ev.kind === "trigger" ? "0 0 8px rgba(167,139,250,0.7)" : "none",
                    }}></span>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "#A78BFA", fontWeight: 700, marginBottom: 2 }}>
                        {ev.who}
                      </div>
                      <div style={{ fontSize: 12.5, color: "var(--text-muted)", lineHeight: 1.45, textWrap: "pretty", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {ev.msg}
                      </div>
                    </div>
                    <div style={{ fontSize: 10, color: "var(--text-faint)", fontFamily: "var(--font-mono)", whiteSpace: "nowrap" }}>
                      {ev.time}
                    </div>
                  </div>
                ))}
              </div>

              <div style={{
                marginTop: 18, paddingTop: 18, borderTop: "1px solid var(--line)",
                display: "flex", justifyContent: "space-between", alignItems: "center",
                fontSize: 11, color: "var(--text-faint)",
              }}>
                <span>Avg run · <b style={{ color: "var(--accent-faint)" }}>1.4s</b></span>
                <span>Success last 30d · <b style={{ color: "var(--accent-faint)" }}>99.7%</b></span>
                <span>Cost · <b style={{ color: "var(--accent-faint)" }}>$0.0009</b></span>
              </div>
            </div>
          </div>
        </Reveal>

        <style>{`
          @keyframes shefaFloatIn {
            from { opacity: 0; transform: translateY(-6px); }
            to   { opacity: 1; transform: translateY(0); }
          }
        `}</style>
      </div>
    </section>
  );
}

function nowStamp() {
  const d = new Date();
  const pad = (n) => String(n).padStart(2, "0");
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

Object.assign(window, { AutomationSection });
