/* ============================================================
 * Journeys & Campaigns Hero (artifact)
 * Concatenated from the Campaigns & Journeys zip and wrapped in an
 * IIFE so its many top-level identifiers (Icon, Panel, Sidebar,
 * Builder, Canvas, Hero, App, etc.) cannot collide with bindings on
 * the host journeys.html page.
 *
 * Adaptations:
 *   1. Brand fuchsia #ED4D86 -> #ED4D86 (plus rgba and gradient stops).
 *   2. Cormorant Garamond -> Instrument Serif so the headlines match
 *      the rest of the GuestMaker marketing typography.
 *   3. The ReactDOM.createRoot(...) mount at the bottom of app.jsx is
 *      removed; App is exposed as window.JourneysHero and rendered
 *      from heroOverride on journeys.html.
 * ============================================================ */

(function () {
  const { useState, useEffect, useRef, useMemo } = React;

  /* ===== data.js ===== */

  // Win back - 365 days after booking journey data

  const JOURNEY_DATA = {
    name: "Win back · 365 days after booking",
    status: "Active",
    hotel: "All Hotels",
    trigger: {
      id: "trig",
      type: "trigger",
      label: "Booking Created",
      sub: "Triggers when a new reservation is made",
      icon: "bolt",
      x: 540, y: 60,
    },
    nodes: [
      { id: "delay1", type: "delay", label: "Wait 365 days", sub: "After reservation_date", icon: "clock", x: 540, y: 220 },
      { id: "tag1",   type: "data",  label: "Add Tag · Win-back eligible", sub: "winback_365", icon: "tag", x: 540, y: 372 },
      { id: "split1", type: "split", label: "Booking Channel", sub: "OTA · Direct · Tour Operator", icon: "split", x: 540, y: 524, branches: ["OTA", "Direct", "Tour Op."] },

      // Branch A, OTA, WhatsApp first because OTA guests rarely have email
      { id: "wa1", type: "whatsapp", label: "WhatsApp · Win-back offer", sub: "Hi {{first_name}}, we miss you in {{hotel_city}} 💛", icon: "whatsapp", x: 180, y: 720 },
      { id: "wait1", type: "delay", label: "Wait 3 days", sub: "for guest reply", icon: "clock", x: 180, y: 880 },
      { id: "ai1", type: "ai", label: "AI Agent · Concierge", sub: "Handles reply, qualifies intent", icon: "sparkles", x: 180, y: 1032 },

      // Branch B, Direct, Email primary, WhatsApp follow-up
      { id: "em1", type: "email", label: "Email · Welcome back", sub: "Subject: A room is calling, {{first_name}}", icon: "mail", x: 540, y: 720 },
      { id: "ab1", type: "abtest", label: "A/B · Subject test", sub: "50% “Come back” · 50% “We saved your suite”", icon: "abtest", x: 540, y: 880 },
      { id: "wa2", type: "whatsapp", label: "WhatsApp · 7-day nudge", sub: "10% off direct booking · {{promo_code}}", icon: "whatsapp", x: 540, y: 1032 },

      // Branch C, Tour Operator, SMS short message
      { id: "sms1", type: "sms", label: "SMS · Loyalty invite", sub: "Join Sunset Rewards, earn on every stay", icon: "sms", x: 900, y: 720 },
      { id: "tag2", type: "data", label: "Update Contact", sub: "lifecycle_stage = win_back", icon: "user", x: 900, y: 880 },

      // Convergence
      { id: "wait2", type: "delay", label: "Wait 14 days", sub: "Conversion window", icon: "clock", x: 540, y: 1192 },
      { id: "cond1", type: "split", label: "Booked again?", sub: "If new booking exists", icon: "split", x: 540, y: 1340, branches: ["Yes", "No"] },
      { id: "end1", type: "end", label: "Journey complete", sub: "Tag · win_back_converted", icon: "check", x: 320, y: 1520 },
      { id: "end2", type: "end", label: "Move to dormant", sub: "Re-enter in 90 days", icon: "moon", x: 760, y: 1520 },
    ],
    edges: [
      ["trig",   "delay1"],
      ["delay1", "tag1"],
      ["tag1",   "split1"],
      ["split1", "wa1",  { branch: "OTA",       color: "#9333ea" }],
      ["split1", "em1",  { branch: "Direct",    color: "#ED4D86" }],
      ["split1", "sms1", { branch: "Tour Op.",  color: "#f59e0b" }],
      ["wa1",    "wait1"],
      ["wait1",  "ai1"],
      ["em1",    "ab1"],
      ["ab1",    "wa2"],
      ["sms1",   "tag2"],
      ["ai1",    "wait2"],
      ["wa2",    "wait2"],
      ["tag2",   "wait2"],
      ["wait2",  "cond1"],
      ["cond1",  "end1", { branch: "Yes", color: "#10b981" }],
      ["cond1",  "end2", { branch: "No",  color: "#94a3b8" }],
    ],
  };

  window.TRIGGERS = [
    {
      section: "Booking Events",
      items: [
        { id: "booking_created",   name: "Booking Created",   sub: "Triggers when a new reservation is made",     color: "blue",  icon: "calendarPlus" },
        { id: "booking_updated",   name: "Booking Updated",   sub: "Triggers when a reservation is modified",      color: "blue",  icon: "calendarCheck" },
        { id: "booking_cancelled", name: "Booking Cancelled", sub: "Triggers when a reservation is cancelled",     color: "red",   icon: "calendarX" },
        { id: "booking_noshow",    name: "Booking No-Show",   sub: "Triggers when a guest is marked as a no-show", color: "amber", icon: "bolt" },
      ],
    },
    {
      section: "Guest Events",
      items: [
        { id: "checkin",  name: "Guest Check-In",  sub: "Triggers when a guest checks into the hotel",    color: "green",  icon: "login" },
        { id: "checkout", name: "Guest Check-Out", sub: "Triggers when a guest checks out of the hotel",  color: "orange", icon: "logout" },
      ],
    },
    {
      section: "Messaging",
      items: [
        { id: "msg_received", name: "Message Received", sub: "Triggers when a guest sends a WhatsApp message", color: "pink", icon: "message" },
      ],
    },
    {
      section: "Segments & Tags",
      items: [
        { id: "seg_entered",    name: "Segment Entered",    sub: "Triggers when a contact enters a segment",                    color: "purple", icon: "users" },
        { id: "tag_added",      name: "Tag Added",          sub: "Triggers when a tag is added to a contact",                   color: "purple", icon: "tag" },
        { id: "subscribed",     name: "Contact Subscribed", sub: "Triggers when a contact subscribes (opt-in)",                 color: "green",  icon: "bell" },
        { id: "contact_created",name: "Contact Created",    sub: "Triggers when a new contact is added to the CRM",             color: "blue",   icon: "userPlus" },
        { id: "contact_updated",name: "Contact Updated",    sub: "Triggers when specific fields on a contact are changed",      color: "blue",   icon: "userEdit" },
        { id: "journey_done",   name: "Journey Completed",  sub: "Triggers when a contact completes another journey",           color: "purple", icon: "flag" },
      ],
    },
    {
      section: "Scheduled",
      items: [
        { id: "birthday",   name: "Birthday",          sub: "Triggers before or on a contact's birthday",            color: "pink",  icon: "cake" },
        { id: "anniv",      name: "Date Anniversary",  sub: "Triggers on the anniversary of a specific date field",  color: "pink",  icon: "heart" },
        { id: "dormant",    name: "Dormant Contact",   sub: "Triggers when a contact has been inactive",             color: "slate", icon: "moon" },
        { id: "scheduled",  name: "Scheduled",         sub: "Run on a recurring schedule for matching contacts",     color: "slate", icon: "repeat" },
      ],
    },
    {
      section: "Manual",
      items: [
        { id: "manual",     name: "Manual Trigger", sub: "Triggered manually by staff for selected contacts", color: "neutral", icon: "hand" },
      ],
    },
    {
      section: "Custom Events",
      items: [
        { id: "custom",     name: "Custom Event", sub: "Triggered by external API events", color: "neutral", icon: "code" },
      ],
    },
  ];

  /* ===== icons.jsx ===== */

  // Icon set, minimalist line icons matching the screenshots
  const Icon = ({ name, size = 16, stroke = 1.6, color = "currentColor" }) => {
    const s = { width: size, height: size, fill: "none", stroke: color, strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round", viewBox: "0 0 24 24" };
    switch (name) {
      case "bolt":         return <svg {...s}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z" /></svg>;
      case "clock":        return <svg {...s}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
      case "tag":          return <svg {...s}><path d="M20 12l-8 8-8-8V4h8z"/><circle cx="8" cy="8" r="1.2" fill={color}/></svg>;
      case "split":        return <svg {...s}><path d="M6 3v4a4 4 0 004 4h4a4 4 0 014 4v6"/><path d="M3 6l3-3 3 3"/><path d="M15 21l3 0 3-3"/></svg>;
      case "whatsapp":     return <svg {...s}><path d="M3 21l1.5-5A8 8 0 1112 20a8 8 0 01-3.5-.8L3 21z"/><path d="M9 10c0 3 2 5 5 5l1.5-1.5-2-1-1 .8c-1-.5-1.7-1.2-2.2-2.2l.8-1-1-2L9 10z"/></svg>;
      case "mail":         return <svg {...s}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>;
      case "sms":          return <svg {...s}><path d="M21 12a8 8 0 01-12 7l-5 1 1-5a8 8 0 1116-3z"/><path d="M8 11h.01M12 11h.01M16 11h.01"/></svg>;
      case "sparkles":     return <svg {...s}><path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.5 5.5l2.5 2.5M16 16l2.5 2.5M5.5 18.5L8 16M16 8l2.5-2.5"/></svg>;
      case "abtest":       return <svg {...s}><path d="M3 7l4-4 4 4"/><path d="M7 3v18"/><path d="M21 17l-4 4-4-4"/><path d="M17 21V3"/></svg>;
      case "user":         return <svg {...s}><circle cx="12" cy="8" r="4"/><path d="M4 21c0-4 4-7 8-7s8 3 8 7"/></svg>;
      case "check":        return <svg {...s}><circle cx="12" cy="12" r="9"/><path d="M8 12l3 3 5-6"/></svg>;
      case "moon":         return <svg {...s}><path d="M21 13A9 9 0 1111 3a7 7 0 0010 10z"/></svg>;
      case "calendarPlus": return <svg {...s}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4M12 14v4M10 16h4"/></svg>;
      case "calendarCheck":return <svg {...s}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4M9 15l2 2 4-4"/></svg>;
      case "calendarX":    return <svg {...s}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4M16 3v4M10 14l4 4M14 14l-4 4"/></svg>;
      case "login":        return <svg {...s}><path d="M15 3h4a2 2 0 012 2v14a2 2 0 01-2 2h-4"/><path d="M10 17l5-5-5-5M3 12h12"/></svg>;
      case "logout":       return <svg {...s}><path d="M9 3H5a2 2 0 00-2 2v14a2 2 0 002 2h4"/><path d="M14 17l5-5-5-5M9 12h10"/></svg>;
      case "message":      return <svg {...s}><path d="M21 12a8 8 0 01-12 7l-5 1 1-5a8 8 0 1116-3z"/></svg>;
      case "users":        return <svg {...s}><circle cx="9" cy="8" r="3.5"/><path d="M2 21c0-3 3-5 7-5s7 2 7 5"/><circle cx="17" cy="6" r="3"/><path d="M14 14c4 0 8 1.5 8 5"/></svg>;
      case "bell":         return <svg {...s}><path d="M6 8a6 6 0 1112 0c0 7 3 8 3 8H3s3-1 3-8z"/><path d="M10 21a2 2 0 004 0"/></svg>;
      case "userPlus":     return <svg {...s}><circle cx="9" cy="8" r="4"/><path d="M2 21c0-4 4-7 7-7s7 3 7 7"/><path d="M19 8v6M22 11h-6"/></svg>;
      case "userEdit":     return <svg {...s}><circle cx="9" cy="8" r="4"/><path d="M2 21c0-4 4-7 7-7"/><path d="M14 19l4-4 3 3-4 4h-3z"/></svg>;
      case "flag":         return <svg {...s}><path d="M5 21V4M5 4h12l-2 4 2 4H5"/></svg>;
      case "cake":         return <svg {...s}><path d="M3 15a3 3 0 003 3h12a3 3 0 003-3v-3H3z"/><path d="M3 12c2 0 2-2 4-2s2 2 4 2 2-2 4-2 2 2 4 2"/><path d="M12 8V4M12 4l-1-1M12 4l1-1"/></svg>;
      case "heart":        return <svg {...s}><path d="M12 21s-7-4.5-9-9a5 5 0 019-3 5 5 0 019 3c-2 4.5-9 9-9 9z"/></svg>;
      case "repeat":       return <svg {...s}><path d="M17 2l4 4-4 4"/><path d="M3 10V8a4 4 0 014-4h14"/><path d="M7 22l-4-4 4-4"/><path d="M21 14v2a4 4 0 01-4 4H3"/></svg>;
      case "hand":         return <svg {...s}><path d="M9 11V5a1.5 1.5 0 013 0v6"/><path d="M12 11V4a1.5 1.5 0 013 0v7"/><path d="M15 11V6a1.5 1.5 0 013 0v9a6 6 0 01-12 0v-1l-2-3a1.5 1.5 0 012-2l2 2"/></svg>;
      case "code":         return <svg {...s}><path d="M16 18l6-6-6-6M8 6l-6 6 6 6"/></svg>;
      case "play":         return <svg {...s}><path d="M6 4l14 8-14 8z" fill={color}/></svg>;
      case "pause":        return <svg {...s}><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>;
      case "save":         return <svg {...s}><path d="M5 4h11l3 3v13a1 1 0 01-1 1H5a1 1 0 01-1-1V5a1 1 0 011-1z"/><path d="M7 4v5h8V4M7 20v-7h10v7"/></svg>;
      case "settings":     return <svg {...s}><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3H9a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8V9a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z"/></svg>;
      case "chev":         return <svg {...s}><path d="M9 6l6 6-6 6"/></svg>;
      case "chevDown":     return <svg {...s}><path d="M6 9l6 6 6-6"/></svg>;
      case "x":            return <svg {...s}><path d="M6 6l12 12M18 6L6 18"/></svg>;
      case "plus":         return <svg {...s}><path d="M12 5v14M5 12h14"/></svg>;
      case "minus":        return <svg {...s}><path d="M5 12h14"/></svg>;
      case "back":         return <svg {...s}><path d="M19 12H5M12 19l-7-7 7-7"/></svg>;
      case "search":       return <svg {...s}><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></svg>;
      case "trash":        return <svg {...s}><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M6 6l1 14a2 2 0 002 2h6a2 2 0 002-2l1-14"/></svg>;
      case "expand":       return <svg {...s}><path d="M9 3H3v6M21 9V3h-6M3 15v6h6M15 21h6v-6"/></svg>;
      case "edit":         return <svg {...s}><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>;
      case "copy":         return <svg {...s}><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>;
      case "eye":          return <svg {...s}><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/></svg>;
      case "stack":        return <svg {...s}><path d="M12 3l9 5-9 5-9-5z"/><path d="M3 13l9 5 9-5M3 18l9 5 9-5"/></svg>;
      case "home":         return <svg {...s}><path d="M3 11l9-7 9 7v9a1 1 0 01-1 1h-5v-7H9v7H4a1 1 0 01-1-1z"/></svg>;
      case "data":         return <svg {...s}><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v6c0 1.7 4 3 9 3s9-1.3 9-3V5M3 11v6c0 1.7 4 3 9 3s9-1.3 9-3v-6"/></svg>;
      case "inbox":        return <svg {...s}><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.5 5h13l3.5 7v6a2 2 0 01-2 2H4a2 2 0 01-2-2v-6z"/></svg>;
      case "broadcast":    return <svg {...s}><circle cx="12" cy="12" r="2"/><path d="M16.2 7.8a6 6 0 010 8.4M7.8 16.2a6 6 0 010-8.4"/><path d="M19 5a10 10 0 010 14M5 19A10 10 0 015 5"/></svg>;
      case "doc":          return <svg {...s}><path d="M14 3H6a2 2 0 00-2 2v14a2 2 0 002 2h12a2 2 0 002-2V9z"/><path d="M14 3v6h6"/></svg>;
      case "journey":      return <svg {...s}><circle cx="6" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="M8 7c4 0 4 5 0 5s-4 5 0 5"/></svg>;
      case "agent":        return <svg {...s}><path d="M12 2l1.5 4 4 1.5-4 1.5L12 13l-1.5-4-4-1.5 4-1.5z"/><path d="M19 14l1 2 2 1-2 1-1 2-1-2-2-1 2-1zM5 14l1 2 2 1-2 1-1 2-1-2-2-1 2-1z"/></svg>;
      case "award":        return <svg {...s}><circle cx="12" cy="9" r="6"/><path d="M9 14l-2 7 5-3 5 3-2-7"/></svg>;
      case "cdp":          return <svg {...s}><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>;
      case "bookmark":     return <svg {...s}><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg>;
      case "filter":       return <svg {...s}><path d="M3 4h18l-7 9v6l-4 2v-8z"/></svg>;
      case "panelLeft":    return <svg {...s}><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/></svg>;
      case "paperclip":    return <svg {...s}><path d="M21 11l-9 9a5 5 0 01-7-7l9-9a3.5 3.5 0 015 5l-8 8a2 2 0 01-3-3l7-7"/></svg>;
      case "image":        return <svg {...s}><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="1.6" fill={color}/><path d="M21 16l-5-5-9 9"/></svg>;
      case "building":     return <svg {...s}><rect x="4" y="3" width="16" height="18" rx="1.5"/><path d="M9 8h.01M15 8h.01M9 12h.01M15 12h.01M9 16h.01M15 16h.01M10 21v-3h4v3"/></svg>;
      case "palette":      return <svg {...s}><path d="M12 3a9 9 0 100 18c1 0 1.5-.5 1.5-1.5S13 18 13 17s.5-1.5 1.5-1.5H17a4 4 0 004-4 8 8 0 00-9-8.5z"/><circle cx="7.5" cy="11" r="1" fill={color}/><circle cx="9.5" cy="6.5" r="1" fill={color}/><circle cx="15" cy="6.5" r="1" fill={color}/><circle cx="17" cy="10" r="1" fill={color}/></svg>;
      case "type":         return <svg {...s}><path d="M5 7V5h14v2M9 5v14M9 19h6M12 5v14"/></svg>;
      case "globe":        return <svg {...s}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></svg>;
      case "sliders":      return <svg {...s}><path d="M4 7h7M15 7h5M4 12h3M11 12h9M4 17h11M19 17h1"/><circle cx="13" cy="7" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="17" cy="17" r="2"/></svg>;
      case "x":            return <svg {...s}><path d="M6 6l12 12M18 6L6 18"/></svg>;
      default: return null;
    }
  };

  window.Icon = Icon;

  /* ===== canvas.jsx ===== */

  // Animated Journey Canvas, the centerpiece
  // Renders nodes + SVG paths with flowing motion graphics

  const NODE_W = 320;
  const NODE_H = 96;

  // Node visual config, colors per type
  const NODE_STYLE = {
    trigger:  { tag: "TRIGGER",          accent: "#a855f7", soft: "rgba(168,85,247,.10)", icon: "bolt" },
    delay:    { tag: "DELAY",            accent: "#f59e0b", soft: "rgba(245,158,11,.10)", icon: "clock" },
    data:     { tag: "DATA",             accent: "#0ea5e9", soft: "rgba(14,165,233,.10)", icon: "tag" },
    split:    { tag: "CONDITIONAL SPLIT",accent: "#f97316", soft: "rgba(249,115,22,.10)", icon: "split" },
    whatsapp: { tag: "WHATSAPP",         accent: "#22c55e", soft: "rgba(34,197,94,.10)",  icon: "whatsapp" },
    email:    { tag: "EMAIL",            accent: "#ED4D86", soft: "rgba(237,77,134,.10)", icon: "mail" },
    sms:      { tag: "SMS",              accent: "#8b5cf6", soft: "rgba(139,92,246,.10)", icon: "sms" },
    ai:       { tag: "AI AGENT",         accent: "#a855f7", soft: "rgba(168,85,247,.10)", icon: "sparkles" },
    abtest:   { tag: "A/B SPLIT",        accent: "#14b8a6", soft: "rgba(20,184,166,.10)", icon: "abtest" },
    end:      { tag: "END",              accent: "#64748b", soft: "rgba(100,116,139,.10)", icon: "check" },
  };

  const Node = ({ node, selected, onClick, onHover, hovered, pulseOn, dim }) => {
    const style = NODE_STYLE[node.type] || NODE_STYLE.data;
    const isEnd = node.type === "end";
    const isSplit = node.type === "split" || node.type === "abtest";
    const accent = style.accent;

    return (
      <div
        onClick={(e) => { e.stopPropagation(); onClick && onClick(node); }}
        onMouseEnter={() => onHover && onHover(node.id)}
        onMouseLeave={() => onHover && onHover(null)}
        style={{
          position: "absolute",
          left: node.x,
          top: node.y,
          width: NODE_W,
          minHeight: NODE_H,
          background: "#fff",
          border: selected ? `2px solid ${accent}` : "1px solid #e5e7eb",
          borderRadius: 14,
          boxShadow: selected
            ? `0 0 0 4px ${style.soft}, 0 12px 32px rgba(15,23,42,.10)`
            : hovered ? `0 6px 20px rgba(15,23,42,.10)` : `0 1px 2px rgba(15,23,42,.04)`,
          cursor: "pointer",
          padding: "12px 14px",
          transition: "transform .18s ease, box-shadow .18s ease, border-color .18s ease, opacity .18s ease",
          transform: hovered && !selected ? "translateY(-2px)" : "none",
          opacity: dim ? 0.45 : 1,
          userSelect: "none",
          fontFamily: "inherit",
        }}
      >
        {/* tag row */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{
              width: 28, height: 28, borderRadius: 8, background: style.soft,
              display: "grid", placeItems: "center", color: accent, flexShrink: 0,
            }}>
              <Icon name={style.icon} size={15} />
            </div>
            <div style={{ fontSize: 10, letterSpacing: ".08em", fontWeight: 600, color: "#94a3b8", textTransform: "uppercase" }}>
              {style.tag}
            </div>
          </div>
          {!isEnd && (
            <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 11, color: "#10b981", fontWeight: 500 }}>
              <span style={{ width: 6, height: 6, borderRadius: 99, background: "#10b981", boxShadow: "0 0 0 3px rgba(16,185,129,.18)" }} />
              Ready
            </div>
          )}
        </div>
        {/* title */}
        <div style={{ marginTop: 6, fontSize: 14.5, fontWeight: 600, color: "#0f172a", lineHeight: 1.25 }}>
          {node.label}
        </div>
        {/* subtitle */}
        {node.sub && (
          <div style={{ marginTop: 3, fontSize: 12.5, color: "#64748b", lineHeight: 1.35,
            overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>
            {node.sub}
          </div>
        )}
        {/* split branch chips */}
        {isSplit && node.branches && (
          <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
            {node.branches.map((b, i) => (
              <span key={i} style={{
                fontSize: 10.5, fontWeight: 600, padding: "3px 8px", borderRadius: 99,
                background: i === 0 ? "rgba(34,197,94,.10)" : i === 1 ? "rgba(237,77,134,.10)" : "rgba(245,158,11,.10)",
                color: i === 0 ? "#059669" : i === 1 ? "#db2777" : "#d97706",
              }}>{b}</span>
            ))}
          </div>
        )}
        {/* connection dots */}
        {!isEnd && (
          <span style={{
            position: "absolute", left: "50%", bottom: -5, transform: "translateX(-50%)",
            width: 10, height: 10, borderRadius: 99, background: "#fff", border: `2px solid ${accent}`,
            boxShadow: pulseOn ? `0 0 0 6px ${style.soft}` : "none", transition: "box-shadow .3s ease",
          }} />
        )}
        {node.type !== "trigger" && (
          <span style={{
            position: "absolute", left: "50%", top: -5, transform: "translateX(-50%)",
            width: 10, height: 10, borderRadius: 99, background: "#fff", border: `2px solid ${accent}`,
          }} />
        )}
      </div>
    );
  };

  // Path generator, orthogonal connector between two nodes
  const buildPath = (from, to, branchIndex = 0, branchCount = 1) => {
    // From node bottom center → To node top center
    let fromX = from.x + NODE_W / 2;
    const fromY = from.y + NODE_H + 5;
    const toX = to.x + NODE_W / 2;
    const toY = to.y - 5;

    // Adjust source x for branches on splits
    if (branchCount > 1) {
      const offsets = branchCount === 2 ? [-60, 60] : [-100, 0, 100];
      fromX = from.x + NODE_W / 2 + offsets[branchIndex];
    }

    const dx = toX - fromX;
    const dy = toY - fromY;
    const midY = fromY + dy / 2;

    if (Math.abs(dx) < 2) {
      return `M ${fromX} ${fromY} L ${toX} ${toY}`;
    }
    // Orthogonal with rounded corners
    const r = 14;
    const sx = dx > 0 ? 1 : -1;
    return `M ${fromX} ${fromY}
            L ${fromX} ${midY - r}
            Q ${fromX} ${midY} ${fromX + sx * r} ${midY}
            L ${toX - sx * r} ${midY}
            Q ${toX} ${midY} ${toX} ${midY + r}
            L ${toX} ${toY}`;
  };

  const Edge = ({ from, to, color = "#cbd5e1", branchIndex, branchCount, branchLabel, dim, active }) => {
    const d = buildPath(from, to, branchIndex, branchCount);
    const fromX = from.x + NODE_W / 2 + (branchCount > 1 ? (branchCount === 2 ? [-60, 60] : [-100, 0, 100])[branchIndex] : 0);
    const labelX = fromX;
    const labelY = from.y + NODE_H + 24;
    return (
      <g style={{ opacity: dim ? 0.25 : 1, transition: "opacity .2s ease" }}>
        {/* base path */}
        <path d={d} fill="none" stroke={color} strokeWidth={active ? 2.5 : 2} strokeOpacity={active ? 1 : 0.55} strokeLinecap="round" />
        {/* animated dashed overlay, flowing pulse */}
        <path
          d={d}
          fill="none"
          stroke={color}
          strokeWidth={2.5}
          strokeLinecap="round"
          strokeDasharray="6 14"
          strokeDashoffset="0"
          style={{ filter: `drop-shadow(0 0 6px ${color}88)` }}
        >
          <animate attributeName="stroke-dashoffset" from="0" to="-60" dur="1.6s" repeatCount="indefinite" />
        </path>
        {/* moving particle */}
        <circle r="3.5" fill={color} style={{ filter: `drop-shadow(0 0 8px ${color})` }}>
          <animateMotion dur="2.4s" repeatCount="indefinite" path={d} />
          <animate attributeName="opacity" values="0;1;1;0" keyTimes="0;0.1;0.9;1" dur="2.4s" repeatCount="indefinite" />
        </circle>
        {/* branch label chip */}
        {branchLabel && (
          <g transform={`translate(${labelX}, ${labelY})`}>
            <rect x="-30" y="-10" width="60" height="20" rx="10" fill="#fff" stroke={color} strokeWidth="1.2" />
            <text x="0" y="4" textAnchor="middle" fontSize="10.5" fontWeight="600" fill={color} fontFamily="ui-sans-serif, system-ui">{branchLabel}</text>
          </g>
        )}
      </g>
    );
  };

  const JourneyCanvas = ({ data, selectedId, onSelect, onPaneClick }) => {
    const [hovered, setHovered] = React.useState(null);
    const [pulseTick, setPulseTick] = React.useState(0);
    React.useEffect(() => {
      const id = setInterval(() => setPulseTick((t) => t + 1), 2400);
      return () => clearInterval(id);
    }, []);

    const allNodes = [data.trigger, ...data.nodes];
    const byId = Object.fromEntries(allNodes.map((n) => [n.id, n]));

    // Compute canvas size
    const maxY = Math.max(...allNodes.map((n) => n.y + NODE_H)) + 120;
    const maxX = Math.max(...allNodes.map((n) => n.x + NODE_W)) + 120;

    // Determine which edges are "active" relative to selection or hover
    const focused = selectedId || hovered;
    const isFocusedEdge = (a, b) => focused && (a === focused || b === focused);

    // Group split edges by source for branch indexing
    const branchGroups = {};
    data.edges.forEach((e) => {
      const [a, b, meta] = e;
      if (meta && meta.branch) {
        branchGroups[a] = branchGroups[a] || [];
        branchGroups[a].push(b);
      }
    });

    return (
      <div
        onClick={onPaneClick}
        style={{
          position: "relative",
          width: maxX,
          height: maxY,
          backgroundImage: `radial-gradient(circle at 1px 1px, rgba(15,23,42,.08) 1px, transparent 1px)`,
          backgroundSize: "20px 20px",
          margin: "0 auto",
        }}
      >
        <svg width={maxX} height={maxY} style={{ position: "absolute", inset: 0, pointerEvents: "none" }}>
          <defs>
            <filter id="glow"><feGaussianBlur stdDeviation="3" /></filter>
          </defs>
          {data.edges.map((edge, i) => {
            const [aId, bId, meta = {}] = edge;
            const a = byId[aId], b = byId[bId];
            if (!a || !b) return null;
            const branchList = branchGroups[aId] || [];
            const branchIndex = branchList.indexOf(bId);
            const branchCount = branchList.length;
            const dim = focused && !isFocusedEdge(aId, bId);
            return (
              <Edge
                key={i}
                from={a}
                to={b}
                color={meta.color || "#cbd5e1"}
                branchIndex={branchIndex >= 0 ? branchIndex : 0}
                branchCount={branchCount}
                branchLabel={meta.branch}
                dim={dim}
                active={isFocusedEdge(aId, bId)}
              />
            );
          })}
        </svg>
        {allNodes.map((n, i) => (
          <Node
            key={n.id}
            node={n}
            selected={selectedId === n.id}
            hovered={hovered === n.id}
            onHover={setHovered}
            onClick={onSelect}
            pulseOn={(pulseTick + i) % 3 === 0}
            dim={focused && focused !== n.id && !data.edges.some((e) => (e[0] === focused && e[1] === n.id) || (e[1] === focused && e[0] === n.id))}
          />
        ))}
      </div>
    );
  };

  window.JourneyCanvas = JourneyCanvas;
  window.NODE_STYLE = NODE_STYLE;

  /* ===== panel.jsx ===== */

  // Side panels for node configuration

  const Panel = ({ title, onClose, children, footer }) => (
    <div style={{
      position: "absolute", top: 0, right: 0, bottom: 0, width: 380, background: "#fff",
      borderLeft: "1px solid #e5e7eb", display: "flex", flexDirection: "column", zIndex: 30,
      boxShadow: "-12px 0 32px rgba(15,23,42,.06)", animation: "slideInRight .25s ease",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "18px 20px", borderBottom: "1px solid #f1f5f9" }}>
        <div style={{ fontSize: 15, fontWeight: 600, color: "#0f172a" }}>{title}</div>
        <button onClick={onClose} style={{ border: "none", background: "transparent", cursor: "pointer", color: "#64748b", padding: 4 }}>
          <Icon name="x" size={18} />
        </button>
      </div>
      <div style={{ flex: 1, overflow: "auto", padding: "20px" }}>{children}</div>
      {footer && <div style={{ padding: 16, borderTop: "1px solid #f1f5f9", display: "flex", flexDirection: "column", gap: 8 }}>{footer}</div>}
    </div>
  );

  const Field = ({ label, children, hint }) => (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: "#0f172a", marginBottom: 6 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 11.5, color: "#94a3b8", marginTop: 6 }}>{hint}</div>}
    </div>
  );

  const Input = (props) => (
    <input {...props} style={{
      width: "100%", padding: "9px 12px", border: "1px solid #e2e8f0", borderRadius: 8,
      fontSize: 13, color: "#0f172a", background: "#fff", outline: "none", fontFamily: "inherit",
      ...props.style,
    }} onFocus={(e) => e.target.style.borderColor = "#a855f7"} onBlur={(e) => e.target.style.borderColor = "#e2e8f0"} />
  );

  const Select = ({ value, onChange, options }) => (
    <div style={{ position: "relative" }}>
      <select value={value} onChange={onChange} style={{
        width: "100%", padding: "9px 32px 9px 12px", border: "1px solid #e2e8f0", borderRadius: 8,
        fontSize: 13, color: "#0f172a", background: "#fff", appearance: "none", outline: "none", fontFamily: "inherit",
      }}>
        {options.map((o) => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
      </select>
      <span style={{ position: "absolute", right: 10, top: "50%", transform: "translateY(-50%)", color: "#64748b", pointerEvents: "none" }}>
        <Icon name="chevDown" size={14} />
      </span>
    </div>
  );

  const PrimaryBtn = ({ children, onClick, dark }) => (
    <button onClick={onClick} style={{
      width: "100%", padding: "10px 16px", borderRadius: 10, fontSize: 13.5, fontWeight: 600, cursor: "pointer",
      background: dark ? "#0f172a" : "#fff", color: dark ? "#fff" : "#0f172a",
      border: dark ? "none" : "1px solid #e2e8f0", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
      fontFamily: "inherit",
    }}>{children}</button>
  );

  const Toggle = ({ on, onChange, label, sub }) => (
    <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, padding: "12px 0" }}>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: "#0f172a" }}>{label}</div>
        {sub && <div style={{ fontSize: 11.5, color: "#64748b", marginTop: 2 }}>{sub}</div>}
      </div>
      <button onClick={() => onChange(!on)} style={{
        width: 38, height: 22, borderRadius: 99, background: on ? "#a855f7" : "#e2e8f0", border: "none",
        position: "relative", cursor: "pointer", flexShrink: 0, transition: "background .2s",
      }}>
        <span style={{
          position: "absolute", top: 2, left: on ? 18 : 2, width: 18, height: 18, borderRadius: 99, background: "#fff",
          transition: "left .2s", boxShadow: "0 1px 3px rgba(0,0,0,.15)",
        }} />
      </button>
    </div>
  );

  // ------------- Specialized panels per node type -------------

  const ConfigPanel = ({ node, onClose, onDelete }) => {
    const style = NODE_STYLE[node.type] || NODE_STYLE.data;

    const renderBody = () => {
      switch (node.type) {
        case "trigger":
          return (
            <>
              <Field label="Trigger Type">
                <div style={{ padding: 12, background: "linear-gradient(135deg, rgba(168,85,247,.08), rgba(237,77,134,.05))",
                  borderRadius: 10, display: "flex", gap: 10, alignItems: "center", border: "1px solid rgba(168,85,247,.18)" }}>
                  <div style={{ width: 32, height: 32, borderRadius: 8, background: "#fff", display: "grid", placeItems: "center", color: "#a855f7" }}>
                    <Icon name="bolt" size={16} />
                  </div>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>Booking Created</div>
                    <div style={{ fontSize: 11.5, color: "#64748b" }}>Fires for every new reservation</div>
                  </div>
                </div>
              </Field>
              <Field label="Filter conditions" hint="Only enter contacts that match all filters">
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  <FilterRow field="reservation_value" op="≥" value="€ 250" />
                  <FilterRow field="lead_time_days" op="≥" value="7" />
                  <button style={{ alignSelf: "flex-start", border: "1px dashed #cbd5e1", background: "transparent",
                    padding: "6px 10px", borderRadius: 8, fontSize: 12, color: "#64748b", cursor: "pointer", display: "flex", gap: 6, alignItems: "center", fontFamily: "inherit" }}>
                    <Icon name="plus" size={12} /> Add filter
                  </button>
                </div>
              </Field>
              <Field label="Re-entry policy">
                <Select value="once" options={[
                  { value: "once",   label: "Enter once per contact" },
                  { value: "stay",   label: "Enter once per stay" },
                  { value: "always", label: "Re-enter on every booking" },
                ]} />
              </Field>
            </>
          );
        case "delay":
          return (
            <>
              <Field label="Wait until"><Select value="reservation_date" options={[
                { value: "reservation_date", label: "reservation_date" },
                { value: "checkin_date", label: "check_in_date" },
                { value: "checkout_date", label: "check_out_date" },
              ]} /></Field>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                <Field label="Offset"><Input defaultValue="365" /></Field>
                <Field label="Unit"><Select value="days" options={["days", "hours", "weeks"]} /></Field>
              </div>
              <Field label="Direction"><Select value="after" options={["after", "before"]} /></Field>
              <Toggle on={true} onChange={() => {}} label="Respect DND windows" sub="Hold messages until 9am local time" />
            </>
          );
        case "split":
          return (
            <>
              <Field label="Node label"><Input defaultValue={node.label} /></Field>
              <Field label="Condition">
                <Select value="channel" options={[
                  { value: "channel", label: "Booking Channel Type" },
                  { value: "value", label: "Reservation Value" },
                  { value: "country", label: "Guest Country" },
                  { value: "loyalty", label: "Loyalty Tier" },
                ]} />
              </Field>
              <div style={{ marginTop: 14, fontSize: 11, fontWeight: 600, color: "#64748b", letterSpacing: ".06em", textTransform: "uppercase" }}>Branches</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 8 }}>
                {(node.branches || ["OTA", "Direct", "Tour Op."]).map((b, i) => (
                  <div key={i} style={{
                    display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 10,
                    border: "1px solid #e2e8f0", background: "#fff",
                  }}>
                    <span style={{ width: 8, height: 8, borderRadius: 99,
                      background: i === 0 ? "#10b981" : i === 1 ? "#ED4D86" : "#f59e0b" }} />
                    <span style={{ fontSize: 13, fontWeight: 500, flex: 1 }}>{b}</span>
                    <span style={{ fontSize: 11, color: "#94a3b8" }}>equals "{b.toLowerCase()}"</span>
                  </div>
                ))}
                <button style={{ alignSelf: "flex-start", border: "1px dashed #cbd5e1", background: "transparent",
                  padding: "8px 12px", borderRadius: 8, fontSize: 12, color: "#64748b", cursor: "pointer", display: "flex", gap: 6, alignItems: "center", fontFamily: "inherit" }}>
                  <Icon name="plus" size={12} /> Add branch
                </button>
              </div>
            </>
          );
        case "whatsapp":
          return (
            <>
              <Field label="Node label"><Input defaultValue={node.label} /></Field>
              <Field label="WhatsApp Template" hint="Approved Meta templates only">
                <div style={{ padding: 12, border: "1px solid #e2e8f0", borderRadius: 10, background: "#f8fafc" }}>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>winback_offer_v3</div>
                      <div style={{ fontSize: 11, color: "#64748b" }}>en · marketing · approved</div>
                    </div>
                    <span style={{ fontSize: 10.5, fontWeight: 600, padding: "3px 8px", borderRadius: 99, background: "rgba(34,197,94,.10)", color: "#059669" }}>WHATSAPP</span>
                  </div>
                  <div style={{ marginTop: 10, padding: 10, background: "#dcf8c6", borderRadius: 8, fontSize: 12, color: "#0f172a", lineHeight: 1.4 }}>
                    Hi {"{{first_name}}"}, we miss you in {"{{hotel_city}}"} 💛<br/>
                    As a returning guest, here's <b>10% off</b> when you book direct: {"{{promo_code}}"}<br/>
                    Valid until {"{{expiry_date}}"}.
                  </div>
                </div>
              </Field>
              <Field label="Variables">
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {[["{{first_name}}", "contact.first_name"], ["{{hotel_city}}", "booking.hotel.city"], ["{{promo_code}}", "generated.promo"]].map(([k, v]) => (
                    <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "6px 10px", background: "#f8fafc", borderRadius: 6, fontSize: 11.5 }}>
                      <code style={{ color: "#a855f7" }}>{k}</code>
                      <code style={{ color: "#64748b" }}>{v}</code>
                    </div>
                  ))}
                </div>
              </Field>
              <Toggle on={true} onChange={() => {}} label="Enable AI Responses" sub="AI Concierge auto-replies to inbound messages" />
            </>
          );
        case "email":
          return (
            <>
              <Field label="Node label"><Input defaultValue={node.label} /></Field>
              <Field label="Email Template">
                <div style={{ padding: 14, border: "1px solid #e2e8f0", borderRadius: 10, background: "#fff",
                  backgroundImage: "linear-gradient(180deg, #fff 0%, #fdf2f8 100%)" }}>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>Win-Back · Editorial</div>
                  <div style={{ fontSize: 11, color: "#64748b", marginTop: 2 }}>Subject: A room is calling, {"{{first_name}}"}</div>
                  <div style={{ marginTop: 10, padding: 10, background: "#fff", border: "1px solid #f1e6f0", borderRadius: 8 }}>
                    <div style={{ fontFamily: "ui-serif, Georgia, serif", fontSize: 18, color: "#831843", lineHeight: 1.1 }}>
                      Come back to where<br/><i>the sea remembers you.</i>
                    </div>
                    <div style={{ height: 1, background: "#f1e6f0", margin: "10px 0" }} />
                    <div style={{ fontSize: 11.5, color: "#64748b", lineHeight: 1.5 }}>
                      Your last stay at {"{{hotel_name}}"} was a year ago this week. We saved a suite, and a small surprise, for your return.
                    </div>
                  </div>
                </div>
              </Field>
              <Field label="From"><Input defaultValue="reservations@sunsethospitality.com" /></Field>
              <Toggle on={true} onChange={() => {}} label="Smart Sending" sub="Skip contacts who got an email in the last 16h" />
              <Toggle on={false} onChange={() => {}} label="Track opens & clicks" />
            </>
          );
        case "sms":
          return (
            <>
              <Field label="Node label"><Input defaultValue={node.label} /></Field>
              <Field label="Message" hint="160 characters · GSM-7">
                <textarea defaultValue="Sunset Rewards: earn points on every stay & unlock exclusive perks. Join free → sunset.co/r/{{code}}" style={{
                  width: "100%", padding: "10px 12px", border: "1px solid #e2e8f0", borderRadius: 8,
                  fontSize: 13, fontFamily: "inherit", outline: "none", minHeight: 90, resize: "vertical",
                }} />
              </Field>
              <Field label="Sender ID"><Input defaultValue="SunsetHotels" /></Field>
            </>
          );
        case "ai":
          return (
            <>
              <Field label="Agent">
                <div style={{ padding: 12, background: "linear-gradient(135deg, rgba(168,85,247,.10), rgba(237,77,134,.06))",
                  borderRadius: 10, border: "1px solid rgba(168,85,247,.18)", display: "flex", gap: 10, alignItems: "center" }}>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: "#fff", display: "grid", placeItems: "center", color: "#a855f7" }}>
                    <Icon name="sparkles" size={18} />
                  </div>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>Concierge AI · GPT-Hospitality</div>
                    <div style={{ fontSize: 11.5, color: "#64748b" }}>Multilingual · 23 languages</div>
                  </div>
                </div>
              </Field>
              <Field label="Goal" hint="What should the agent try to achieve?">
                <textarea defaultValue="Qualify reply intent. If the guest expresses interest in a return stay, offer the promo code and route to the booking link. If unsure, hand off to staff." style={{
                  width: "100%", padding: "10px 12px", border: "1px solid #e2e8f0", borderRadius: 8,
                  fontSize: 13, fontFamily: "inherit", outline: "none", minHeight: 96, resize: "vertical",
                }} />
              </Field>
              <Field label="Handoff condition"><Select value="confidence" options={[
                { value: "confidence", label: "When confidence < 80%" },
                { value: "always", label: "Always notify staff" },
                { value: "never", label: "Never, fully autonomous" },
              ]} /></Field>
            </>
          );
        case "data":
          return (
            <>
              <Field label="Action"><Select value="add_tag" options={[
                { value: "add_tag", label: "Add Tag" }, { value: "remove_tag", label: "Remove Tag" }, { value: "update_field", label: "Update Field" },
              ]} /></Field>
              <Field label="Tag"><Input defaultValue="winback_365" /></Field>
              <Field label="Tag color">
                <div style={{ display: "flex", gap: 6 }}>
                  {["#a855f7", "#ED4D86", "#f59e0b", "#10b981", "#0ea5e9"].map((c, i) => (
                    <span key={c} style={{ width: 24, height: 24, borderRadius: 99, background: c, cursor: "pointer", border: i === 0 ? "2px solid #0f172a" : "2px solid transparent" }} />
                  ))}
                </div>
              </Field>
            </>
          );
        case "end":
          return (
            <>
              <Field label="End behavior"><Select value="complete" options={[
                { value: "complete", label: "Complete journey" }, { value: "exit", label: "Exit & re-enter eligible" },
              ]} /></Field>
              <Field label="Final tag"><Input defaultValue={node.sub.split("·")[1]?.trim() || "win_back_complete"} /></Field>
            </>
          );
        default:
          return <div style={{ fontSize: 13, color: "#64748b" }}>Configure this step.</div>;
      }
    };

    return (
      <Panel
        title={`Configure ${style.tag.split(" ").map(w => w[0] + w.slice(1).toLowerCase()).join(" ")}`}
        onClose={onClose}
        footer={
          <>
            <PrimaryBtn dark>
              <Icon name="save" size={14} /> Save Changes
            </PrimaryBtn>
            <button onClick={onDelete} style={{
              width: "100%", padding: "10px 16px", borderRadius: 10, fontSize: 13, fontWeight: 600, cursor: "pointer",
              background: "transparent", color: "#dc2626", border: "1px solid #fee2e2", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "inherit",
            }}><Icon name="trash" size={14} /> Delete Node</button>
          </>
        }
      >
        <Field label="Node Label"><Input defaultValue={node.label} /></Field>
        <div style={{ height: 1, background: "#f1f5f9", margin: "4px 0 18px" }} />
        {renderBody()}
      </Panel>
    );
  };

  const FilterRow = ({ field, op, value }) => (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 50px 1fr 28px", gap: 6, alignItems: "center" }}>
      <Input defaultValue={field} />
      <Input defaultValue={op} style={{ textAlign: "center", padding: "9px 4px" }} />
      <Input defaultValue={value} />
      <button style={{ background: "transparent", border: "none", color: "#cbd5e1", cursor: "pointer", padding: 4 }}><Icon name="x" size={14} /></button>
    </div>
  );

  window.ConfigPanel = ConfigPanel;
  window.Field = Field;
  window.Input = Input;
  window.Select = Select;
  window.PrimaryBtn = PrimaryBtn;
  window.Toggle = Toggle;

  /* ===== sidebar.jsx ===== */

  // Sidebar (left navigation) + top app shell

  const NAV = [
    { label: "Home", icon: "home" },
    { section: "DATA", icon: "data", children: ["Contacts", "Segments", "Tags"] },
    { section: "CHANNELS", icon: "inbox", expanded: true, children: [
      { label: "Inbox", icon: "inbox" },
      { label: "Broadcasts", icon: "broadcast", group: ["WhatsApp", "Email"] },
      { label: "Templates", icon: "doc", group: ["WhatsApp", "Email"] },
      { label: "Journeys", icon: "journey", active: true },
    ]},
    { section: "AI AGENTS", icon: "agent", children: ["Concierge", "Reservations"] },
    { section: "CDP", icon: "cdp", children: ["Sources"] },
    { section: "LOYALTY", icon: "award", children: ["Tiers", "Rewards"] },
  ];

  const Sidebar = ({ onNavigate }) => {
    return (
      <aside style={{
        width: 232, background: "#fafafa", borderRight: "1px solid #ececec",
        padding: "0", display: "flex", flexDirection: "column", flexShrink: 0, height: "100%",
      }}>
        <div style={{ padding: "18px 18px 12px", display: "flex", alignItems: "center", gap: 8 }}>
          <div style={{ width: 28, height: 28, borderRadius: 8, background: "#0f172a", display: "grid", placeItems: "center" }}>
            <GMMark size={18} color="white" />
          </div>
          <div style={{ fontWeight: 700, fontSize: 15, color: "#0f172a" }}>GuestMaker</div>
        </div>
        <div style={{ padding: "0 14px 12px" }}>
          <div style={{ background: "#fff", border: "1px solid #ececec", borderRadius: 10, padding: "8px 10px", display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{ width: 24, height: 24, borderRadius: 6, background: "#0f172a", display: "grid", placeItems: "center", color: "#fef3c7", fontSize: 12 }}>🏨</div>
            <div style={{ fontSize: 12, fontWeight: 600, color: "#0f172a", flex: 1 }}>Sunset Hospitality</div>
            <Icon name="chevDown" size={12} color="#94a3b8" />
          </div>
        </div>
        <nav style={{ flex: 1, overflow: "auto", padding: "0 8px", fontSize: 13 }}>
          <NavItem icon="home" label="Home" />
          <NavGroup title="DATA" icon="data">
            <NavItem label="Contacts" indent />
            <NavItem label="Segments" indent />
            <NavItem label="Tags" indent />
          </NavGroup>
          <NavGroup title="CHANNELS" icon="inbox" defaultOpen>
            <NavItem icon="inbox" label="Inbox" indent />
            <NavGroup title="Broadcasts" icon="broadcast" indent small>
              <NavItem label="WhatsApp" deepIndent />
              <NavItem label="Email" deepIndent />
            </NavGroup>
            <NavGroup title="Templates" icon="doc" indent small>
              <NavItem label="WhatsApp" deepIndent />
              <NavItem label="Email" deepIndent />
            </NavGroup>
            <NavItem icon="journey" label="Journeys" indent active onClick={() => onNavigate && onNavigate("journeys")} />
          </NavGroup>
          <NavGroup title="AI AGENTS" icon="agent">
            <NavItem label="Concierge" indent />
            <NavItem label="Reservations" indent />
          </NavGroup>
          <NavGroup title="CDP" icon="cdp">
            <NavItem label="Sources" indent />
          </NavGroup>
          <NavGroup title="LOYALTY" icon="award">
            <NavItem label="Tiers" indent />
            <NavItem label="Rewards" indent />
          </NavGroup>
        </nav>
        <div style={{ padding: "12px 14px", borderTop: "1px solid #ececec" }}>
          <div style={{ fontSize: 10.5, fontWeight: 600, color: "#94a3b8", letterSpacing: ".08em", marginBottom: 8 }}>PLATFORM</div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 6px", borderRadius: 8 }}>
            <svg width="22" height="22" viewBox="0 0 22 22"><circle cx="11" cy="11" r="9" fill="none" stroke="#e2e8f0" strokeWidth="2.5" /><circle cx="11" cy="11" r="9" fill="none" stroke="#a855f7" strokeWidth="2.5" strokeDasharray="56.5" strokeDashoffset="23.5" transform="rotate(-90 11 11)" strokeLinecap="round"/></svg>
            <div style={{ flex: 1, fontSize: 12.5, fontWeight: 500, color: "#0f172a" }}>Setup Guide</div>
            <div style={{ fontSize: 11, color: "#94a3b8" }}>7/12</div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 6px", borderRadius: 8, color: "#0f172a", fontSize: 12.5 }}>
            <Icon name="doc" size={14} color="#64748b" /> Knowledge Base
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 6px", borderRadius: 8, color: "#0f172a", fontSize: 12.5 }}>
            <Icon name="settings" size={14} color="#64748b" /> Settings
          </div>
        </div>
      </aside>
    );
  };

  const NavItem = ({ icon, label, active, indent, deepIndent, onClick }) => (
    <button onClick={onClick} style={{
      width: "100%", display: "flex", alignItems: "center", gap: 10,
      padding: deepIndent ? "7px 10px 7px 36px" : indent ? "7px 10px 7px 22px" : "7px 10px",
      border: "none", borderRadius: 8, cursor: "pointer", fontSize: 13, color: active ? "#a855f7" : "#0f172a",
      background: active ? "rgba(168,85,247,.10)" : "transparent", fontWeight: active ? 600 : 500, fontFamily: "inherit",
      margin: "1px 0",
    }}>
      {icon && <Icon name={icon} size={14} color={active ? "#a855f7" : "#64748b"} />}
      {label}
    </button>
  );

  const NavGroup = ({ title, icon, children, defaultOpen, indent, small }) => {
    const [open, setOpen] = React.useState(defaultOpen ?? false);
    return (
      <div style={{ marginTop: small ? 0 : 4 }}>
        <button onClick={() => setOpen(!open)} style={{
          width: "100%", display: "flex", alignItems: "center", gap: 10,
          padding: indent ? "7px 10px 7px 22px" : "7px 10px",
          border: "none", background: "transparent", borderRadius: 8, cursor: "pointer", fontFamily: "inherit",
          fontSize: small ? 13 : 11.5, fontWeight: small ? 500 : 700,
          letterSpacing: small ? "normal" : ".08em",
          color: small ? "#0f172a" : "#94a3b8",
          textTransform: small ? "none" : "uppercase",
        }}>
          {icon && <Icon name={icon} size={14} color="#64748b" />}
          <span style={{ flex: 1, textAlign: "left" }}>{title}</span>
          <Icon name={open ? "chevDown" : "chev"} size={11} color="#94a3b8" />
        </button>
        {open && <div>{children}</div>}
      </div>
    );
  };

  window.Sidebar = Sidebar;

  /* ===== wizard.jsx ===== */

  // Wizard steps + Trigger picker

  const WizardStepper = ({ active, onNavigate }) => {
    const steps = [
      { n: 1, title: "Setup",    sub: "Name your journey" },
      { n: 2, title: "Template", sub: "Choose a starting point" },
      { n: 3, title: "Trigger",  sub: "Choose what starts it" },
      { n: 4, title: "Builder",  sub: "Design your flow" },
    ];
    return (
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "center", gap: 0, padding: "32px 24px 28px" }}>
        {steps.map((s, i) => {
          const done = active > s.n;
          const current = active === s.n;
          return (
            <React.Fragment key={s.n}>
              <button onClick={() => onNavigate && onNavigate(s.n)} style={{
                display: "flex", flexDirection: "column", alignItems: "center", gap: 6,
                border: "none", background: "transparent", cursor: "pointer", fontFamily: "inherit", padding: "0 12px",
              }}>
                <div style={{
                  width: 30, height: 30, borderRadius: 99, display: "grid", placeItems: "center",
                  background: current ? "#a855f7" : done ? "#a855f7" : "#fff",
                  color: current || done ? "#fff" : "#94a3b8",
                  border: current || done ? "none" : "1.5px solid #cbd5e1",
                  fontSize: 13, fontWeight: 600, transition: "all .2s",
                  boxShadow: current ? "0 0 0 6px rgba(168,85,247,.15)" : "none",
                }}>{done ? <Icon name="check" size={14} stroke={2.5}/> : s.n}</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: current ? "#a855f7" : "#0f172a" }}>{s.title}</div>
                <div style={{ fontSize: 11, color: "#94a3b8" }}>{s.sub}</div>
              </button>
              {i < steps.length - 1 && (
                <div style={{ height: 1.5, flex: 1, maxWidth: 120, background: active > s.n ? "#a855f7" : "#e2e8f0", marginTop: 14 }} />
              )}
            </React.Fragment>
          );
        })}
      </div>
    );
  };

  // ---- Wizard Step 1: Setup ----
  const SetupStep = ({ onNext }) => (
    <div style={{ maxWidth: 540, margin: "0 auto", padding: "12px 24px 64px" }}>
      <div style={{ background: "#fff", border: "1px solid #ececec", borderRadius: 14, padding: 32, boxShadow: "0 1px 2px rgba(15,23,42,.04)" }}>
        <div style={{ width: 56, height: 56, borderRadius: 99, background: "rgba(168,85,247,.10)", margin: "0 auto", display: "grid", placeItems: "center", color: "#a855f7" }}>
          <Icon name="journey" size={26} />
        </div>
        <div style={{ textAlign: "center", marginTop: 14, fontSize: 22, fontWeight: 600, color: "#0f172a" }}>Let's set up your journey</div>
        <div style={{ textAlign: "center", marginTop: 6, fontSize: 13.5, color: "#64748b" }}>Give your journey a name and optionally assign it to a specific hotel.</div>
        <div style={{ marginTop: 28 }}>
          <Field label="Journey Name *">
            <Input defaultValue="Win back · 365 days after booking" style={{ borderColor: "#a855f7", boxShadow: "0 0 0 3px rgba(168,85,247,.10)" }} />
          </Field>
          <Field label="Description">
            <textarea defaultValue="Re-engage past guests one year after their booking with a personalized win-back offer across WhatsApp, email & SMS." style={{
              width: "100%", padding: "10px 12px", border: "1px solid #e2e8f0", borderRadius: 8,
              fontSize: 13, fontFamily: "inherit", outline: "none", minHeight: 80, resize: "vertical",
            }} />
          </Field>
          <Field label="Hotel" hint='Limit this journey to a specific hotel or leave as "All Hotels".'>
            <Select value="all" options={[
              { value: "all", label: "All Hotels" },
              { value: "tenerife", label: "Lumia Tenerife" },
              { value: "mallorca", label: "Lumia Mallorca" },
            ]}/>
          </Field>
          <button onClick={() => onNext(2)} style={{
            width: "100%", marginTop: 12, padding: "12px 16px", background: "#0f172a", color: "#fff",
            border: "none", borderRadius: 10, fontSize: 13.5, fontWeight: 600, cursor: "pointer",
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "inherit",
          }}>Continue to Templates <Icon name="chev" size={14} stroke={2}/></button>
        </div>
      </div>
    </div>
  );

  // ---- Wizard Step 2: Template picker ----
  const TEMPLATES = [
    { id: "scratch", title: "Start from scratch", sub: "Build your journey step by step with a blank canvas.", icon: "sparkles", featured: true },
    { id: "prestay",  title: "Pre-Stay",          sub: "Engage guests from booking to arrival, confirmations, upsells, pre-arrival info.", icon: "calendarPlus", count: 12 },
    { id: "during",   title: "During Stay",       sub: "Enhance the on-property experience, welcome messages, check-in flows, concierge.", icon: "stack", count: 12 },
    { id: "post",     title: "Post-Stay",         sub: "Turn guests into advocates, feedback, reviews, thank you messages.", icon: "award", count: 12 },
    { id: "loyalty",  title: "Loyalty & Retention", sub: "Build lasting relationships, enrollment, tier upgrades, points, birthday rewards.", icon: "heart", count: 12 },
    { id: "reengage", title: "Re-engagement",     sub: "Win back dormant guests, reactivation campaigns, win-back sequences.", icon: "repeat", count: 12, recommended: true },
  ];

  const TemplateStep = ({ onNext }) => {
    const [selected, setSelected] = React.useState("scratch");
    return (
      <div style={{ maxWidth: 1000, margin: "0 auto", padding: "12px 24px 64px" }}>
        <div onClick={() => setSelected("scratch")} style={{
          border: selected === "scratch" ? "2px solid #a855f7" : "1px solid #ececec",
          background: selected === "scratch" ? "rgba(168,85,247,.04)" : "#fff",
          borderRadius: 14, padding: 18, display: "flex", alignItems: "center", gap: 14, cursor: "pointer",
          marginBottom: 28,
        }}>
          <div style={{ width: 40, height: 40, borderRadius: 10, background: "rgba(168,85,247,.12)", display: "grid", placeItems: "center", color: "#a855f7" }}>
            <Icon name="sparkles" size={18} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: "#0f172a" }}>Start from scratch</div>
            <div style={{ fontSize: 12.5, color: "#64748b" }}>Build your journey step by step with a blank canvas.</div>
          </div>
          {selected === "scratch" && (
            <div style={{ width: 24, height: 24, borderRadius: 99, background: "#a855f7", display: "grid", placeItems: "center", color: "#fff" }}>
              <Icon name="check" size={14} stroke={2.5}/>
            </div>
          )}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 14 }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: "#0f172a" }}>Browse by category</div>
            <div style={{ fontSize: 12, color: "#64748b" }}>Pre-built journeys designed for hotels, ready to use.</div>
          </div>
          <button style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "7px 12px", fontSize: 12.5, color: "#0f172a", cursor: "pointer", fontFamily: "inherit" }}>View All Journeys</button>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          {TEMPLATES.slice(1).map((t) => (
            <div key={t.id} style={{
              background: "#fff", border: t.recommended ? "1.5px solid #a855f7" : "1px solid #ececec", borderRadius: 12, padding: 16,
              cursor: "pointer", position: "relative",
            }}>
              {t.recommended && <span style={{ position: "absolute", top: 12, right: 12, fontSize: 10, fontWeight: 600, background: "#a855f7", color: "#fff", borderRadius: 99, padding: "3px 8px" }}>Recommended for win-back</span>}
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: "#f1f5f9", display: "grid", placeItems: "center", color: "#475569" }}>
                  <Icon name={t.icon} size={16}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "#0f172a" }}>{t.title}</div>
                </div>
                <Icon name="chev" size={14} color="#94a3b8" />
              </div>
              <div style={{ fontSize: 12.5, color: "#64748b", margin: "10px 0", lineHeight: 1.5 }}>{t.sub}</div>
              <div style={{ fontSize: 11.5, color: "#94a3b8" }}>{t.count} journeys</div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 28 }}>
          <button onClick={() => onNext(1)} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "10px 18px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 8 }}>
            <Icon name="back" size={14}/> Back
          </button>
          <button onClick={() => onNext(3)} style={{ background: "#0f172a", color: "#fff", border: "none", borderRadius: 10, padding: "10px 18px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 8 }}>
            Continue to Triggers <Icon name="chev" size={14}/>
          </button>
        </div>
      </div>
    );
  };

  // ---- Wizard Step 3: Trigger picker ----
  const TRIGGER_COLORS = {
    blue:    { bg: "rgba(59,130,246,.10)",  fg: "#3b82f6" },
    red:     { bg: "rgba(239,68,68,.10)",   fg: "#ef4444" },
    amber:   { bg: "rgba(245,158,11,.12)",  fg: "#d97706" },
    green:   { bg: "rgba(34,197,94,.10)",   fg: "#16a34a" },
    orange:  { bg: "rgba(249,115,22,.10)",  fg: "#ea580c" },
    pink:    { bg: "rgba(237,77,134,.10)",  fg: "#db2777" },
    purple:  { bg: "rgba(168,85,247,.10)",  fg: "#9333ea" },
    slate:   { bg: "rgba(100,116,139,.10)", fg: "#475569" },
    neutral: { bg: "rgba(148,163,184,.12)", fg: "#475569" },
  };

  const TriggerStep = ({ onNext }) => {
    const [selected, setSelected] = React.useState("booking_created");
    return (
      <div style={{ maxWidth: 1100, margin: "0 auto", padding: "0 24px 64px" }}>
        <div style={{ textAlign: "center" }}>
          <div style={{ fontSize: 22, fontWeight: 600, color: "#0f172a" }}>What should trigger this journey?</div>
          <div style={{ fontSize: 13.5, color: "#64748b", marginTop: 4 }}>Select the event that will start this journey for your guests.</div>
        </div>
        <div style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 28 }}>
          {window.TRIGGERS.map((sec) => (
            <div key={sec.section}>
              <div style={{ fontSize: 11, fontWeight: 700, color: "#94a3b8", letterSpacing: ".08em", textTransform: "uppercase", marginBottom: 10 }}>{sec.section}</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
                {sec.items.map((t) => {
                  const c = TRIGGER_COLORS[t.color] || TRIGGER_COLORS.neutral;
                  const isSel = selected === t.id;
                  return (
                    <button key={t.id} onClick={() => setSelected(t.id)} style={{
                      background: "#fff", border: isSel ? "1.5px solid #a855f7" : "1px solid #ececec",
                      boxShadow: isSel ? "0 0 0 3px rgba(168,85,247,.12)" : "none",
                      borderRadius: 12, padding: 14, textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                      display: "flex", flexDirection: "column", gap: 10, transition: "all .15s",
                    }}>
                      <div style={{ width: 34, height: 34, borderRadius: 9, background: c.bg, color: c.fg, display: "grid", placeItems: "center" }}>
                        <Icon name={t.icon} size={16}/>
                      </div>
                      <div>
                        <div style={{ fontSize: 13.5, fontWeight: 600, color: "#0f172a" }}>{t.name}</div>
                        <div style={{ fontSize: 11.5, color: "#64748b", marginTop: 2, lineHeight: 1.4 }}>{t.sub}</div>
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 28 }}>
          <button onClick={() => onNext(2)} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10, padding: "10px 18px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 8 }}>
            <Icon name="back" size={14}/> Back
          </button>
          <button onClick={() => onNext(4)} style={{ background: "#0f172a", color: "#fff", border: "none", borderRadius: 10, padding: "10px 18px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 8 }}>
            Continue to Builder <Icon name="chev" size={14}/>
          </button>
        </div>
      </div>
    );
  };

  window.WizardStepper = WizardStepper;
  window.SetupStep = SetupStep;
  window.TemplateStep = TemplateStep;
  window.TriggerStep = TriggerStep;

  /* ===== builder.jsx ===== */

  // Builder view, header + canvas + panels + node palette

  const NODE_PALETTE = {
    MESSAGES: [
      { type: "whatsapp", label: "WhatsApp",   icon: "whatsapp" },
      { type: "ai",       label: "AI Response",icon: "sparkles" },
      { type: "email",    label: "Email",      icon: "mail" },
      { type: "sms",      label: "SMS",        icon: "sms" },
    ],
    DATA: [
      { type: "data", label: "Update Contact", icon: "user" },
      { type: "data", label: "Add Tag",        icon: "tag" },
      { type: "data", label: "Webhook",        icon: "code" },
    ],
    LOGIC: [
      { type: "delay",  label: "Time Delay",       icon: "clock" },
      { type: "delay",  label: "Delay Until",      icon: "clock" },
      { type: "delay",  label: "Send at Time",     icon: "clock" },
      { type: "split",  label: "Conditional Split",icon: "split" },
      { type: "abtest", label: "A/B Split",        icon: "abtest" },
      { type: "end",    label: "End",              icon: "check" },
    ],
  };

  const PaletteSidebar = () => (
    <div style={{
      width: 232, flexShrink: 0, background: "#fafafa", borderRight: "1px solid #ececec",
      overflow: "auto", padding: "20px 14px",
    }}>
      <div style={{ fontSize: 14, fontWeight: 700, color: "#0f172a" }}>Add Steps</div>
      <div style={{ fontSize: 11.5, color: "#94a3b8", marginTop: 2 }}>Click or drag to canvas</div>
      {Object.entries(NODE_PALETTE).map(([section, items]) => (
        <div key={section} style={{ marginTop: 22 }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: "#94a3b8", letterSpacing: ".08em", marginBottom: 8 }}>{section}</div>
          {items.map((it, i) => {
            const style = NODE_STYLE[it.type] || {};
            return (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 8,
                background: "#fff", border: "1px solid #ececec", marginBottom: 6, cursor: "grab",
                fontSize: 13, color: "#0f172a", fontWeight: 500,
              }}>
                <span style={{ color: style.accent || "#64748b" }}><Icon name={it.icon} size={14}/></span>
                <span style={{ flex: 1 }}>{it.label}</span>
                <span style={{ color: "#cbd5e1", fontSize: 12 }}>⋮⋮</span>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );

  const BuilderHeader = ({ onBack, onOpenSettings }) => (
    <div style={{
      height: 56, padding: "0 20px", display: "flex", alignItems: "center", gap: 12,
      background: "#fff", borderBottom: "1px solid #ececec", flexShrink: 0,
    }}>
      <button onClick={onBack} style={{ background: "transparent", border: "none", padding: 6, cursor: "pointer", color: "#0f172a", fontFamily: "inherit" }}>
        <Icon name="back" size={18}/>
      </button>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: "#0f172a" }}>Win back · 365 days after booking</div>
        <span style={{ fontSize: 11, fontWeight: 600, padding: "3px 8px", borderRadius: 99, background: "rgba(168,85,247,.10)", color: "#9333ea" }}>Draft</span>
        <span style={{ fontSize: 11.5, color: "#64748b" }}>Unsaved changes</span>
      </div>
      <div style={{ flex: 1 }} />
      <button style={{ background: "transparent", border: "none", padding: 6, cursor: "pointer", color: "#64748b" }}>
        <Icon name="panelLeft" size={16}/>
      </button>
      <button onClick={onOpenSettings} style={{
        background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "7px 12px", fontSize: 12.5, color: "#0f172a",
        cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        <Icon name="settings" size={13}/> Settings
      </button>
      <button style={{
        background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "7px 12px", fontSize: 12.5, color: "#0f172a",
        cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        <Icon name="play" size={11}/> Review and activate
      </button>
      <button style={{
        background: "#0f172a", color: "#fff", border: "none", borderRadius: 8, padding: "7px 14px",
        fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 6,
      }}>
        <Icon name="save" size={13}/> Save
      </button>
    </div>
  );

  const SettingsModal = ({ onClose }) => {
    const [ai, setAi] = React.useState(true);
    const [dnd, setDnd] = React.useState(false);
    const [smart, setSmart] = React.useState(true);
    return (
      <div onClick={onClose} style={{
        position: "fixed", inset: 0, background: "rgba(15,23,42,.5)", zIndex: 100,
        display: "grid", placeItems: "center", animation: "fadeIn .15s ease",
      }}>
        <div onClick={(e) => e.stopPropagation()} style={{
          background: "#fff", borderRadius: 14, width: 480, padding: 24, boxShadow: "0 30px 60px rgba(15,23,42,.30)",
        }}>
          <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
            <div>
              <div style={{ fontSize: 17, fontWeight: 600, color: "#0f172a" }}>Journey Settings</div>
              <div style={{ fontSize: 12.5, color: "#64748b", marginTop: 2 }}>Configure channel-specific settings for this journey</div>
            </div>
            <button onClick={onClose} style={{ background: "transparent", border: "none", color: "#64748b", cursor: "pointer", padding: 4 }}>
              <Icon name="x" size={18}/>
            </button>
          </div>
          <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 8, color: "#a855f7" }}>
            <Icon name="sparkles" size={14}/> <span style={{ fontSize: 13, fontWeight: 600, color: "#0f172a" }}>AI Assistance</span>
          </div>
          <Toggle on={ai} onChange={setAi} label="Enable AI Responses" sub="AI will automatically respond to guest messages during this journey" />
          <div style={{ background: "#f8fafc", borderRadius: 10, padding: 12, fontSize: 11.5, color: "#64748b", lineHeight: 1.5 }}>
            AI settings will inherit from hotel configuration. You can customize per-node settings by adding AI Response nodes.
          </div>
          <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 8, color: "#a855f7" }}>
            <Icon name="moon" size={14}/> <span style={{ fontSize: 13, fontWeight: 600, color: "#0f172a" }}>Do Not Disturb</span>
          </div>
          <Toggle on={dnd} onChange={setDnd} label="Respect DND Windows" sub="Delay messages during quiet hours" />
          <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 8, color: "#a855f7" }}>
            <Icon name="mail" size={14}/> <span style={{ fontSize: 13, fontWeight: 600, color: "#0f172a" }}>Smart Sending</span>
          </div>
          <Toggle on={smart} onChange={setSmart} label="Enable Smart Sending" sub="Skip contacts who received an email within the sending window" />
          {smart && (
            <>
              <div style={{ fontSize: 11.5, color: "#64748b", marginTop: 4 }}>Using tenant default: <b style={{ color: "#0f172a" }}>16 hours</b></div>
              <Field label="Override period for this journey (optional)">
                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <Input defaultValue="16" style={{ width: 90 }} />
                  <span style={{ fontSize: 12.5, color: "#64748b" }}>hours</span>
                </div>
              </Field>
            </>
          )}
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 8 }}>
            <button onClick={onClose} style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "8px 16px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>Cancel</button>
            <button onClick={onClose} style={{ background: "#0f172a", color: "#fff", border: "none", borderRadius: 8, padding: "8px 16px", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>Save Settings</button>
          </div>
        </div>
      </div>
    );
  };

  const Minimap = ({ data }) => {
    const SCALE = 0.07;
    const w = 200, h = 130;
    const allNodes = [data.trigger, ...data.nodes];
    const maxX = Math.max(...allNodes.map(n => n.x + 320));
    const maxY = Math.max(...allNodes.map(n => n.y + 96));
    const sx = w / maxX, sy = h / maxY;
    return (
      <div style={{
        position: "absolute", right: 16, bottom: 16, width: w, height: h, background: "#fff",
        border: "1px solid #ececec", borderRadius: 8, padding: 6, zIndex: 5, boxShadow: "0 4px 12px rgba(15,23,42,.06)",
      }}>
        <svg width="100%" height="100%" viewBox={`0 0 ${w} ${h}`}>
          {allNodes.map((n, i) => {
            const c = (NODE_STYLE[n.type] || {}).accent || "#94a3b8";
            return <rect key={i} x={n.x * sx} y={n.y * sy} width={320 * sx} height={96 * sy} rx="2" fill={c} opacity="0.5" />;
          })}
        </svg>
      </div>
    );
  };

  const Builder = ({ data, onBack }) => {
    const [selected, setSelected] = useState(null);
    const [settings, setSettings] = useState(false);
    const allNodes = [data.trigger, ...data.nodes];
    const selectedNode = allNodes.find((n) => n.id === selected);
    const canvasScrollRef = React.useRef(null);

    /* Center the trigger node and pin to the top on first paint so the
       canvas always opens at the design-spec view. clientWidth can be 0
       on the first tick before flex layout settles, so retry via rAF. */
    React.useEffect(() => {
      const t = data.trigger;
      const PAD_LEFT = 32;
      const triggerCenterX = (t?.x || 0) + 320 / 2 + PAD_LEFT;
      let raf, retries = 0;
      const apply = () => {
        const e = canvasScrollRef.current;
        if (!e) return;
        if (e.clientWidth < 100 && retries < 30) {
          retries += 1; raf = requestAnimationFrame(apply); return;
        }
        e.scrollLeft = Math.max(0, triggerCenterX - e.clientWidth / 2);
        e.scrollTop = 0;
      };
      raf = requestAnimationFrame(apply);
      const onResize = () => apply();
      window.addEventListener("resize", onResize);
      return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", onResize); };
    }, [data.trigger]);

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%", background: "#fff" }}>
        <BuilderHeader onBack={onBack} onOpenSettings={() => setSettings(true)} />
        <div style={{ display: "flex", flex: 1, overflow: "hidden", position: "relative" }}>
          <PaletteSidebar />
          <div ref={canvasScrollRef} style={{ flex: 1, overflow: "auto", position: "relative", background: "#fafafa" }}>
            <div style={{ minWidth: 1280, padding: "32px 32px 64px", position: "relative" }}>
              <JourneyCanvas
                data={data}
                selectedId={selected}
                onSelect={(n) => setSelected(n.id)}
                onPaneClick={() => setSelected(null)}
              />
            </div>
          </div>
          {selectedNode && <ConfigPanel node={selectedNode} onClose={() => setSelected(null)} onDelete={() => setSelected(null)} />}
          <Minimap data={data} />
        </div>
        {settings && <SettingsModal onClose={() => setSettings(false)} />}
      </div>
    );
  };

  window.Builder = Builder;

  /* ===== marketing.jsx ===== */

  // Marketing sections: Triggers showcase + Journey Library
  // Linework illustrations, pink + cream + dark palette only

  const PINK = "#ED4D86";
  const PINK_TINT = "#fbcfe8";
  const PINK_SOFT = "#fdf2f8";
  const CREAM = "#fef9f4";
  const CREAM_BORDER = "#f1e9df";
  const INK = "#0f172a";
  const MUTE = "#94a3b8";

  // ===================== TRIGGER ILLUSTRATIONS =====================

  const BookingsArt = () => (
    <svg viewBox="0 0 360 200" style={{ width: "100%", height: "auto", display: "block" }}>
      {/* Mini calendar */}
      <g transform="translate(40 28)">
        <rect x="0" y="0" width="120" height="138" rx="10" fill="#fff" stroke={PINK_TINT} strokeWidth="1.4" />
        <rect x="0" y="0" width="120" height="24" rx="10" fill={INK} />
        <rect x="0" y="14" width="120" height="10" fill={INK} />
        <text x="60" y="16" textAnchor="middle" fill="#fff" fontSize="8" fontWeight="700" letterSpacing="2">OCTOBER 2025</text>
        {Array.from({ length: 7 }).map((_, c) =>
          Array.from({ length: 4 }).map((_, r) => (
            <rect key={`${c}-${r}`} x={6 + c * 16} y={32 + r * 22} width="13" height="18" rx="2" fill={CREAM} stroke={CREAM_BORDER} strokeWidth=".5" />
          ))
        )}
        <rect x="54" y="54" width="13" height="18" rx="2" fill={PINK} />
        <text x="60.5" y="67" textAnchor="middle" fill="#fff" fontSize="8" fontWeight="700">14</text>
      </g>
      {/* Dashed connector */}
      <path d="M168 82 L210 82" stroke={PINK} strokeWidth="1.2" strokeDasharray="3 3" fill="none" />
      {/* Confirmation card */}
      <g transform="translate(212 50)">
        <rect x="0" y="0" width="120" height="84" rx="8" fill="#fff" stroke={PINK_TINT} strokeWidth="1.4" />
        <rect x="10" y="12" width="50" height="5" rx="2" fill={INK} />
        <rect x="10" y="22" width="80" height="3" rx="1" fill="#cbd5e1" />
        <rect x="10" y="30" width="60" height="3" rx="1" fill="#cbd5e1" />
        <rect x="10" y="48" width="100" height="22" rx="6" fill={PINK_SOFT} stroke={PINK_TINT} strokeWidth=".8" />
        <circle cx="20" cy="59" r="3.5" fill={PINK} />
        <path d="M18 59 l1.5 1.5 l3 -3" stroke="#fff" strokeWidth="1.2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        <text x="28" y="62" fill={PINK} fontSize="8" fontWeight="700" letterSpacing=".5">CONFIRMED · BR-2487</text>
      </g>
    </svg>
  );

  const ConvoArt = () => (
    <svg viewBox="0 0 480 200" style={{ width: "100%", height: "auto", display: "block" }}>
      {/* SMS card - back */}
      <g transform="translate(34 28) rotate(-5 80 50)">
        <rect x="0" y="0" width="150" height="84" rx="10" fill="#fff" stroke={CREAM_BORDER} strokeWidth="1.2" />
        <text x="14" y="20" fill={MUTE} fontSize="8" fontWeight="700" letterSpacing="1.5">SMS · INBOUND</text>
        <rect x="14" y="30" width="120" height="34" rx="8" fill={CREAM} stroke={CREAM_BORDER} strokeWidth=".8" />
        <rect x="22" y="40" width="92" height="3" rx="1" fill="#cbd5e1" />
        <rect x="22" y="48" width="68" height="3" rx="1" fill="#cbd5e1" />
        <rect x="22" y="56" width="50" height="3" rx="1" fill="#cbd5e1" />
      </g>
      {/* Webchat card - middle */}
      <g transform="translate(150 50) rotate(-1 90 60)">
        <rect x="0" y="0" width="170" height="100" rx="10" fill="#fff" stroke={PINK_TINT} strokeWidth="1.4" />
        <rect x="0" y="0" width="170" height="20" rx="10" fill={INK} />
        <rect x="0" y="10" width="170" height="10" fill={INK} />
        <text x="14" y="13" fill="#fff" fontSize="8" fontWeight="700" letterSpacing="1">WEB CHAT · SUNSET HOTELS</text>
        <rect x="14" y="32" width="100" height="20" rx="8" fill={CREAM} />
        <text x="22" y="45" fill={INK} fontSize="8" fontWeight="500">Hi, do you have ocean view?</text>
        <rect x="44" y="58" width="116" height="32" rx="8" fill={PINK_SOFT} stroke={PINK_TINT} strokeWidth=".8" />
        <text x="52" y="71" fill={INK} fontSize="8" fontWeight="600">Yes, suite 412 has it.</text>
        <text x="52" y="82" fill={PINK} fontSize="7" fontWeight="600">Want me to hold it?</text>
      </g>
      {/* WhatsApp card - front */}
      <g transform="translate(290 86) rotate(4 90 60)">
        <rect x="0" y="0" width="172" height="106" rx="10" fill="#fff" stroke={PINK_TINT} strokeWidth="1.4" />
        <rect x="0" y="0" width="172" height="22" rx="10" fill={PINK} />
        <rect x="0" y="12" width="172" height="10" fill={PINK} />
        <circle cx="14" cy="11" r="4.5" fill="#fff" />
        <path d="M11.5 11 l2 2 l4 -4" stroke={PINK} strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        <text x="24" y="14" fill="#fff" fontSize="8" fontWeight="700" letterSpacing="1">WHATSAPP · ELENA M.</text>
        <rect x="14" y="34" width="118" height="20" rx="8" fill={CREAM} />
        <text x="22" y="47" fill={INK} fontSize="8" fontWeight="500">We miss you in Mallorca</text>
        <rect x="40" y="60" width="120" height="34" rx="8" fill={PINK_SOFT} stroke={PINK_TINT} strokeWidth=".8" />
        <text x="48" y="73" fill={INK} fontSize="8" fontWeight="600">Suites available in May?</text>
        <text x="48" y="86" fill={PINK} fontSize="7">Replied · 2 min ago</text>
        <circle cx="160" cy="96" r="6" fill={PINK} />
        <text x="160" y="99" textAnchor="middle" fill="#fff" fontSize="8" fontWeight="700">1</text>
      </g>
    </svg>
  );

  const ScheduledArt = () => (
    <svg viewBox="0 0 360 200" style={{ width: "100%", height: "auto", display: "block" }}>
      <g transform="translate(180 100)">
        <circle r="68" fill="#fff" stroke={PINK_TINT} strokeWidth="1.5" />
        <circle r="68" fill="none" stroke={PINK} strokeWidth="1" strokeDasharray="2 5" opacity=".5" />
        {Array.from({ length: 12 }).map((_, i) => {
          const a = (i / 12) * Math.PI * 2 - Math.PI / 2;
          const x1 = Math.cos(a) * 56, y1 = Math.sin(a) * 56;
          const x2 = Math.cos(a) * 62, y2 = Math.sin(a) * 62;
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={INK} strokeWidth={i % 3 === 0 ? 2 : .8} strokeLinecap="round" />;
        })}
        <line x1="0" y1="0" x2="0" y2="-38" stroke={INK} strokeWidth="2.4" strokeLinecap="round" />
        <line x1="0" y1="0" x2="32" y2="-16" stroke={PINK} strokeWidth="2.4" strokeLinecap="round" />
        <circle r="4" fill={INK} />
      </g>
      {/* Date chips */}
      <g transform="translate(20 22)">
        <rect x="0" y="0" width="76" height="30" rx="8" fill="#fff" stroke={PINK_TINT} strokeWidth="1.2" />
        <text x="10" y="13" fill={PINK} fontSize="7" fontWeight="700" letterSpacing="1">BIRTHDAY</text>
        <text x="10" y="24" fill={INK} fontSize="10" fontWeight="700">May 14</text>
      </g>
      <g transform="translate(264 22)">
        <rect x="0" y="0" width="80" height="30" rx="8" fill="#fff" stroke={PINK_TINT} strokeWidth="1.2" />
        <text x="10" y="13" fill={PINK} fontSize="7" fontWeight="700" letterSpacing="1">ANNIVERSARY</text>
        <text x="10" y="24" fill={INK} fontSize="10" fontWeight="700">1 year</text>
      </g>
      <g transform="translate(20 152)">
        <rect x="0" y="0" width="80" height="30" rx="8" fill="#fff" stroke={CREAM_BORDER} strokeWidth="1.2" />
        <text x="10" y="13" fill={MUTE} fontSize="7" fontWeight="700" letterSpacing="1">DORMANT</text>
        <text x="10" y="24" fill={INK} fontSize="10" fontWeight="700">90 days</text>
      </g>
      <g transform="translate(260 152)">
        <rect x="0" y="0" width="84" height="30" rx="8" fill="#fff" stroke={CREAM_BORDER} strokeWidth="1.2" />
        <text x="10" y="13" fill={MUTE} fontSize="7" fontWeight="700" letterSpacing="1">RECURRING</text>
        <text x="10" y="24" fill={INK} fontSize="10" fontWeight="700">Mondays</text>
      </g>
    </svg>
  );

  const OnPropertyArt = () => (
    <svg viewBox="0 0 360 200" style={{ width: "100%", height: "auto", display: "block" }}>
      {/* Hotel building outline */}
      <g transform="translate(120 22)">
        <rect x="0" y="14" width="120" height="148" rx="4" fill="#fff" stroke={PINK_TINT} strokeWidth="1.4" />
        <rect x="0" y="14" width="120" height="20" fill={INK} />
        <text x="60" y="27" textAnchor="middle" fill="#fff" fontSize="8" fontWeight="700" letterSpacing="2">SUNSET HOTEL</text>
        {[0, 1, 2, 3].map((r) =>
          [0, 1, 2, 3].map((c) => (
            <rect key={`${r}-${c}`} x={10 + c * 26} y={44 + r * 24} width="18" height="14" rx="2" fill={CREAM} stroke={CREAM_BORDER} strokeWidth=".6" />
          ))
        )}
        <rect x="36" y="68" width="18" height="14" rx="2" fill={PINK} />
        <rect x="50" y="146" width="20" height="16" fill={INK} />
      </g>
      {/* Keycard */}
      <g transform="translate(22 102) rotate(-10 50 22)">
        <rect x="0" y="0" width="84" height="44" rx="6" fill={INK} />
        <text x="10" y="16" fill={PINK} fontSize="6" fontWeight="700" letterSpacing="1.5">SUITE</text>
        <text x="10" y="34" fill="#fff" fontSize="14" fontWeight="700">412</text>
        <circle cx="70" cy="22" r="7" fill="none" stroke={PINK} strokeWidth="1" />
        <circle cx="70" cy="22" r="2.5" fill={PINK} />
      </g>
      {/* Check-in chip */}
      <g transform="translate(252 96)">
        <rect x="0" y="0" width="92" height="28" rx="14" fill="#fff" stroke={PINK_TINT} strokeWidth="1.2" />
        <circle cx="14" cy="14" r="5" fill={PINK} />
        <path d="M11.5 14 l1.6 1.6 l3.4 -3.4" stroke="#fff" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        <text x="24" y="18" fill={INK} fontSize="9" fontWeight="600">Checked in</text>
      </g>
    </svg>
  );

  const SegmentsArt = () => (
    <svg viewBox="0 0 360 200" style={{ width: "100%", height: "auto", display: "block" }}>
      <g transform="translate(180 100)">
        <circle cx="-38" cy="-10" r="44" fill={PINK_SOFT} stroke={PINK} strokeWidth="1.2" />
        <circle cx="38" cy="-10" r="44" fill={PINK_SOFT} stroke={PINK} strokeWidth="1.2" />
        <circle cx="0" cy="34" r="44" fill={PINK_SOFT} stroke={PINK} strokeWidth="1.2" />
        <text x="-50" y="-22" fill={PINK} fontSize="9" fontWeight="700" letterSpacing="1">VIP</text>
        <text x="36" y="-22" fill={PINK} fontSize="9" fontWeight="700" letterSpacing="1">REPEAT</text>
        <text x="-22" y="58" fill={PINK} fontSize="9" fontWeight="700" letterSpacing="1">DIRECT</text>
        {[
          [-44, -8], [-26, -2], [36, -2], [48, -18], [-4, 24], [10, 38],
          [0, 4], [-18, 14], [18, 14], [-34, 18], [32, 22],
        ].map(([x, y], i) => (
          <circle key={i} cx={x} cy={y} r="2.4" fill={INK} />
        ))}
      </g>
      <g transform="translate(20 30)">
        <rect x="0" y="0" width="78" height="26" rx="13" fill="#fff" stroke={PINK_TINT} strokeWidth="1.2" />
        <circle cx="14" cy="13" r="3" fill={PINK} />
        <text x="22" y="17" fill={INK} fontSize="9" fontWeight="600">+ Tagged</text>
      </g>
      <g transform="translate(262 30)">
        <rect x="0" y="0" width="82" height="26" rx="13" fill="#fff" stroke={PINK_TINT} strokeWidth="1.2" />
        <path d="M14 13 l-4 -4 l0 3 l-6 0 l0 2 l6 0 l0 3 z" fill={PINK} />
        <text x="22" y="17" fill={INK} fontSize="9" fontWeight="600">Entered</text>
      </g>
    </svg>
  );

  const ManualArt = () => (
    <svg viewBox="0 0 480 160" style={{ width: "100%", height: "auto", display: "block" }}>
      <g transform="translate(30 38)">
        <rect x="0" y="0" width="180" height="86" rx="10" fill="#fff" stroke={PINK_TINT} strokeWidth="1.4" />
        <text x="14" y="20" fill={PINK} fontSize="8" fontWeight="700" letterSpacing="1.5">MANUAL FIRE</text>
        <rect x="14" y="30" width="120" height="5" rx="2" fill={INK} />
        <rect x="14" y="42" width="86" height="3" rx="1" fill="#cbd5e1" />
        <rect x="14" y="54" width="98" height="22" rx="11" fill={INK} />
        <text x="63" y="68" textAnchor="middle" fill="#fff" fontSize="9" fontWeight="700">Run journey →</text>
      </g>
      {/* Connector */}
      <path d="M218 80 L260 80" stroke={PINK} strokeWidth="1.2" strokeDasharray="3 3" fill="none" />
      <g transform="translate(264 38)">
        <rect x="0" y="0" width="190" height="86" rx="10" fill={INK} />
        <circle cx="14" cy="14" r="3" fill={PINK} />
        <circle cx="24" cy="14" r="3" fill={PINK_TINT} />
        <circle cx="34" cy="14" r="3" fill="#475569" />
        <text x="14" y="38" fill={MUTE} fontSize="8" fontFamily="monospace">POST /v1/triggers</text>
        <text x="14" y="52" fill={PINK} fontSize="8" fontFamily="monospace">{"{ \"event\": \"booking_paid\","}</text>
        <text x="14" y="64" fill="#ffe5ed" fontSize="8" fontFamily="monospace">{"  \"contact_id\": \"c_8421\" }"}</text>
        <text x="14" y="78" fill={MUTE} fontSize="8" fontFamily="monospace">→ 200 OK</text>
      </g>
    </svg>
  );

  // ===================== TRIGGER CARDS =====================

  const TRIGGER_CARDS = [
    {
      n: "01", eyebrow: "PMS · CRS · CHANNEL MGR", title: "Reservations",
      description: "Hotel-native triggers from your PMS, the moment they happen.",
      bullets: [
        "Created, updated, cancelled, no-show, folio paid.",
        "Per-property and per-channel, OTA, direct, tour operator.",
      ],
      quote: "\"A new direct booking just dropped. Fire the upgrade upsell.\"",
      art: BookingsArt, span: 2,
    },
    {
      n: "02", eyebrow: "WHATSAPP · WEB · SMS · EMAIL", title: "Conversations",
      description: "Every reply, every chat, across every channel becomes a trigger.",
      bullets: [
        "Webchat started or finished, WhatsApp replied, SMS in, email opened.",
        "Sentiment, intent and language extracted on the fly for routing.",
      ],
      quote: "\"Guest replied on WhatsApp at 11pm. Handoff to the AI concierge.\"",
      art: ConvoArt, span: 4,
    },
    {
      n: "03", eyebrow: "FRONT DESK · OPERATIONS", title: "On-Property",
      description: "What happens at the front desk and around the building.",
      bullets: [
        "Check-in, check-out, room assigned, room ready, late checkout.",
        "Folio events, mini-bar, spa booking, restaurant reservation.",
      ],
      quote: "\"Suite 412 just checked in. Send the welcome WhatsApp.\"",
      art: OnPropertyArt, span: 2,
    },
    {
      n: "04", eyebrow: "TIME · DATE · CADENCE", title: "Scheduled",
      description: "Time itself becomes a trigger.",
      bullets: [
        "Birthday, anniversary, specific date, dormancy threshold.",
        "Cron-style cadences: daily, weekly, monthly, quarterly.",
      ],
      quote: "\"Every Monday at 9am, run the win-back over dormant guests.\"",
      art: ScheduledArt, span: 2,
    },
    {
      n: "05", eyebrow: "CRM · SEGMENTS · TAGS", title: "Profile changes",
      description: "When a contact's profile changes, the journey reacts.",
      bullets: [
        "Segment entered, tag added, contact subscribed, journey completed.",
        "Reacts to any custom field on the contact record.",
      ],
      quote: "\"Tagged as VIP for the first time. Start the recognition flow.\"",
      art: SegmentsArt, span: 2,
    },
    {
      n: "06", eyebrow: "STAFF ACTIONS · INTEGRATIONS", title: "Manual & Custom",
      description: "For everything else, staff actions and your own external systems.",
      bullets: [
        "Manual fire from any contact list, front desk and revenue managers.",
        "Custom API events from your PMS, POS, loyalty platform or internal tools.",
      ],
      quote: "\"Webhook from the spa: massage booked. Trigger the upsell sequence.\"",
      art: ManualArt, span: 6, horizontal: true,
    },
  ];

  const TriggerCard = ({ data }) => {
    const Art = data.art;
    return (
      <div className={`jrn-trigger-card${data.horizontal ? " jrn-trigger-card-horizontal" : ""}`} style={{
        gridColumn: `span ${data.span}`,
        background: "#fff",
        border: `1px solid ${CREAM_BORDER}`,
        borderRadius: 18,
        padding: data.horizontal ? 28 : 24,
        display: data.horizontal ? "grid" : "flex",
        gridTemplateColumns: data.horizontal ? "minmax(0, 520px) 1fr" : undefined,
        gap: data.horizontal ? 36 : 18,
        flexDirection: data.horizontal ? undefined : "column",
        alignItems: data.horizontal ? "center" : undefined,
      }}>
        <div style={{
          background: CREAM, border: `1px solid ${CREAM_BORDER}`,
          borderRadius: 12, padding: 12,
          height: data.horizontal ? 150 : 156,
          display: "grid", placeItems: "center",
          order: data.horizontal ? 2 : undefined,
        }}>
          <Art />
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".18em", color: MUTE }}>
            <span style={{ color: PINK }}>{data.n}</span> &nbsp;/&nbsp; {data.eyebrow}
          </div>
          <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: data.horizontal ? "clamp(20px, 2.6vw, 36px)" : "clamp(19px, 2.2vw, 30px)", fontWeight: 400, color: INK, margin: 0, lineHeight: 1.05, letterSpacing: "-0.01em" }}>
            {data.title}
          </h3>
          <p style={{ margin: "2px 0 4px", fontSize: 14.5, lineHeight: 1.5, color: "#475569" }}>
            {data.description}
          </p>
          <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 8 }}>
            {data.bullets.map((b, i) => (
              <li key={i} style={{ display: "flex", gap: 10, fontSize: 13.5, lineHeight: 1.5, color: "#334155" }}>
                <span style={{ color: PINK, fontWeight: 700, flexShrink: 0 }}>•</span>
                <span>{b}</span>
              </li>
            ))}
          </ul>
          <div style={{ marginTop: 10, paddingTop: 14, borderTop: `1px dashed ${CREAM_BORDER}`, fontSize: 13, fontStyle: "italic", color: MUTE, fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontWeight: 400 }}>
            {data.quote}
          </div>
        </div>
      </div>
    );
  };

  const TriggersSection = () => (
    <section style={{ background: CREAM, padding: "100px 24px 80px" }}>
      <div style={{ maxWidth: 1320, margin: "0 auto" }}>
        <div style={{ maxWidth: 820, margin: "0 0 64px" }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: ".24em", color: PINK, marginBottom: 22 }}>
            30+ TRIGGERS · 6 CATEGORIES
          </div>
          <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(28px, 4.6vw, 64px)", lineHeight: 1.02, fontWeight: 400, color: INK, margin: "0 0 4px", letterSpacing: "-0.01em" }}>
            Anything can start <span style={{ fontStyle: "italic", color: PINK }}>a journey.</span>
          </h2>
          <p style={{ marginTop: 26, fontSize: 17, lineHeight: 1.55, color: "#475569" }}>
            A reservation, a reply, a returning guest, a Tuesday at 9am. GuestMaker listens to your PMS, your inbox, your chatbot and your calendar, then sets the right journey in motion.
          </p>
        </div>
        <div className="jrn-triggers-grid" style={{ display: "grid", gridTemplateColumns: "repeat(6, minmax(0, 1fr))", gap: 18 }}>
          {TRIGGER_CARDS.map((c) => <TriggerCard key={c.n} data={c} />)}
        </div>
      </div>
      <style>{`
        /* Six-column grid with card spans of 2/4/2/2/2/6 has no floor: at
           mobile widths a span-2 card gets ~33% of the viewport, wrapping
           "Reservations" mid-word and squeezing every card's art+copy into
           illegible slivers — minmax(0,1fr) stops it OVERFLOWING but does
           nothing for READABILITY. Stack to one column below 860px. */
        @media (max-width: 860px) {
          .jrn-triggers-grid { grid-template-columns: minmax(0, 1fr) !important; }
          .jrn-trigger-card { grid-column: span 1 !important; }
          .jrn-trigger-card-horizontal { grid-template-columns: minmax(0, 1fr) !important; }
        }
      `}</style>
    </section>
  );

  // ===================== JOURNEY LIBRARY =====================

  const LIBRARY_CATEGORIES = [
    {
      name: "Pre-Stay",
      sub: "Engage guests from booking to arrival. Confirmations, upsells, pre-arrival info.",
      count: 12,
      samples: ["Booking confirmation", "Pre-arrival info", "Upgrade upsell", "Airport transfer", "Special requests"],
      art: "presty",
    },
    {
      name: "During Stay",
      sub: "Enhance the on-property experience. Welcome messages, check-in flows, concierge.",
      count: 12,
      samples: ["Welcome WhatsApp", "Check-in flow", "Concierge handoff", "Mid-stay survey", "Late checkout offer"],
      art: "during",
    },
    {
      name: "Post-Stay",
      sub: "Turn guests into advocates. Feedback, reviews, thank-you messages.",
      count: 12,
      samples: ["Thank-you note", "TripAdvisor ask", "NPS survey", "Lost & found", "Photo memories"],
      art: "post",
    },
    {
      name: "Loyalty & Retention",
      sub: "Build lasting relationships. Enrollment, tier upgrades, points, birthday rewards.",
      count: 12,
      samples: ["Loyalty enrollment", "Tier upgrade", "Points expiring", "Birthday reward", "VIP recognition"],
      art: "loyalty",
    },
    {
      name: "Re-engagement",
      sub: "Win back dormant guests. Reactivation campaigns, win-back sequences.",
      count: 12,
      samples: ["365-day win-back", "Dormant 90d", "Cancelled rebound", "Seasonal nudge", "Direct booking incentive"],
      art: "winback",
    },
  ];

  const LibraryArt = ({ kind }) => {
    const common = { width: 96, height: 96, viewBox: "0 0 96 96", style: { display: "block" } };
    if (kind === "presty") {
      return (
        <svg {...common}>
          <rect x="14" y="22" width="56" height="42" rx="8" fill="#fff" stroke={PINK} strokeWidth="1.5" />
          <path d="M14 30 l28 18 l28 -18" stroke={PINK} strokeWidth="1.5" fill="none" />
          <circle cx="74" cy="22" r="10" fill={PINK} />
          <path d="M70 22 l3 3 l5 -6" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      );
    }
    if (kind === "during") {
      return (
        <svg {...common}>
          <rect x="20" y="14" width="56" height="68" rx="6" fill="#fff" stroke={PINK} strokeWidth="1.5" />
          <rect x="20" y="14" width="56" height="14" fill={PINK} />
          <rect x="28" y="36" width="20" height="14" rx="2" fill={PINK_SOFT} />
          <rect x="52" y="36" width="20" height="14" rx="2" fill={PINK_SOFT} />
          <rect x="28" y="56" width="20" height="14" rx="2" fill={PINK} />
          <rect x="52" y="56" width="20" height="14" rx="2" fill={PINK_SOFT} />
        </svg>
      );
    }
    if (kind === "post") {
      return (
        <svg {...common}>
          <path d="M48 22 l6 14 l16 2 l-12 11 l4 16 l-14 -8 l-14 8 l4 -16 l-12 -11 l16 -2 z" fill={PINK_SOFT} stroke={PINK} strokeWidth="1.5" strokeLinejoin="round" />
          <circle cx="48" cy="48" r="4" fill={PINK} />
        </svg>
      );
    }
    if (kind === "loyalty") {
      return (
        <svg {...common}>
          <circle cx="48" cy="44" r="22" fill="#fff" stroke={PINK} strokeWidth="1.5" />
          <circle cx="48" cy="44" r="14" fill={PINK_SOFT} />
          <path d="M48 32 l3 7 l8 1 l-6 5 l2 8 l-7 -4 l-7 4 l2 -8 l-6 -5 l8 -1 z" fill={PINK} />
          <rect x="40" y="68" width="16" height="14" rx="3" fill={PINK_TINT} />
        </svg>
      );
    }
    return (
      <svg {...common}>
        <path d="M22 48 a26 26 0 1 1 26 26" stroke={PINK} strokeWidth="2.5" fill="none" strokeLinecap="round" />
        <path d="M16 42 l6 6 l6 -6" stroke={PINK} strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx="58" cy="62" r="6" fill={PINK} />
        <path d="M55 62 l2 2 l4 -4" stroke="#fff" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    );
  };

  const LibraryCard = ({ data }) => (
    <div style={{
      background: "#fff", border: `1px solid ${CREAM_BORDER}`,
      borderRadius: 20, padding: 28,
      display: "flex", flexDirection: "column", gap: 18,
      position: "relative", overflow: "hidden", minHeight: 320,
    }}>
      <div style={{ position: "absolute", top: 24, right: 24 }}>
        <LibraryArt kind={data.art} />
      </div>
      <div style={{
        alignSelf: "flex-start",
        display: "inline-flex", alignItems: "center", gap: 8,
        background: CREAM, border: `1px solid ${PINK_TINT}`,
        borderRadius: 99, padding: "6px 12px",
        fontSize: 12, fontWeight: 600, color: PINK, letterSpacing: ".02em",
      }}>
        <span style={{ width: 6, height: 6, borderRadius: 99, background: PINK }} />
        {data.count} journeys
      </div>
      <div style={{ marginTop: "auto" }}>
        <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(20px, 2.6vw, 36px)", fontWeight: 400, color: INK, margin: "0 0 8px", lineHeight: 1.05, letterSpacing: "-0.01em" }}>
          {data.name}
        </h3>
        <p style={{ margin: 0, fontSize: 14, lineHeight: 1.55, color: "#64748b", maxWidth: 460 }}>
          {data.sub}
        </p>
        <div style={{ marginTop: 18, display: "flex", flexWrap: "wrap", gap: 6 }}>
          {data.samples.map((s) => (
            <span key={s} style={{
              background: CREAM, border: `1px solid ${CREAM_BORDER}`,
              color: "#334155", fontSize: 12, fontWeight: 500,
              padding: "5px 10px", borderRadius: 99,
            }}>{s}</span>
          ))}
        </div>
      </div>
    </div>
  );

  const LibrarySection = () => (
    <section style={{ background: INK, padding: "100px 24px 100px", position: "relative", overflow: "hidden" }}>
      <div style={{
        position: "absolute", inset: 0,
        backgroundImage: `radial-gradient(circle, ${PINK}14 1px, transparent 1px)`,
        backgroundSize: "32px 32px", opacity: .5, pointerEvents: "none",
      }} />
      <div style={{ maxWidth: 1320, margin: "0 auto", position: "relative" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 48, marginBottom: 64, flexWrap: "wrap" }}>
          <div style={{ maxWidth: 720 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: ".24em", color: PINK, marginBottom: 22 }}>
              THE JOURNEY LIBRARY
            </div>
            <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(28px, 4.6vw, 64px)", lineHeight: 1.02, fontWeight: 400, color: CREAM, margin: "0 0 4px", letterSpacing: "-0.01em" }}>
              60 ready-made journeys,
            </h2>
            <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(28px, 4.6vw, 64px)", lineHeight: 1.02, fontWeight: 400, fontStyle: "italic", color: PINK, margin: 0, letterSpacing: "-0.01em" }}>
              growing weekly.
            </h2>
            <p style={{ marginTop: 26, fontSize: 17, lineHeight: 1.55, color: "#cbd5e1", maxWidth: 580 }}>
              Pre-built journeys designed for hotels, ready to use. Pick one, swap the copy for your brand voice, set it live in an afternoon.
            </p>
          </div>
          <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 16 }}>
            <div style={{ textAlign: "right" }}>
              <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 88, lineHeight: 1, fontWeight: 400, color: CREAM, letterSpacing: "-0.02em" }}>
                60<span style={{ color: PINK }}>+</span>
              </div>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".18em", color: MUTE, marginTop: 4 }}>
                TEMPLATES · 5 CATEGORIES
              </div>
            </div>
            <button style={{
              background: CREAM, color: INK, border: "none",
              borderRadius: 99, padding: "13px 22px", fontSize: 14, fontWeight: 600,
              cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8,
            }}>
              View all journeys <span>→</span>
            </button>
          </div>
        </div>
        <div className="jrn-library-grid" style={{ display: "grid", gridTemplateColumns: "repeat(6, minmax(0, 1fr))", gap: 18 }}>
          <div className="jrn-library-card" style={{ gridColumn: "span 3" }}><LibraryCard data={LIBRARY_CATEGORIES[0]} /></div>
          <div className="jrn-library-card" style={{ gridColumn: "span 3" }}><LibraryCard data={LIBRARY_CATEGORIES[1]} /></div>
          <div className="jrn-library-card" style={{ gridColumn: "span 2" }}><LibraryCard data={LIBRARY_CATEGORIES[2]} /></div>
          <div className="jrn-library-card" style={{ gridColumn: "span 2" }}><LibraryCard data={LIBRARY_CATEGORIES[3]} /></div>
          <div className="jrn-library-card" style={{ gridColumn: "span 2" }}><LibraryCard data={LIBRARY_CATEGORIES[4]} /></div>
        </div>
        <style>{`
          /* Same shape as .jrn-triggers-grid above: a 6-col grid with 3/3/2/2/2
             spans has no floor, so the bottom row's span-2 cards get ~33% of
             the viewport on mobile and truncate ("Loyalty & Retention" ->
             "Loyalt/Retent", "12 journeys" -> "12 journey"). Stack to 1 column. */
          @media (max-width: 860px) {
            .jrn-library-grid { grid-template-columns: minmax(0, 1fr) !important; }
            .jrn-library-card { grid-column: span 1 !important; }
          }
        `}</style>
        <div style={{
          marginTop: 56, textAlign: "center",
          fontSize: 13, color: MUTE,
          display: "flex", alignItems: "center", justifyContent: "center", gap: 14,
        }}>
          <span style={{ width: 40, height: 1, background: "#334155" }} />
          New templates published every two weeks. Suggest one and we&rsquo;ll build it.
          <span style={{ width: 40, height: 1, background: "#334155" }} />
        </div>
      </div>
    </section>
  );

  window.TriggersSection = TriggersSection;
  window.LibrarySection = LibrarySection;

  /* ===== email.jsx ===== */

  // Email marketing sections: Gallery, AI Studio, Import, Campaign Audit
  // Matches the pink/cream/dark aesthetic from marketing.jsx

  const E_PINK = "#ED4D86";
  const E_PINK_TINT = "#fbcfe8";
  const E_PINK_SOFT = "#fdf2f8";
  const E_CREAM = "#fef9f4";
  const E_CREAM_BORDER = "#f1e9df";
  const E_INK = "#0f172a";
  const E_MUTE = "#94a3b8";

  const { useState: eUseState, useEffect: eUseEffect, useRef: eUseRef } = React;

  // ============== HOTEL IMAGES (real unsplash) ==============
  const HOTEL_IMG = {
    pool: "https://images.unsplash.com/photo-1571896349842-33c89424de2d?w=900&q=80&auto=format&fit=crop",
    villa: "https://images.unsplash.com/photo-1582719508461-905c673771fd?w=900&q=80&auto=format&fit=crop",
    beach: "https://images.unsplash.com/photo-1566073771259-6a8506099945?w=900&q=80&auto=format&fit=crop",
    sunset: "https://images.unsplash.com/photo-1542314831-068cd1dbfeeb?w=900&q=80&auto=format&fit=crop",
    bungalow: "https://images.unsplash.com/photo-1519449556851-5720b33024e7?w=900&q=80&auto=format&fit=crop",
    spa: "https://images.unsplash.com/photo-1540541338287-41700207dee6?w=900&q=80&auto=format&fit=crop",
  };

  // ============== USE IN VIEW HOOK ==============
  const useInView = (threshold = 0.2) => {
    const ref = eUseRef(null);
    const [seen, setSeen] = eUseState(false);
    eUseEffect(() => {
      if (!ref.current) return;
      const ob = new IntersectionObserver(
        ([e]) => { if (e.isIntersecting) { setSeen(true); ob.disconnect(); } },
        { threshold }
      );
      ob.observe(ref.current);
      return () => ob.disconnect();
    }, []);
    return [ref, seen];
  };

  // ============== SCALE FRAME ==============
  // Shrinks a fixed-canvas product mockup to fit any container width,
  // preserving its exact desktop composition instead of restacking it into a
  // mobile-native column. Restacking a product screenshot produces a different,
  // worse-looking UI that no longer reads as "the real product"; scaling keeps
  // it recognisable, just smaller — the same technique memory's hero diagram
  // has always used. The wrapper is sized to the SCALED height because
  // transform does not affect layout: without it the element would still
  // reserve its full native height and leave a large gap below.
  // NOTE: uses the plain useRef/useState/useEffect bindings from the top of
  // this file, not the eUse* aliases below — the react-hooks lint rule only
  // recognises a hook by NAME, so an aliased eUseEffect reads as an ordinary
  // function call and every ref access inside it is flagged as render-phase.
  const ScaleFrame = ({ nativeWidth, children, style }) => {
    const wrapRef = useRef(null);
    const innerRef = useRef(null);
    const [scale, setScale] = useState(1);
    const [nativeHeight, setNativeHeight] = useState(0);

    useEffect(() => {
      const wrap = wrapRef.current;
      if (!wrap) return;
      const ro = new ResizeObserver((entries) => {
        const w = entries[0].contentRect.width;
        if (w > 0) setScale(Math.min(1, w / nativeWidth));
      });
      ro.observe(wrap);
      return () => ro.disconnect();
    }, [nativeWidth]);

    useEffect(() => {
      const inner = innerRef.current;
      if (!inner) return;
      const ro = new ResizeObserver((entries) => {
        const h = entries[0].contentRect.height;
        if (h > 0) setNativeHeight(h);
      });
      ro.observe(inner);
      return () => ro.disconnect();
    }, []);

    return (
      <div ref={wrapRef} style={{ width: "100%", height: nativeHeight ? nativeHeight * scale : undefined, overflow: "hidden", ...style }}>
        <div ref={innerRef} style={{ width: nativeWidth, transform: `scale(${scale})`, transformOrigin: "top left" }}>
          {children}
        </div>
      </div>
    );
  };

  // ============== EMAIL INTRO ==============
  const EmailIntro = () => (
    <section style={{ background: E_CREAM, padding: "120px 24px 40px", textAlign: "center" }}>
      <div style={{ maxWidth: 880, margin: "0 auto" }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 22, display: "inline-flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 28, height: 1.5, background: E_PINK }} /> EMAIL · TEMPLATES &amp; CAMPAIGNS <span style={{ width: 28, height: 1.5, background: E_PINK }} />
        </div>
        <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(30px, 5.4vw, 76px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
          Beautiful emails,
        </h2>
        <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(30px, 5.4vw, 76px)", lineHeight: 1.0, fontWeight: 400, fontStyle: "italic", color: E_PINK, margin: "0 0 24px", letterSpacing: "-0.01em" }}>
          in any language, in minutes.
        </h2>
        <p style={{ fontSize: 17, lineHeight: 1.55, color: "#475569", maxWidth: 720, margin: "0 auto" }}>
          90 hospitality-grade templates out of the box, an AI studio that generates editable HTML in under two minutes, one-click multilingual translation, and a campaign wizard that audits every send before you press the button.
        </p>
      </div>
    </section>
  );

  // ============== TEMPLATE THUMBNAIL ==============
  const TemplateThumb = ({ kind, hotel, headline, accent }) => {
    const c = accent || E_PINK;
    if (kind === "image") {
      return (
        <div style={{ position: "relative", width: "100%", height: "100%", background: E_INK, overflow: "hidden" }}>
          <img src={hotel} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", filter: "brightness(0.85)" }} loading="lazy" />
          <div style={{ position: "absolute", inset: 0, padding: "10px 12px", display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
            <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 9, color: "#fff", letterSpacing: "0.2em", textShadow: "0 1px 4px rgba(0,0,0,.5)" }}>
              {"{{hotel_name}}"}
            </div>
            <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 14, color: "#fff", fontStyle: "italic", textShadow: "0 1px 6px rgba(0,0,0,.6)", lineHeight: 1.05 }}>
              {headline}
            </div>
          </div>
        </div>
      );
    }
    if (kind === "dark") {
      return (
        <div style={{ width: "100%", height: "100%", background: E_INK, padding: "12px 10px", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8 }}>
          <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 8, color: c, letterSpacing: "0.2em" }}>{"{{hotel_name}}"}</div>
          <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 13, color: "#fff", fontStyle: "italic", lineHeight: 1.05, textAlign: "center" }}>{headline}</div>
          <div style={{ width: 28, height: 2, background: c, marginTop: 2 }} />
          <div style={{ width: "70%", height: 2, background: "#475569" }} />
          <div style={{ width: "55%", height: 2, background: "#334155" }} />
        </div>
      );
    }
    // light
    return (
      <div style={{ width: "100%", height: "100%", background: "#fff", padding: "12px 10px", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8 }}>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 8, color: c, letterSpacing: "0.2em" }}>{"{{hotel_name}}"}</div>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 13, color: E_INK, fontStyle: "italic", lineHeight: 1.05, textAlign: "center" }}>{headline}</div>
        <div style={{ width: 28, height: 2, background: c, marginTop: 2 }} />
        <div style={{ width: "70%", height: 2, background: "#e2e8f0" }} />
        <div style={{ width: "55%", height: 2, background: "#e2e8f0" }} />
      </div>
    );
  };

  // ============== GALLERY ARTIFACT ==============
  const GALLERY_TEMPLATES = [
    { name: "Birthday Greeting (colorful)", folder: "Post-Stay", tags: ["birthday", "anniversary"], kind: "light", headline: "Happy Birthday, {{first_name}}!", accent: "#dc2626" },
    { name: "Birthday Greeting (dark)", folder: "Post-Stay", tags: ["birthday"], kind: "dark", headline: "Happy Birthday, {{first_name}}!", accent: "#f59e0b" },
    { name: "Birthday Greeting (light)", folder: "Post-Stay", tags: ["birthday"], kind: "light", headline: "Happy Birthday, {{first_name}}!", accent: "#0ea5e9" },
    { name: "Loyalty Enrollment", folder: "Loyalty", tags: ["loyalty"], kind: "image", hotel: HOTEL_IMG.pool, headline: "Join {{hotel_name}} Rewards" },
    { name: "Loyalty Enrollment (dark)", folder: "Loyalty", tags: ["loyalty"], kind: "image", hotel: HOTEL_IMG.sunset, headline: "Join {{hotel_name}} Rewards" },
    { name: "Re-Booking Incentive", folder: "Re-engagement", tags: ["rebooking"], kind: "image", hotel: HOTEL_IMG.bungalow, headline: "Your Next Escape Awaits" },
    { name: "Re-Booking Incentive (dark)", folder: "Re-engagement", tags: ["rebooking"], kind: "image", hotel: HOTEL_IMG.beach, headline: "Your Next Escape Awaits" },
    { name: "Re-Booking Incentive (light)", folder: "Re-engagement", tags: ["rebooking"], kind: "image", hotel: HOTEL_IMG.villa, headline: "Your Next Escape Awaits" },
    { name: "Thank You & Review", folder: "Post-Stay", tags: ["thank-you"], kind: "image", hotel: HOTEL_IMG.pool, headline: "Thank You, {{first_name}}" },
    { name: "Thank You & Review (dark)", folder: "Post-Stay", tags: ["thank-you"], kind: "image", hotel: HOTEL_IMG.sunset, headline: "Thank You, {{first_name}}" },
    { name: "Thank You & Review (light)", folder: "Post-Stay", tags: ["thank-you"], kind: "image", hotel: HOTEL_IMG.spa, headline: "Thank You, {{first_name}}" },
    { name: "Pre-Arrival Welcome", folder: "Pre-Stay", tags: ["pre-stay"], kind: "image", hotel: HOTEL_IMG.villa, headline: "We can&rsquo;t wait, {{first_name}}" },
  ];

  const FOLDERS = [
    { name: "All Templates", count: 90, active: false },
    { name: "In-Stay", count: 12 },
    { name: "Loyalty", count: 15 },
    { name: "Newsletter", count: 9 },
    { name: "Post-Stay", count: 12, active: true },
    { name: "Pre-Stay", count: 15 },
    { name: "Promotional", count: 24 },
    { name: "Re-engagement", count: 3 },
  ];

  const TRANSLATE_LANGS = [
    { code: "ES", name: "Spanish", headline: "Tu próxima escapada te espera" },
    { code: "FR", name: "French", headline: "Votre prochaine évasion" },
    { code: "DE", name: "German", headline: "Ihre nächste Auszeit wartet" },
    { code: "IT", name: "Italian", headline: "La tua prossima fuga" },
    { code: "PT", name: "Portuguese", headline: "A sua próxima escapada" },
    { code: "NL", name: "Dutch", headline: "Je volgende ontsnapping" },
    { code: "RU", name: "Russian", headline: "Ваш следующий отдых" },
  ];

  // Phases: 0 idle, 1 modal open, 2 picking ES, 3 picking DE, 4 picking IT, 5 click translate, 6 translating, 7 done (variants visible), then loop
  const GalleryArtifact = () => {
    const [ref, seen] = useInView(0.15);
    const [phase, setPhase] = eUseState(0);

    eUseEffect(() => {
      if (!seen) return;
      let cancelled = false;
      const wait = (ms) => new Promise((r) => setTimeout(r, ms));
      const run = async () => {
        while (!cancelled) {
          setPhase(0); await wait(1200); if (cancelled) return;
          setPhase(1); await wait(1400); if (cancelled) return;  // modal open
          setPhase(2); await wait(1100); if (cancelled) return;  // ES checked
          setPhase(3); await wait(1100); if (cancelled) return;  // DE checked
          setPhase(4); await wait(1100); if (cancelled) return;  // IT checked
          setPhase(5); await wait(1300); if (cancelled) return;  // hover translate btn
          setPhase(6); await wait(1800); if (cancelled) return;  // translating in modal
          setPhase(7); await wait(4200); if (cancelled) return;  // placeholder cards w/ progress
          setPhase(8); await wait(5500); if (cancelled) return;  // ready cards
        }
      };
      run();
      return () => { cancelled = true; };
    }, [seen]);

    const selected = phase >= 2 && phase <= 8
      ? ["ES", phase >= 3 ? "DE" : null, phase >= 4 ? "IT" : null].filter(Boolean)
      : [];
    const showModal = phase >= 1 && phase <= 6;
    const translating = phase === 7;
    const showVariants = phase === 7 || phase === 8;
    const variantsReady = phase === 8;

    return (
      <section ref={ref} style={{ background: E_CREAM, padding: "60px 24px 80px" }}>
        <div style={{ maxWidth: 1480, margin: "0 auto" }}>
          <div className="jrn-artifact-header" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", alignItems: "end", gap: 48, marginBottom: 36 }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 18 }}>
                01 · GUESTMAKER GALLERY
              </div>
              <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(24px, 4vw, 56px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
                90 templates, <span style={{ fontStyle: "italic", color: E_PINK }}>26 languages,</span> one click.
              </h3>
            </div>
            <div style={{ paddingBottom: 8 }}>
              <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", margin: 0, maxWidth: 540 }}>
                The Guestmaker Gallery ships with hospitality-grade templates across pre-stay, in-stay, post-stay, loyalty, and promotions. Translate any template into 26 languages in one click, every variant stays in sync with the original.
              </p>
            </div>
          </div>

          {/* Artifact frame */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{
            background: "#fff", borderRadius: 18,
            boxShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
            border: "1px solid rgba(15,23,42,.06)", overflow: "hidden",
          }}>
            {/* Top bar */}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 22px", borderBottom: "1px solid #f1f5f9" }}>
              <div style={{ fontSize: 12, color: "#64748b" }}>
                TEMPLATES <span style={{ margin: "0 6px", color: "#cbd5e1" }}>›</span>
                <span style={{ color: E_INK, fontWeight: 600 }}>EMAIL</span>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                <button style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "6px 12px", fontSize: 12, color: "#475569", display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
                  <Icon name="mail" size={13} /> Import
                </button>
                <button style={{ background: E_INK, color: "#fff", border: "none", borderRadius: 8, padding: "7px 14px", fontSize: 12, fontWeight: 600, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6 }}>
                  <Icon name="plus" size={13} /> Create Template
                </button>
              </div>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "230px 1fr", minHeight: 580 }}>
              {/* Folders */}
              <div style={{ borderRight: "1px solid #f1f5f9", padding: "16px 14px" }}>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".18em", color: "#94a3b8", padding: "0 8px 10px" }}>FOLDERS</div>
                {FOLDERS.map((f) => (
                  <div key={f.name} style={{
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    padding: "8px 10px", borderRadius: 8, marginBottom: 2,
                    background: f.active ? E_PINK_SOFT : "transparent",
                    color: f.active ? E_PINK : "#334155",
                    fontSize: 13, fontWeight: f.active ? 600 : 500, cursor: "pointer",
                  }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                      {f.name === "All Templates" ? "📂" : "📁"} {f.name}
                    </span>
                    <span style={{ fontSize: 11, color: f.active ? E_PINK : "#94a3b8", fontWeight: 600 }}>{f.count}</span>
                  </div>
                ))}
                <div style={{ marginTop: 12, padding: "10px 8px", background: "linear-gradient(135deg," + E_PINK_SOFT + " 0%, #fff 100%)", border: "1px dashed " + E_PINK_TINT, borderRadius: 10 }}>
                  <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".15em", color: E_PINK, marginBottom: 4 }}>✨ AI TRANSLATE</div>
                  <div style={{ fontSize: 11.5, color: "#475569", lineHeight: 1.4 }}>Spanish, French, German, Italian, 26 languages, one click.</div>
                </div>
              </div>

              {/* Right side */}
              <div style={{ padding: "18px 22px", position: "relative" }}>
                {/* Tabs */}
                <div style={{ display: "flex", gap: 18, fontSize: 12.5, color: "#64748b", marginBottom: 16, borderBottom: "1px solid #f1f5f9", paddingBottom: 10 }}>
                  <span style={{ color: E_INK, fontWeight: 600, position: "relative" }}>
                    All
                    <span style={{ position: "absolute", left: 0, right: 0, bottom: -11, height: 2, background: E_INK }} />
                  </span>
                  {["Promotional", "Transactional", "Newsletter", "Welcome", "Re-engagement"].map((t) => (
                    <span key={t} style={{ cursor: "pointer" }}>{t}</span>
                  ))}
                </div>

                {/* Action toolbar */}
                <div style={{
                  marginBottom: 14, padding: "10px 14px", background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 10,
                  display: "flex", alignItems: "center", justifyContent: "space-between",
                }}>
                  <div style={{ fontSize: 12, color: "#64748b" }}>
                    <span style={{ fontWeight: 700, color: E_INK }}>1 selected</span> &middot; Early Bird (dark)
                  </div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 6, padding: "5px 10px", fontSize: 11, color: "#475569" }}>Set Active</button>
                    <button style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 6, padding: "5px 10px", fontSize: 11, color: "#475569" }}>Move</button>
                    <button style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 6, padding: "5px 10px", fontSize: 11, color: "#475569" }}>Add tags</button>
                    <button style={{
                      background: showVariants ? "#fff" : E_PINK, color: showVariants ? E_PINK : "#fff",
                      border: showVariants ? `1px solid ${E_PINK_TINT}` : "none",
                      borderRadius: 6, padding: "5px 12px", fontSize: 11, fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 5,
                    }}>
                      <Icon name="sparkles" size={11} color={showVariants ? E_PINK : "#fff"} /> Translate
                    </button>
                  </div>
                </div>

                {/* Grid */}
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, position: "relative" }}>
                  {/* Translated variant cards (appear top-left) */}
                  {showVariants && ["ES", "DE", "IT"].map((sel, vi) => {
                    const variant = TRANSLATE_LANGS.find((l) => l.code === sel);
                    const ready = variantsReady; // simple binary; per-card stagger via CSS animation-delay
                    return (
                      <div key={"v"+vi} style={{
                        border: `1px solid ${E_PINK_TINT}`, borderRadius: 10, overflow: "hidden", background: "#fff",
                        boxShadow: "0 8px 22px -10px rgba(237,77,134,.30)",
                        animation: `popIn .5s ${vi * 140}ms cubic-bezier(.34,1.56,.64,1) backwards`,
                        position: "relative",
                      }}>
                        <div style={{
                          position: "absolute", top: 8, right: 8, zIndex: 2,
                          background: ready ? E_PINK : "rgba(15,23,42,.85)", color: "#fff",
                          borderRadius: 4, padding: "2px 6px", fontSize: 9, fontWeight: 700, letterSpacing: ".06em",
                          display: "inline-flex", alignItems: "center", gap: 4,
                          transition: "background .3s",
                        }}>
                          {ready ? <>✨ NEW &middot; {variant.code}</> : (
                            <>
                              <span style={{
                                width: 8, height: 8, borderRadius: 99, border: "1.5px solid rgba(255,255,255,.4)",
                                borderTopColor: "#fff", animation: "spin .8s linear infinite",
                              }} />
                              {variant.code}
                            </>
                          )}
                        </div>
                        <div style={{ height: 130, position: "relative", overflow: "hidden", background: E_INK, padding: "12px 10px", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8 }}>
                          {!ready && (
                            <div style={{
                              position: "absolute", inset: 0, background: "rgba(15,23,42,.55)", backdropFilter: "blur(2px)",
                              display: "grid", placeItems: "center", zIndex: 1,
                            }}>
                              <div style={{ textAlign: "center" }}>
                                <div style={{ fontSize: 9, color: E_PINK_TINT, letterSpacing: ".18em", fontWeight: 700, marginBottom: 6 }}>TRANSLATING…</div>
                                <div style={{ width: 100, height: 3, background: "rgba(255,255,255,.12)", borderRadius: 99, overflow: "hidden", margin: "0 auto" }}>
                                  <div style={{
                                    height: "100%", background: E_PINK, borderRadius: 99,
                                    width: "0%",
                                    animation: `progFill 3.6s ${vi * 350}ms ease-out forwards`,
                                  }} />
                                </div>
                              </div>
                            </div>
                          )}
                          <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 8, color: E_PINK, letterSpacing: "0.2em" }}>{"{{hotel_name}}"}</div>
                          <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 12, color: "#fff", fontStyle: "italic", lineHeight: 1.05, textAlign: "center", padding: "0 6px" }}>
                            {ready ? variant.headline : "…"}
                          </div>
                          <div style={{ width: 28, height: 2, background: E_PINK, marginTop: 2 }} />
                          <div style={{ width: "70%", height: 2, background: "#475569" }} />
                          <div style={{ width: "55%", height: 2, background: "#334155" }} />
                        </div>
                        <div style={{ padding: "10px 12px" }}>
                          <div style={{ fontSize: 11.5, fontWeight: 600, color: E_INK, marginBottom: 4 }}>
                            Early Bird ({variant.name})
                          </div>
                          <div style={{ display: "flex", gap: 4, alignItems: "center" }}>
                            <span style={{
                              background: ready ? E_PINK_SOFT : "#f1f5f9",
                              color: ready ? E_PINK : "#94a3b8",
                              fontSize: 9, fontWeight: 700, padding: "2px 5px", borderRadius: 3,
                              transition: "all .3s",
                            }}>{ready ? "translated" : "in progress"}</span>
                            <span style={{ marginLeft: "auto", fontSize: 9, color: ready ? E_PINK : "#94a3b8", fontWeight: 700 }}>{variant.code}</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                  {GALLERY_TEMPLATES.map((t, i) => {
                    const isHero = i === 5; // Early Bird-ish hero card
                    return (
                      <div key={i} style={{
                        border: isHero ? `2px solid ${E_PINK}` : "1px solid #f1f5f9", borderRadius: 10, overflow: "hidden",
                        background: "#fff", boxShadow: isHero ? "0 12px 28px -8px rgba(237,77,134,.30)" : "none",
                        transform: seen ? "translateY(0)" : "translateY(20px)",
                        opacity: seen ? 1 : 0,
                        transition: `transform .5s ${i * 50}ms ease-out, opacity .5s ${i * 50}ms ease-out`,
                        position: "relative",
                      }}>
                        {isHero && (
                          <div style={{ position: "absolute", top: 8, left: 8, zIndex: 2, background: E_PINK, color: "#fff", borderRadius: 4, width: 18, height: 18, display: "grid", placeItems: "center" }}>
                            <Icon name="check" size={11} color="#fff" />
                          </div>
                        )}
                        <div style={{ height: 130, position: "relative", overflow: "hidden" }}>
                          <TemplateThumb {...t} />
                        </div>
                        <div style={{ padding: "10px 12px" }}>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 6, marginBottom: 4 }}>
                            <div style={{ fontSize: 11.5, fontWeight: 600, color: E_INK, lineHeight: 1.25, flex: 1 }}>{t.name}</div>
                            <span style={{ background: "#dcfce7", color: "#166534", fontSize: 9, fontWeight: 700, padding: "2px 6px", borderRadius: 4 }}>Active</span>
                          </div>
                          <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                            {t.tags.slice(0, 2).map((tag) => (
                              <span key={tag} style={{ background: "#f1f5f9", color: "#64748b", fontSize: 9, padding: "2px 5px", borderRadius: 3 }}>{tag}</span>
                            ))}
                            <span style={{ marginLeft: "auto", fontSize: 9, color: "#94a3b8", fontWeight: 700 }}>EN</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}

                </div>

                {/* Translate Modal Overlay */}
                {showModal && (
                  <div style={{
                    position: "absolute", inset: 0, background: "rgba(15,23,42,.55)", backdropFilter: "blur(4px)",
                    display: "grid", placeItems: "center", zIndex: 10, animation: "fadeIn .25s ease-out",
                  }}>
                    <div style={{
                      width: 460, background: "#fff", borderRadius: 14, padding: "22px 24px",
                      boxShadow: "0 30px 60px -10px rgba(15,23,42,.4)",
                      animation: "popIn .35s cubic-bezier(.34,1.56,.64,1)",
                    }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
                        <div>
                          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                            <div style={{ width: 28, height: 28, borderRadius: 7, background: E_PINK_SOFT, display: "grid", placeItems: "center" }}>
                              <span style={{ fontSize: 14 }}>文<sub style={{ fontSize: 8, color: E_PINK }}>A</sub></span>
                            </div>
                            <div style={{ fontSize: 16, fontWeight: 700, color: E_INK }}>Translate Template</div>
                          </div>
                          <div style={{ fontSize: 12, color: "#94a3b8", marginTop: 5, marginLeft: 37 }}>Early Bird (dark)</div>
                        </div>
                        <Icon name="x" size={16} color="#94a3b8" />
                      </div>

                      {/* Search */}
                      <div style={{ background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 8, padding: "8px 12px", display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
                        <Icon name="search" size={13} color="#94a3b8" />
                        <span style={{ fontSize: 12.5, color: "#94a3b8" }}>Search languages…</span>
                      </div>

                      {/* Header row */}
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "0 2px 10px", borderBottom: "1px solid #f1f5f9", marginBottom: 8 }}>
                        <div style={{ fontSize: 12, fontWeight: 600, color: E_INK }}>{selected.length} selected</div>
                        <div style={{ display: "flex", gap: 14, fontSize: 11.5 }}>
                          <span style={{ color: E_PINK, fontWeight: 600 }}>Select All</span>
                          <span style={{ color: "#94a3b8" }}>Clear</span>
                        </div>
                      </div>

                      {/* Language rows */}
                      <div style={{ maxHeight: 230, overflow: "hidden", marginBottom: 16 }}>
                        {TRANSLATE_LANGS.map((l) => {
                          const isSel = selected.includes(l.code);
                          return (
                            <div key={l.code} style={{
                              display: "flex", alignItems: "center", justifyContent: "space-between",
                              padding: "9px 12px", borderRadius: 8, marginBottom: 2,
                              background: isSel ? E_PINK_SOFT : "transparent",
                              border: isSel ? `1px solid ${E_PINK_TINT}` : "1px solid transparent",
                              transition: "background .2s, border-color .2s",
                            }}>
                              <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
                                <div style={{
                                  width: 16, height: 16, borderRadius: 4,
                                  background: isSel ? E_PINK : "#fff",
                                  border: isSel ? "none" : "1.5px solid #cbd5e1",
                                  display: "grid", placeItems: "center",
                                  transition: "all .2s",
                                }}>
                                  {isSel && <Icon name="check" size={11} color="#fff" />}
                                </div>
                                <span style={{ fontSize: 13, color: E_INK, fontWeight: isSel ? 600 : 500 }}>{l.name}</span>
                              </div>
                              <span style={{ fontSize: 10.5, fontWeight: 700, color: "#94a3b8", letterSpacing: ".05em" }}>{l.code}</span>
                            </div>
                          );
                        })}
                      </div>

                      <div style={{ display: "flex", justifyContent: "flex-end", gap: 10 }}>
                        <button style={{ background: "#fff", border: "1px solid #e2e8f0", color: "#475569", borderRadius: 8, padding: "9px 16px", fontSize: 12.5, fontWeight: 600 }}>Cancel</button>
                        <button style={{
                          background: phase === 6 ? "#9d174d" : E_PINK, color: "#fff", border: "none",
                          borderRadius: 8, padding: "9px 18px", fontSize: 12.5, fontWeight: 700,
                          boxShadow: phase === 5 ? `0 0 0 4px ${E_PINK_TINT}` : "none",
                          transition: "all .2s",
                          display: "inline-flex", alignItems: "center", gap: 7,
                        }}>
                          {phase === 6 ? (
                            <>
                              <span style={{
                                width: 12, height: 12, borderRadius: 99, border: "2px solid rgba(255,255,255,.4)",
                                borderTopColor: "#fff", animation: "spin .8s linear infinite",
                              }} />
                              Translating…
                            </>
                          ) : (
                            <>Translate to {selected.length || 0} languages</>
                          )}
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
          </ScaleFrame>
        </div>
        <style>{`
          @keyframes popIn { 0% { transform: scale(.92); opacity: 0 } 100% { transform: scale(1); opacity: 1 } }
          @keyframes modalPopIn { 0% { transform: translate(-50%, -50%) scale(.94); opacity: 0 } 100% { transform: translate(-50%, -50%) scale(1); opacity: 1 } }
          @keyframes spin { to { transform: rotate(360deg) } }
          @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
          @keyframes float { 0%, 100% { transform: translateY(0) } 50% { transform: translateY(-3px) } }
          @keyframes progFill { 0% { width: 0% } 100% { width: 100% } }
          @keyframes slideInRight { from { transform: translateX(40px); opacity: 0 } to { transform: translateX(0); opacity: 1 } }
        `}</style>
      </section>
    );
  };

  // ============== AI STUDIO ARTIFACT ==============
  const PROMPT_LIBRARY = [
    { name: "Black Friday", style: "Bold", color: "#fee2e2", accent: "#dc2626" },
    { name: "Cyber Monday", style: "Modern", color: "#dbeafe", accent: "#2563eb" },
    { name: "Summer Special", style: "Resort", color: "#cffafe", accent: "#0891b2" },
    { name: "Winter Escape", style: "Luxury", color: "#fef3c7", accent: "#b45309" },
    { name: "Early Bird", style: "Minimal", color: "#fef3c7", accent: "#b45309" },
    { name: "Flash Sale", style: "Bold", color: "#fee2e2", accent: "#dc2626" },
    { name: "Holiday Season", style: "Classic", color: "#dbeafe", accent: "#1e40af" },
    { name: "Anniversary", style: "Boutique", color: "#fef3c7", accent: "#b45309" },
    { name: "Eco Retreat", style: "Eco", color: "#dcfce7", accent: "#15803d" },
    { name: "Booking Confirm", style: "Modern", color: "#dbeafe", accent: "#2563eb" },
    { name: "Room Upgrade", style: "Luxury", color: "#fef3c7", accent: "#b45309" },
    { name: "Pre-Arrival", style: "Resort", color: "#cffafe", accent: "#0891b2" },
  ];

  const TYPING_PROMPT = "Create a summer promotion email for Aurea Hotels beachfront properties with 20% early bird discount.";

  const AIStudioArtifact = () => {
    const [ref, seen] = eUseRef ? useInView(0.2) : [null, false];
    // Phases: 0 landing idle, 1 typing prompt in centered box, 2 plus-button drawer open,
    //         3 drawer closes & layout shifts to chat/canvas split (prompt sent), 4 AI thinking,
    //         5 AI reply + email renders, 6 dwell
    const [phase, setPhase] = eUseState(0);
    const [typed, setTyped] = eUseState("");

    eUseEffect(() => {
      if (!seen) return;
      let cancel = false;
      const wait = (ms) => new Promise((r) => setTimeout(r, ms));
      const run = async () => {
        while (!cancel) {
          setPhase(0); setTyped("");
          await wait(1200);
          setPhase(1);
          for (let i = 1; i <= TYPING_PROMPT.length; i++) {
            if (cancel) return;
            setTyped(TYPING_PROMPT.slice(0, i));
            await wait(20);
          }
          await wait(600);
          setPhase(2); // + popup
          await wait(2000);
          setPhase(3); // Design Controls drawer
          await wait(3500);
          setPhase(4); // drawer closes, popup gone
          await wait(700);
          setPhase(5); // Sections modal
          await wait(3500);
          setPhase(6); // modal closes
          await wait(600);
          setPhase(7); // chat split
          await wait(900);
          setPhase(8); // AI thinking
          await wait(1700);
          setPhase(9); // email renders
          await wait(8000);
        }
      };
      run();
      return () => { cancel = true; };
    }, [seen]);

    return (
      <section ref={ref} style={{ background: "#fff", padding: "100px 24px 80px" }}>
        <div style={{ maxWidth: 1480, margin: "0 auto" }}>
          <div className="jrn-artifact-header" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", alignItems: "end", gap: 48, marginBottom: 36 }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 18 }}>
                02 · AI EMAIL STUDIO
              </div>
              <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(24px, 4vw, 56px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
                From sentence to send-ready, <span style={{ fontStyle: "italic", color: E_PINK }}>in two minutes.</span>
              </h3>
            </div>
            <div style={{ paddingBottom: 8 }}>
              <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", margin: 0, maxWidth: 540 }}>
                30+ curated prompts cover every hospitality scenario, Black Friday, post-stay thank-you, room upgrade, anniversary. Pick one or describe your own. The AI Studio writes copy, picks imagery, builds responsive HTML, and hands it off to the visual editor in under 120 seconds.
              </p>
            </div>
          </div>

          {/* Artifact */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{
            background: E_CREAM, borderRadius: 18,
            boxShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
            border: "1px solid rgba(15,23,42,.06)", overflow: "hidden",
            display: "grid",
            gridTemplateColumns: phase <= 6 ? "230px minmax(0, 1fr)" : "minmax(0, 1fr) minmax(0, 1.35fr)",
            height: 760,
            position: "relative",
          }}>
            {/* Advanced Design drawer overlay (phase 3) */}
            {phase === 3 && (
              <>
                <div style={{ position: "absolute", inset: 0, background: "rgba(15,23,42,.18)", zIndex: 30, animation: "fadeIn .25s" }} />
                <div style={{ position: "absolute", top: 0, right: 0, bottom: 0, width: 380, background: "#fff", boxShadow: "-30px 0 60px -20px rgba(15,23,42,.25)", zIndex: 31, display: "flex", flexDirection: "column", animation: "slideInRight .35s cubic-bezier(.2,.8,.2,1)" }}>
                  <div style={{ padding: "20px 22px 14px", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".15em", color: E_PINK, marginBottom: 4 }}>ADVANCED</div>
                      <div style={{ fontSize: 16, fontWeight: 700, color: E_INK }}>Design controls</div>
                    </div>
                    <Icon name="x" size={16} color="#94a3b8" />
                  </div>
                  <div style={{ padding: "16px 22px", overflow: "auto", display: "flex", flexDirection: "column", gap: 18, fontSize: 12 }}>
                    {[
                      { l: "Hero treatment", o: ["Full-bleed", "Boxed", "Split", "None"], a: 0 },
                      { l: "Typography", o: ["Editorial", "Modern", "Friendly"], a: 0 },
                      { l: "Color mood", sw: ["#0f172a", "#0a4f4a", "#7c2d12", "#be185d", "#1e3a8a"], a: 1 },
                      { l: "Density", o: ["Compact", "Comfortable", "Spacious"], a: 1 },
                      { l: "CTA style", o: ["Solid", "Outline", "Pill", "Underline"], a: 0 },
                      { l: "Image style", o: ["Photographic", "Illustrative", "None"], a: 0 },
                    ].map((c, i) => (
                      <div key={i}>
                        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".08em", color: "#64748b", marginBottom: 7, textTransform: "uppercase" }}>{c.l}</div>
                        {c.sw ? (
                          <div style={{ display: "flex", gap: 8 }}>{c.sw.map((sw, j) => (
                            <div key={j} style={{ width: 30, height: 30, borderRadius: 8, background: sw, boxShadow: j === c.a ? `0 0 0 2px #fff, 0 0 0 4px ${E_PINK}` : "none" }} />
                          ))}</div>
                        ) : (
                          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>{c.o.map((o, j) => (
                            <div key={j} style={{ padding: "6px 11px", borderRadius: 7, fontSize: 11.5, fontWeight: 600, background: j === c.a ? E_PINK : "#f8fafc", color: j === c.a ? "#fff" : "#334155", border: j === c.a ? "none" : "1px solid #e2e8f0" }}>{o}</div>
                          ))}</div>
                        )}
                      </div>
                    ))}
                    <div style={{ marginTop: 4, padding: "12px 14px", background: E_PINK_SOFT, borderRadius: 10, display: "flex", gap: 10, alignItems: "flex-start" }}>
                      <Icon name="sparkles" size={14} color={E_PINK} />
                      <div>
                        <div style={{ fontSize: 12, fontWeight: 700, color: E_INK, marginBottom: 2 }}>AI will adapt</div>
                        <div style={{ fontSize: 11, color: "#64748b", lineHeight: 1.45 }}>These rules apply to every email this session generates.</div>
                      </div>
                    </div>
                  </div>
                  <div style={{ marginTop: "auto", padding: "14px 22px", borderTop: "1px solid #f1f5f9", display: "flex", gap: 8 }}>
                    <button style={{ flex: 1, height: 36, borderRadius: 8, border: "1px solid #e2e8f0", background: "#fff", fontSize: 12.5, fontWeight: 600, color: "#475569" }}>Reset</button>
                    <button style={{ flex: 2, height: 36, borderRadius: 8, border: "none", background: E_PINK, color: "#fff", fontSize: 12.5, fontWeight: 700 }}>Apply</button>
                  </div>
                </div>
              </>
            )}
            {/* Sections modal overlay (phase 5) */}
            {phase === 5 && (
              <>
                <div style={{ position: "absolute", inset: 0, background: "rgba(15,23,42,.42)", zIndex: 30, animation: "fadeIn .25s" }} />
                <div style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width: 760, maxHeight: "86%", background: "#fff", borderRadius: 16, boxShadow: "0 40px 80px -20px rgba(15,23,42,.3)", zIndex: 31, animation: "modalPopIn .3s cubic-bezier(.34,1.56,.64,1)", overflow: "hidden", display: "flex", flexDirection: "column" }}>
                  <div style={{ padding: "20px 24px 14px", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                    <div>
                      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".15em", color: E_PINK, marginBottom: 3 }}>SECTIONS LIBRARY</div>
                      <div style={{ fontSize: 17, fontWeight: 700, color: E_INK }}>Build your email layout</div>
                    </div>
                    <Icon name="x" size={16} color="#94a3b8" />
                  </div>
                  <div style={{ padding: "12px 24px 0", display: "flex", gap: 4, borderBottom: "1px solid #f1f5f9" }}>
                    {["All", "Hero", "Content", "Cards", "Social proof", "CTA"].map((t, i) => (
                      <div key={t} style={{ padding: "7px 12px", fontSize: 11.5, fontWeight: 600, color: i === 0 ? "#fff" : "#64748b", background: i === 0 ? E_INK : "transparent", borderRadius: 99, marginBottom: 10 }}>{t}</div>
                    ))}
                  </div>
                  <div style={{ padding: "18px 24px", overflow: "auto" }}>
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
                      {[
                        { n: "Hero, Full bleed", c: "Hero", bg: "#fef2f2", bar: "#dc2626", on: true },
                        { n: "Hero, Boxed", c: "Hero", bg: "#eff6ff", bar: "#2563eb" },
                        { n: "Hero, Split", c: "Hero", bg: "#ecfdf5", bar: "#059669" },
                        { n: "Headline + Subhead", c: "Content", bg: "#fef3c7", bar: "#d97706", on: true },
                        { n: "Personalized Greeting", c: "Content", bg: "#fdf4ff", bar: "#a855f7", on: true },
                        { n: "Stat Strip", c: "Content", bg: "#f0f9ff", bar: "#0891b2", on: true },
                        { n: "Property Cards, 3up", c: "Cards", bg: "#fef2f2", bar: "#be185d", on: true },
                        { n: "Property Cards, 2up", c: "Cards", bg: "#fff7ed", bar: "#c2410c" },
                        { n: "Inclusion List", c: "Cards", bg: "#f0fdf4", bar: "#16a34a" },
                        { n: "Guest Testimonial", c: "Social proof", bg: "#fdf4ff", bar: "#7c3aed" },
                        { n: "Booking Deadline", c: "CTA", bg: "#fffbeb", bar: "#b45309", on: true },
                        { n: "Final CTA, Dark", c: "CTA", bg: "#1e293b", bar: E_PINK, on: true, dark: true },
                      ].map((s, i) => (
                        <div key={i} style={{ position: "relative", borderRadius: 10, overflow: "hidden", border: s.on ? `1.5px solid ${E_PINK}` : "1px solid #e2e8f0", boxShadow: s.on ? `0 0 0 3px ${E_PINK_TINT}` : "none" }}>
                          <div style={{ background: s.bg, padding: "22px 14px 14px", height: 86, position: "relative" }}>
                            <div style={{ height: 3, width: "45%", background: s.bar, marginBottom: 8, borderRadius: 2 }} />
                            <div style={{ height: 6, width: "70%", background: s.dark ? "rgba(255,255,255,.25)" : "rgba(15,23,42,.12)", borderRadius: 2, marginBottom: 4 }} />
                            <div style={{ height: 6, width: "55%", background: s.dark ? "rgba(255,255,255,.18)" : "rgba(15,23,42,.08)", borderRadius: 2, marginBottom: 8 }} />
                            <div style={{ display: "flex", gap: 4 }}>
                              <div style={{ height: 16, width: 24, background: s.dark ? "rgba(255,255,255,.18)" : "rgba(15,23,42,.08)", borderRadius: 2 }} />
                              <div style={{ height: 16, width: 24, background: s.dark ? "rgba(255,255,255,.18)" : "rgba(15,23,42,.08)", borderRadius: 2 }} />
                              <div style={{ height: 16, width: 24, background: s.dark ? "rgba(255,255,255,.18)" : "rgba(15,23,42,.08)", borderRadius: 2 }} />
                            </div>
                            {s.on && (
                              <div style={{ position: "absolute", top: 8, right: 8, width: 18, height: 18, borderRadius: 99, background: E_PINK, display: "grid", placeItems: "center" }}>
                                <Icon name="check" size={10} color="#fff" />
                              </div>
                            )}
                          </div>
                          <div style={{ padding: "9px 12px", background: "#fff" }}>
                            <div style={{ fontSize: 11.5, fontWeight: 700, color: E_INK, lineHeight: 1.2 }}>{s.n}</div>
                            <div style={{ fontSize: 10, color: "#94a3b8", marginTop: 1 }}>{s.c}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                  <div style={{ padding: "14px 24px", borderTop: "1px solid #f1f5f9", display: "flex", gap: 10, justifyContent: "space-between", alignItems: "center", background: "#fafafa" }}>
                    <div style={{ fontSize: 11.5, color: "#64748b" }}><b style={{ color: E_PINK }}>7 sections</b> selected, drag to reorder</div>
                    <div style={{ display: "flex", gap: 8 }}>
                      <button style={{ height: 36, padding: "0 16px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#fff", fontSize: 12.5, fontWeight: 600, color: "#475569" }}>Cancel</button>
                      <button style={{ height: 36, padding: "0 18px", borderRadius: 8, border: "none", background: E_PINK, color: "#fff", fontSize: 12.5, fontWeight: 700 }}>Use 7 sections</button>
                    </div>
                  </div>
                </div>
              </>
            )}
            {phase <= 6 && (
              <>
                {/* Sessions sidebar */}
                <div style={{ background: "#fafafa", borderRight: "1px solid #f1f5f9", padding: "18px 14px", display: "flex", flexDirection: "column", animation: "fadeIn .4s" }}>
                  <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".18em", color: "#94a3b8", marginBottom: 12, padding: "0 4px" }}>SESSIONS</div>
                  <button style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "9px 12px", display: "flex", alignItems: "center", gap: 8, fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 10, cursor: "pointer" }}>
                    <Icon name="plus" size={12} /> New session
                  </button>
                  <div style={{ background: "#fff", border: "1px solid #e2e8f0", borderRadius: 8, padding: "8px 10px", display: "flex", alignItems: "center", gap: 7, marginBottom: 14 }}>
                    <Icon name="search" size={11} color="#94a3b8" />
                    <span style={{ fontSize: 11.5, color: "#94a3b8" }}>Search sessions…</span>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 2, fontSize: 11.5 }}>
                    {[
                      { t: "Build me a featured property…", s: "about 21 hours ago", st: "Modern" },
                      { t: "The Meridian summer collecti…", s: "about 21 hours ago", st: "Modern" },
                      { t: "Build me a featured property…", s: "7 days ago", st: "Modern" },
                      { t: "Luxury style. The Meridian su…", s: "7 days ago", st: "Luxury" },
                      { t: "modern style. Aurea Hotels su…", s: "11 days ago", st: "Modern" },
                      { t: "Create a 3-property showcase…", s: "11 days ago", st: "Modern" },
                    ].map((s, i) => (
                      <div key={i} style={{ padding: "9px 10px", borderRadius: 6, color: "#334155", lineHeight: 1.3 }}>
                        <div style={{ fontWeight: 500, color: E_INK, fontSize: 11.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.t}</div>
                        <div style={{ fontSize: 9.5, color: "#94a3b8", marginTop: 2 }}>{s.s} · <span style={{ color: "#64748b" }}>{s.st}</span></div>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Studio main */}
                <div style={{ background: "#fff", padding: "30px 36px 36px", animation: "fadeIn .4s", display: "flex", flexDirection: "column" }}>
                  {/* Header */}
                  <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 28 }}>
                    <div style={{ width: 28, height: 28, borderRadius: 7, background: "linear-gradient(135deg, " + E_PINK + ", #a855f7)", display: "grid", placeItems: "center" }}>
                      <Icon name="sparkles" size={14} color="#fff" />
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: E_INK }}>Untitled template</div>
                  </div>

                  {/* Centered prompt */}
                  <div style={{ textAlign: "center", marginBottom: 24 }}>
                    <div style={{ width: 44, height: 44, borderRadius: 11, background: E_PINK_SOFT, display: "grid", placeItems: "center", margin: "0 auto 14px" }}>
                      <Icon name="sparkles" size={22} color={E_PINK} />
                    </div>
                    <h4 style={{ fontSize: 22, fontWeight: 600, color: E_INK, margin: "0 0 6px", lineHeight: 1.2, letterSpacing: "-0.01em" }}>What email would you like to create?</h4>
                    <div style={{ fontSize: 13, color: "#64748b" }}>Describe your vision and I&rsquo;ll design a stunning HTML email template</div>
                  </div>

                  {/* Prompt input */}
                  <div style={{ position: "relative" }}>
                  <div style={{
                    border: phase >= 1 ? `1.5px solid ${E_PINK}` : "1.5px solid #e2e8f0",
                    borderRadius: 14, padding: "16px 18px", background: "#fff",
                    boxShadow: phase >= 1 ? `0 0 0 4px ${E_PINK_TINT}` : "none",
                    transition: "all .25s", marginBottom: 30,
                  }}>
                    <div style={{ fontSize: 13, color: phase >= 1 ? E_INK : "#94a3b8", minHeight: 44, lineHeight: 1.5 }}>
                      {phase >= 1 ? <>{typed}<span style={{ opacity: phase === 1 ? 1 : 0, color: E_PINK }}>|</span></> : "Describe the email you\u2019d like to create\u2026"}
                    </div>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 6 }}>
                      <div style={{ display: "flex", gap: 14, fontSize: 12, color: "#64748b", alignItems: "center" }}>
                        <span style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 22, height: 22, borderRadius: 6, background: (phase === 2 || phase === 3) ? E_PINK_SOFT : "transparent", transition: "all .2s", boxShadow: (phase === 2 || phase === 3) ? `0 0 0 3px ${E_PINK_TINT}` : "none" }}><Icon name="plus" size={12} color={(phase === 2 || phase === 3) ? E_PINK : "#64748b"} /></span>
                        <span style={{ display: "inline-flex", alignItems: "center", gap: 5, padding: "4px 8px", borderRadius: 6, background: (phase === 5 || phase === 6) ? E_PINK_SOFT : "transparent", color: (phase === 5 || phase === 6) ? E_PINK : "#64748b", fontWeight: (phase === 5 || phase === 6) ? 600 : 400, boxShadow: (phase === 5 || phase === 6) ? `0 0 0 3px ${E_PINK_TINT}` : "none", transition: "all .2s" }}><Icon name="stack" size={12} color={(phase === 5 || phase === 6) ? E_PINK : "#64748b"} /> Sections</span>
                      </div>
                      <button style={{ width: 30, height: 30, borderRadius: 8, background: phase >= 1 ? E_PINK : "#f1f5f9", color: phase >= 1 ? "#fff" : "#94a3b8", border: "none", display: "grid", placeItems: "center", transition: "all .25s", fontSize: 14, fontWeight: 700 }}>
                        ↑
                      </button>
                    </div>
                  </div>
                  {(phase === 2 || phase === 3) && (
                    <div style={{ position: "absolute", top: 56, left: 0, width: 290, background: "#fff", border: "1px solid #e2e8f0", borderRadius: 12, boxShadow: "0 24px 48px -12px rgba(15,23,42,.18)", padding: 6, zIndex: 5, animation: "popIn .25s ease-out" }}>
                      {[
                        { ic: "paperclip", n: "Attach image", v: "" },
                        { ic: "image", n: "Image gallery", v: "" },
                        { ic: "building", n: "Property", v: "All properties" },
                        { ic: "palette", n: "Brand settings", v: "Setup", warn: true },
                        { ic: "type", n: "Writing tone", v: "Professional" },
                        { ic: "globe", n: "Language", v: "English" },
                        { ic: "sparkles", n: "Design style", v: "Modern" },
                        { ic: "sliders", n: "Advanced design", v: "", hi: phase === 3 },
                      ].map((it, i) => (
                        <div key={i} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 10px", borderRadius: 7, fontSize: 12.5, color: E_INK, background: it.hi ? E_PINK_SOFT : "transparent", boxShadow: it.hi ? `0 0 0 2px ${E_PINK_TINT}` : "none", transition: "all .2s" }}>
                          <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
                            <span style={{ width: 16, height: 16, display: "inline-flex", alignItems: "center", justifyContent: "center", color: it.hi ? E_PINK : "#64748b" }}>
                              <Icon name={it.ic} size={13} color={it.hi ? E_PINK : "#64748b"} />
                            </span>
                            {it.n}
                          </span>
                          <span style={{ fontSize: 11, color: it.warn ? "#f59e0b" : "#94a3b8" }}>
                            {it.v}{it.v && " \u203a"}
                          </span>
                        </div>
                      ))}
                    </div>
                  )}
                  </div>

                  {/* Prompt library */}
                  <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".2em", color: "#94a3b8", marginBottom: 12 }}>PROMPT LIBRARY</div>
                  <div style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
                    {["All", "Promotional", "Pre-Stay", "Welcome", "In-Stay", "Post-Stay", "Re-engagement", "Newsletter"].map((c, i) => (
                      <span key={c} style={{
                        fontSize: 11, padding: "5px 11px", borderRadius: 99, fontWeight: 600,
                        background: i === 0 ? E_INK : "transparent", color: i === 0 ? "#fff" : "#475569",
                      }}>{c}</span>
                    ))}
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, flex: 1 }}>
                    {PROMPT_LIBRARY.map((p, i) => (
                      <div key={i} style={{
                        background: p.color, borderRadius: 9, padding: "14px 12px 12px",
                        display: "flex", flexDirection: "column", justifyContent: "space-between",
                        border: "1px solid rgba(0,0,0,.04)", minHeight: 110,
                      }}>
                        <div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "center", marginTop: 6 }}>
                          <div style={{ width: 36, height: 3, background: p.accent, borderRadius: 99 }} />
                          <div style={{ width: 50, height: 4, background: "rgba(15,23,42,.12)", borderRadius: 99 }} />
                          <div style={{ width: 40, height: 4, background: "rgba(15,23,42,.12)", borderRadius: 99 }} />
                        </div>
                        <div>
                          <div style={{ fontSize: 11, fontWeight: 700, color: E_INK, lineHeight: 1.1 }}>{p.name}</div>
                          <div style={{ fontSize: 9, color: "#64748b", marginTop: 2 }}>{p.style}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
            {phase >= 7 && (
            <>
            {/* Left: chat + prompt library */}
            <div style={{ background: "#fff", borderRight: "1px solid #f1f5f9", display: "flex", flexDirection: "column" }}>
              <div style={{ padding: "14px 18px", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", gap: 10 }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: "linear-gradient(135deg, " + E_PINK + ", #a855f7)", display: "grid", placeItems: "center" }}>
                  <Icon name="sparkles" size={15} color="#fff" />
                </div>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Untitled template</div>
                <div style={{ marginLeft: "auto", fontSize: 11, color: "#94a3b8" }}>Aurea Hotels</div>
              </div>

              {/* Chat area */}
              <div style={{ padding: "20px 22px", flex: 1, display: "flex", flexDirection: "column", gap: 14, fontSize: 13.5 }}>
                {phase >= 7 && (
                  <div style={{ alignSelf: "flex-end", maxWidth: "85%", background: E_PINK_SOFT, color: E_INK, padding: "10px 14px", borderRadius: 14, borderBottomRightRadius: 4, lineHeight: 1.5 }}>
                    {typed}
                  </div>
                )}
                {phase >= 8 && (
                  <div style={{ alignSelf: "flex-start", display: "flex", gap: 10, alignItems: "flex-start" }}>
                    <div style={{ width: 22, height: 22, borderRadius: 6, background: "linear-gradient(135deg, " + E_PINK + ", #a855f7)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                      <Icon name="sparkles" size={11} color="#fff" />
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".1em", color: E_PINK, marginBottom: 4 }}>GUESTMAKER</div>
                      {phase === 8 && (
                        <div style={{ display: "flex", gap: 4, alignItems: "center", color: "#64748b" }}>
                          <span className="dot" style={{ width: 6, height: 6, borderRadius: 99, background: E_PINK, animation: "float 1s ease-in-out infinite" }} />
                          <span className="dot" style={{ width: 6, height: 6, borderRadius: 99, background: E_PINK, animation: "float 1s ease-in-out .2s infinite" }} />
                          <span className="dot" style={{ width: 6, height: 6, borderRadius: 99, background: E_PINK, animation: "float 1s ease-in-out .4s infinite" }} />
                          <span style={{ marginLeft: 8, fontSize: 12 }}>Building your template…</span>
                        </div>
                      )}
                      {phase === 9 && (
                        <div style={{ color: "#334155", lineHeight: 1.55 }}>
                          I&rsquo;ll create a bold summer promo email with a dramatic beachfront hero, a stat strip highlighting the 20% discount and June 1 deadline, and a three-card offer grid showcasing your beachfront resorts.
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>

              {/* Composer at bottom */}
              <div style={{ padding: "14px 18px 18px", borderTop: "1px solid #f1f5f9" }}>
                <div style={{ border: "1px solid #e2e8f0", borderRadius: 12, padding: "10px 12px", background: "#fff" }}>
                  <div style={{ fontSize: 12, color: "#94a3b8" }}>Describe your email template…</div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8 }}>
                    <div style={{ display: "flex", gap: 12, fontSize: 11.5, color: "#64748b" }}>
                      <Icon name="plus" size={11} />
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="stack" size={11} /> Sections</span>
                    </div>
                    <div style={{ width: 24, height: 24, borderRadius: 6, background: "#f1f5f9", display: "grid", placeItems: "center", color: "#94a3b8", fontSize: 12, fontWeight: 700 }}>↑</div>
                  </div>
                </div>
              </div>
            </div>

            {/* Right: canvas, full bleed */}
            <div style={{ display: "flex", flexDirection: "column", background: "#f1f5f9" }}>
              <div style={{ padding: "12px 18px", borderBottom: "1px solid #e2e8f0", display: "flex", alignItems: "center", justifyContent: "space-between", background: "#fff" }}>
                <div style={{ display: "flex", gap: 4, padding: 3, background: "#f1f5f9", borderRadius: 8 }}>
                  <button style={{ background: "#fff", color: E_INK, border: "none", padding: "5px 10px", borderRadius: 6, fontSize: 11, fontWeight: 600, boxShadow: "0 1px 2px rgba(0,0,0,.06)", display: "inline-flex", alignItems: "center", gap: 5 }}>🖥 Desktop</button>
                  <button style={{ background: "transparent", color: "#94a3b8", border: "none", padding: "5px 10px", borderRadius: 6, fontSize: 11, fontWeight: 600 }}>📱 Mobile</button>
                </div>
                <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                  <button style={{ background: "#fff", border: "1px solid #e2e8f0", padding: "6px 10px", borderRadius: 7, fontSize: 11.5, color: "#475569", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="sparkles" size={11} color={E_PINK} /> Tweak</button>
                  <button style={{ background: "#fff", border: "1px solid #e2e8f0", padding: "6px 10px", borderRadius: 7, fontSize: 11.5, color: "#475569", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="edit" size={11} /> Edit</button>
                  <button style={{ background: "#fff", border: "1px solid #e2e8f0", padding: "6px 10px", borderRadius: 7, fontSize: 11.5, color: "#475569", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="copy" size={11} /> Save</button>
                  <button style={{ background: E_INK, color: "#fff", border: "none", padding: "7px 14px", borderRadius: 7, fontSize: 11.5, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 5 }}>Open in Editor →</button>
                </div>
              </div>
              <div style={{ flex: 1, minHeight: 0, overflow: "auto", display: "flex", justifyContent: "center", alignItems: phase < 9 ? "center" : "flex-start", padding: phase < 9 ? 28 : "22px 28px" }}>
                {phase < 9 ? (
                  <div style={{ textAlign: "center", color: "#94a3b8" }}>
                    <div style={{ width: 56, height: 56, borderRadius: 14, background: E_PINK_SOFT, display: "grid", placeItems: "center", margin: "0 auto 14px", animation: phase === 8 ? "float 1.4s ease-in-out infinite" : "none" }}>
                      <Icon name="sparkles" size={26} color={E_PINK} />
                    </div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: E_INK }}>{phase === 8 ? "Designing your template" : "Your template will appear here"}</div>
                    <div style={{ fontSize: 12, marginTop: 4 }}>{phase === 8 ? "Building responsive sections..." : "Describe your email in the chat"}</div>
                    {phase === 8 && (
                      <div style={{ marginTop: 18, width: 200, height: 4, background: "#fff", borderRadius: 99, overflow: "hidden", margin: "18px auto 0", border: "1px solid #f1f5f9" }}>
                        <div style={{ width: "65%", height: "100%", background: E_PINK, animation: "shimmerProgress 1.4s ease-in-out infinite" }} />
                      </div>
                    )}
                  </div>
                ) : (
                  <div style={{ width: "100%", maxWidth: 620 }}><GeneratedEmailPreview /></div>
                )}
              </div>
            </div>
            </>
            )}
          </div>
          </ScaleFrame>
        </div>
        <style>{`
          @keyframes shimmerProgress { 0% { transform: translateX(-100%) } 100% { transform: translateX(160%) } }
        `}</style>
      </section>
    );
  };

  // ============== GENERATED EMAIL PREVIEW (high-quality realistic) ==============
  const GeneratedEmailPreview = () => (
    <div style={{
      width: "100%", background: "#fff", borderRadius: 10, overflow: "hidden",
      boxShadow: "0 16px 40px -12px rgba(15,23,42,.22)", border: "1px solid #f1f5f9",
      fontFamily: '"Inter", sans-serif', animation: "fadeIn .6s ease-out",
    }}>
      {/* Subject line bar */}
      <div style={{ padding: "10px 14px", background: "#f8fafc", borderBottom: "1px solid #f1f5f9", fontSize: 10.5 }}>
        <span style={{ color: "#94a3b8", fontWeight: 600 }}>Subject </span>
        <span style={{ color: E_INK, fontWeight: 600 }}>Summer Early Bird: 20% Off Beachfront Stays, Book by June 1</span>
      </div>
      {/* Pre-header */}
      <div style={{ padding: "8px 14px", textAlign: "center", fontSize: 9.5, color: "#94a3b8", borderBottom: "1px solid #f8fafc" }}>
        View this email in your browser · Aurea Hotels
      </div>
      {/* Hero */}
      <div style={{ position: "relative", height: 320 }}>
        <img src={HOTEL_IMG.bungalow} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", filter: "brightness(.72)" }} />
        <div style={{ position: "absolute", inset: 0, padding: "32px 28px", display: "flex", flexDirection: "column", justifyContent: "space-between", color: "#fff" }}>
          <div>
            <div style={{ fontSize: 9, fontWeight: 700, letterSpacing: ".24em", textShadow: "0 1px 4px rgba(0,0,0,.4)", marginBottom: 6 }}>SUMMER EARLY BIRD · BOOK BY JUNE 1</div>
            <div style={{ fontSize: 10, opacity: .85, letterSpacing: ".2em", fontWeight: 600 }}>AUREA HOTELS</div>
          </div>
          <div>
            <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 44, fontWeight: 400, lineHeight: 1.0, textShadow: "0 2px 12px rgba(0,0,0,.5)", marginBottom: 10, letterSpacing: "-0.01em" }}>
              Your Summer<br/>Escape Awaits
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.5, marginBottom: 18, maxWidth: 380, opacity: .92, textShadow: "0 1px 4px rgba(0,0,0,.4)" }}>
              Reserve before June 1 and save 20% on beachfront stays at three of our most coveted properties, July through September.
            </div>
            <button style={{ background: "#fff", color: E_INK, border: "none", padding: "11px 22px", borderRadius: 4, fontSize: 11, fontWeight: 700, letterSpacing: ".1em" }}>
              BOOK NOW &amp; SAVE 20%
            </button>
          </div>
        </div>
      </div>
      {/* Greeting */}
      <div style={{ padding: "30px 28px 12px" }}>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 26, fontWeight: 400, color: E_INK, marginBottom: 12, letterSpacing: "-0.01em" }}>Dear {"{{first_name}}"},</div>
        <div style={{ fontSize: 13, lineHeight: 1.7, color: "#475569" }}>
          Summer at Aurea is a feeling, barefoot mornings on the sand, long lunches under the palms, the salt-and-citrus quiet of an evening swim. This year, we&rsquo;re offering an early bird gift to the guests who plan ahead: <strong style={{ color: E_INK }}>20% off every beachfront stay</strong> booked before June 1, for travel between July and September.
        </div>
      </div>
      {/* Stat strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", background: "#eef2ff", padding: "22px 18px", gap: 10, margin: "20px 28px", borderRadius: 6 }}>
        {[
          { k: "20%", l: "EARLY BIRD\nDISCOUNT" },
          { k: "JUN 1", l: "BOOKING\nDEADLINE" },
          { k: "3", l: "BEACHFRONT\nRESORTS" },
          { k: "JUL–\nSEP", l: "TRAVEL\nPERIOD" },
        ].map((s) => (
          <div key={s.k} style={{ textAlign: "center" }}>
            <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 22, fontWeight: 400, color: E_INK, lineHeight: 1, whiteSpace: "pre-line" }}>{s.k}</div>
            <div style={{ fontSize: 7.5, fontWeight: 700, letterSpacing: ".14em", color: "#475569", marginTop: 6, whiteSpace: "pre-line", lineHeight: 1.3 }}>{s.l}</div>
          </div>
        ))}
      </div>
      {/* Property cards header */}
      <div style={{ padding: "16px 28px 8px", textAlign: "center" }}>
        <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".22em", color: E_PINK, marginBottom: 6 }}>FEATURED PROPERTIES</div>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 26, fontWeight: 400, color: E_INK, lineHeight: 1.05, letterSpacing: "-0.01em" }}>Three shorelines.<br/>One unforgettable summer.</div>
      </div>
      {/* Property cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", padding: "14px 20px 22px", gap: 14 }}>
        {[
          { name: "Azure Bay", loc: "MALDIVES · INDIAN OCEAN", img: HOTEL_IMG.beach, price: "from $480/night" },
          { name: "Costa Blanca", loc: "ALICANTE · SPAIN", img: HOTEL_IMG.villa, price: "from $320/night" },
          { name: "Coral Cove", loc: "BORA BORA · POLYNESIA", img: HOTEL_IMG.sunset, price: "from $620/night" },
        ].map((p) => (
          <div key={p.name}>
            <div style={{ height: 110, borderRadius: 6, overflow: "hidden", marginBottom: 8 }}>
              <img src={p.img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            </div>
            <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 15, fontWeight: 400, color: E_INK, lineHeight: 1.1 }}>{p.name}</div>
            <div style={{ fontSize: 7.5, fontWeight: 700, letterSpacing: ".12em", color: "#94a3b8", marginTop: 3 }}>{p.loc}</div>
            <div style={{ fontSize: 10, color: E_PINK, marginTop: 6, fontWeight: 600 }}>{p.price}</div>
          </div>
        ))}
      </div>
      {/* Inclusions */}
      <div style={{ padding: "20px 28px", borderTop: "1px solid #f1f5f9", borderBottom: "1px solid #f1f5f9", background: "#fafafa" }}>
        <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".22em", color: E_PINK, marginBottom: 10, textAlign: "center" }}>WHAT&rsquo;S INCLUDED</div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10, fontSize: 11.5, color: "#334155", lineHeight: 1.5 }}>
          {[
            "Daily breakfast for two",
            "Welcome cocktail on arrival",
            "Sunset sailing experience",
            "Late checkout until 4 PM",
            "Resort credit ($75/stay)",
            "Complimentary Wi-Fi & parking",
          ].map((t) => (
            <div key={t} style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
              <span style={{ color: E_PINK, fontWeight: 700, marginTop: 1 }}>✓</span>
              <span>{t}</span>
            </div>
          ))}
        </div>
      </div>
      {/* Testimonial */}
      <div style={{ padding: "30px 28px 26px", textAlign: "center" }}>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontStyle: "italic", fontSize: 17, lineHeight: 1.45, color: E_INK, maxWidth: 460, margin: "0 auto 12px" }}>
          &ldquo;The most thoughtful summer escape we&rsquo;ve had in years, every detail felt designed for us.&rdquo;
        </div>
        <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".18em", color: "#94a3b8" }}>ELENA &amp; MARCO · GUESTS, AZURE BAY</div>
      </div>
      {/* Final CTA */}
      <div style={{ padding: "36px 28px 40px", background: E_INK, color: "#fff", textAlign: "center" }}>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 28, fontWeight: 400, marginBottom: 10, lineHeight: 1.1 }}>Don&rsquo;t wait until summer.</div>
        <div style={{ fontSize: 12, opacity: .75, marginBottom: 20, maxWidth: 360, margin: "0 auto 20px", lineHeight: 1.55 }}>
          Early bird rates expire June 1. After that, standard summer rates apply, and our best rooms book first.
        </div>
        <button style={{ background: E_PINK, color: "#fff", border: "none", padding: "12px 28px", borderRadius: 4, fontSize: 11, fontWeight: 700, letterSpacing: ".1em" }}>
          RESERVE YOUR ESCAPE →
        </button>
      </div>
      {/* Footer */}
      <div style={{ padding: "20px 28px 22px", textAlign: "center", fontSize: 9.5, color: "#94a3b8", lineHeight: 1.6 }}>
        <div style={{ marginBottom: 6, fontWeight: 700, letterSpacing: ".18em", color: "#475569" }}>AUREA HOTELS</div>
        <div>123 Beachfront Avenue · Marina Bay · Reservations +34 900 000 000</div>
        <div style={{ marginTop: 8 }}>
          <span style={{ color: "#64748b" }}>Update preferences</span> · <span style={{ color: "#64748b" }}>Unsubscribe</span> · <span style={{ color: "#64748b" }}>View in browser</span>
        </div>
      </div>
    </div>
  );

  // ============== IMPORT FLOW ==============
  const ImportFlow = () => {
    const [ref, seen] = useInView(0.25);
    const [count, setCount] = eUseState(0);
    eUseEffect(() => {
      if (!seen) return;
      let n = 0;
      const t = setInterval(() => {
        n += 7;
        if (n >= 200) { n = 200; clearInterval(t); }
        setCount(n);
      }, 50);
      return () => clearInterval(t);
    }, [seen]);

    return (
      <section ref={ref} style={{ background: E_CREAM, padding: "80px 24px 80px" }}>
        <div style={{ maxWidth: 1320, margin: "0 auto" }}>
          <div className="jrn-import-grid" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", gap: 48, alignItems: "center" }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 18 }}>
                03 · MIGRATION-FRIENDLY IMPORT
              </div>
              <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(24px, 4vw, 56px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: "0 0 24px", letterSpacing: "-0.01em" }}>
                200 templates,<br/><span style={{ fontStyle: "italic", color: E_PINK }}>15 minutes flat.</span>
              </h3>
              <p style={{ fontSize: 16, lineHeight: 1.6, color: "#475569", margin: 0, maxWidth: 520 }}>
                Switching CRMs is the moment most teams lose years of templates. We give every account a unique import inbox, forward your templates from your old provider and they land here, parsed, indexed, and ready to edit in the visual editor. No copy-paste, no rebuild.
              </p>
              <div style={{ marginTop: 26, display: "flex", flexWrap: "wrap", gap: 10 }}>
                {["Mailchimp", "Klaviyo", "Brevo", "HubSpot", "Customer.io", "ActiveCampaign"].map((p) => (
                  <span key={p} style={{ fontSize: 12, padding: "6px 12px", borderRadius: 99, background: "#fff", border: "1px solid " + E_CREAM_BORDER, color: "#475569", fontWeight: 500 }}>{p}</span>
                ))}
              </div>
            </div>

            {/* Visual: Import Templates side drawer */}
            <div style={{
              background: "#fff", borderRadius: 16, padding: 0,
              position: "relative", overflow: "hidden",
              boxShadow: "0 30px 60px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.06)",
              border: "1px solid " + E_CREAM_BORDER,
              transform: seen ? "translateX(0)" : "translateX(40px)",
              opacity: seen ? 1 : 0,
              transition: "all .7s cubic-bezier(.34,1,.64,1)",
            }}>
              {/* Drawer header */}
              <div style={{ padding: "24px 28px 18px", borderBottom: "1px solid #f1f5f9" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
                  <div style={{ fontSize: 22, fontWeight: 700, color: E_INK, letterSpacing: "-0.01em" }}>Import Templates</div>
                  <div style={{ width: 26, height: 26, border: `1px solid ${E_PINK_TINT}`, borderRadius: 6, display: "grid", placeItems: "center", color: E_PINK }}>
                    <Icon name="x" size={13} color={E_PINK} />
                  </div>
                </div>
                <div style={{ fontSize: 13, color: "#64748b", marginTop: 6, lineHeight: 1.5, maxWidth: 460 }}>
                  Import email templates from another CRM or platform by forwarding them via email.
                </div>
              </div>

              {/* Body */}
              <div style={{ padding: "22px 28px 26px" }}>
                {/* Import via Email card */}
                <div style={{ border: `1px solid ${E_CREAM_BORDER}`, borderRadius: 12, padding: "18px 18px 16px", marginBottom: 16, background: "#fff" }}>
                  <div style={{ display: "flex", gap: 12, alignItems: "flex-start", marginBottom: 14 }}>
                    <div style={{ width: 36, height: 36, borderRadius: 9, background: E_PINK_SOFT, display: "grid", placeItems: "center", flexShrink: 0 }}>
                      <Icon name="mail" size={17} color={E_PINK} />
                    </div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 700, color: E_INK }}>Import via Email</div>
                      <div style={{ fontSize: 12, color: "#64748b", lineHeight: 1.45, marginTop: 2 }}>
                        Forward email templates to the address below. Each email will be automatically converted into an editable template in your library.
                      </div>
                    </div>
                  </div>
                  <div style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".18em", color: "#94a3b8", marginBottom: 6 }}>YOUR IMPORT ADDRESS</div>
                  <div style={{ display: "flex", gap: 8, alignItems: "stretch" }}>
                    <div style={{
                      flex: 1, fontFamily: "ui-monospace, monospace", fontSize: 11.5, color: E_INK,
                      padding: "10px 12px", background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 8,
                      wordBreak: "break-all", lineHeight: 1.35,
                    }}>
                      templates+ea8dffb299a4ab1b159eb420@inbound.guestmaker.ai
                    </div>
                    <button style={{ width: 38, background: "#f8fafc", border: "1px solid #e2e8f0", borderRadius: 8, color: "#64748b", display: "grid", placeItems: "center" }}>
                      <Icon name="copy" size={13} />
                    </button>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10 }}>
                    <div style={{ fontSize: 11, color: "#94a3b8" }}>Forward HTML emails to this address.</div>
                    <span style={{ fontSize: 11, color: E_PINK, display: "inline-flex", alignItems: "center", gap: 4, fontWeight: 600 }}>
                      <Icon name="repeat" size={11} color={E_PINK} /> Regenerate
                    </span>
                  </div>
                </div>

                {/* How it works */}
                <div style={{ marginBottom: 18 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 8 }}>How it works</div>
                  {[
                    "Copy the import address above",
                    "Forward any HTML email template to that address",
                    "The template is automatically converted to editable format and added to your library as a draft",
                    "Open it in the visual editor to customize",
                  ].map((s, i) => (
                    <div key={i} style={{ display: "flex", gap: 10, alignItems: "flex-start", marginBottom: 6, fontSize: 12, color: "#475569", lineHeight: 1.5 }}>
                      <span style={{ color: "#94a3b8", fontWeight: 700, minWidth: 12 }}>{i + 1}.</span>
                      <span>{s}</span>
                    </div>
                  ))}
                </div>

                {/* Recent imports */}
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK }}>Recent Imports <span style={{ color: "#94a3b8", fontWeight: 500 }}>({count > 200 ? 5 : Math.min(5, Math.floor(count / 40))})</span></div>
                  <span style={{ fontSize: 11, color: "#64748b", display: "inline-flex", alignItems: "center", gap: 4 }}>
                    <Icon name="repeat" size={11} /> Refresh
                  </span>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                  {[
                    { subj: "Spa & Wellness Newsletter, March 2026", from: "Luxury Spa Resort", time: "Feb 24, 05:00 PM" },
                    { subj: "Exclusive Loyalty Member Rewards, 50% Off", from: "Luxury Chain Rewards", time: "Feb 24, 04:58 PM" },
                    { subj: "FW: Welcome to Mountain Lodge Spa Retreat", from: "Mountain Lodge", time: "Feb 24, 04:58 PM" },
                    { subj: "Monthly Hotel Newsletter, February 2026", from: "Grand Hotel Newsletter", time: "Feb 24, 04:58 PM" },
                    { subj: "Summer Beach Resort Promotion 2026", from: "Beach Resort Marketing", time: "Feb 24, 04:58 PM" },
                  ].map((e, i) => {
                    const arrived = seen && count > i * 40;
                    return (
                      <div key={i} style={{
                        display: "grid", gridTemplateColumns: "22px 1fr auto auto", gap: 10, alignItems: "center",
                        padding: "10px 12px", borderRadius: 8, background: "#fff", border: "1px solid #f1f5f9",
                        opacity: arrived ? 1 : 0,
                        transform: arrived ? "translateX(0)" : "translateX(-12px)",
                        transition: "all .35s ease-out",
                      }}>
                        <div style={{ width: 18, height: 18, borderRadius: 99, background: "#dcfce7", display: "grid", placeItems: "center" }}>
                          <Icon name="check" size={11} color="#16a34a" />
                        </div>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e.subj}</div>
                          <div style={{ fontSize: 10.5, color: "#94a3b8", marginTop: 1 }}>From {e.from} · {e.time}</div>
                        </div>
                        <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".06em", padding: "3px 8px", borderRadius: 4, background: "#f1f5f9", color: "#475569" }}>Imported</span>
                        <Icon name="chev" size={13} color="#cbd5e1" />
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>
          <style>{`
            /* This 2-up grid holds a realistic drawer-mockup graphic beside
               its copy; at mobile widths the mockup shrinks to illegible
               clutter (and was previously a bare "1fr 1fr" with no minmax(0,
               ...), which let it blow out the viewport entirely). Stack. */
            /* Every "Artifact" section repeats the same title+description
               header as a 2-up grid with alignItems:"end" — at mobile widths
               each column narrows to ~half the viewport, the headline wraps
               into many short lines, and because both columns are bottom-
               aligned the now-much-taller headline column collides with the
               paragraph beside it. Stack and align to start.
               The artifact FRAMES themselves are NOT stacked: they are wrapped
               in <ScaleFrame>, which shrinks the whole fixed-canvas mockup to
               fit. Only this header is plain marketing copy. */
            @media (max-width: 860px) {
              .jrn-import-grid { grid-template-columns: minmax(0, 1fr) !important; }
              .jrn-artifact-header { grid-template-columns: minmax(0, 1fr) !important; align-items: start !important; }
            }
          `}</style>
        </div>
      </section>
    );
  };

  // ============== CAMPAIGN AUDIT ARTIFACT ==============
  const AUDIT_CHECKS = [
    { group: "Content Integrity", items: [
      "Template has sufficient content",
      "All links have valid href values",
      "No placeholder domains detected",
      "All images have valid src values",
      "All images have alt text",
    ]},
    { group: "Deliverability", items: [
      "Unsubscribe link present",
      "Preferences link present",
      "Domain \"hotelinking.com\" is verified",
    ]},
    { group: "Audience &amp; Settings", items: [
      "2,630 recipients will receive this campaign",
      "Subject line length is good (52 chars)",
      "No spam trigger words detected",
      "Sender name and reply-to set",
    ]},
  ];

  const CampaignAuditArtifact = () => {
    const [ref, seen] = useInView(0.15);
    const [revealed, setRevealed] = eUseState(0);
    const total = AUDIT_CHECKS.reduce((a, g) => a + g.items.length, 0);

    eUseEffect(() => {
      if (!seen) return;
      let i = 0;
      const t = setInterval(() => {
        i += 1;
        setRevealed(i);
        if (i >= total) clearInterval(t);
      }, 240);
      return () => clearInterval(t);
    }, [seen]);

    return (
      <section ref={ref} style={{ background: "#fff", padding: "100px 24px 100px" }}>
        <div style={{ maxWidth: 1480, margin: "0 auto" }}>
          <div className="jrn-artifact-header" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", alignItems: "end", gap: 48, marginBottom: 36 }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 18 }}>
                04 · CAMPAIGN WIZARD &amp; AI AUDIT
              </div>
              <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(24px, 4vw, 56px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
                Catch the mistake <span style={{ fontStyle: "italic", color: E_PINK }}>before send.</span>
              </h3>
            </div>
            <div style={{ paddingBottom: 8 }}>
              <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", margin: 0, maxWidth: 540 }}>
                The wizard walks teams through basics, goal, audience, template, subject, settings, and schedule. The final step runs a 12-point AI audit, broken images, missing alt text, spam triggers, unverified domains, empty links, every issue surfaced before a single guest gets the email.
              </p>
            </div>
          </div>

          {/* Wizard step strip */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "20px 28px", background: E_CREAM, borderRadius: 12, marginBottom: 24 }}>
            {["Basics", "Goal", "Audience", "Template", "Subject", "Settings", "Schedule", "Review"].map((s, i) => {
              const active = i === 7;
              const done = i < 7;
              return (
                <React.Fragment key={s}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <div style={{
                      width: 28, height: 28, borderRadius: 99,
                      background: active ? E_PINK : done ? "#fff" : "#fff",
                      border: `2px solid ${active ? E_PINK : done ? E_PINK : "#e2e8f0"}`,
                      display: "grid", placeItems: "center",
                      color: active ? "#fff" : done ? E_PINK : "#94a3b8",
                    }}>
                      {done ? <Icon name="check" size={14}/> : <span style={{ fontSize: 11, fontWeight: 700 }}>{i+1}</span>}
                    </div>
                    <span style={{ fontSize: 12, fontWeight: active ? 700 : 500, color: active ? E_INK : done ? "#475569" : "#94a3b8" }}>{s}</span>
                  </div>
                  {i < 7 && <div style={{ flex: 1, height: 1.5, background: done ? E_PINK : "#e2e8f0", margin: "0 10px" }} />}
                </React.Fragment>
              );
            })}
          </div>

          {/* Two-pane: audit + email preview */}
          <div style={{
            display: "grid", gridTemplateColumns: "1.05fr 1fr", gap: 24, alignItems: "stretch",
          }}>
            {/* Audit panel */}
            <div style={{
              background: E_INK, color: "#fff", borderRadius: 18, padding: 28,
              boxShadow: "0 30px 60px -20px rgba(15,23,42,.35)", display: "flex", flexDirection: "column",
            }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
                <div>
                  <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: ".2em", color: E_PINK, marginBottom: 6 }}>FINAL REVIEW · AI CAMPAIGN AUDIT</div>
                  <div style={{ fontSize: 20, fontWeight: 700, lineHeight: 1.1, letterSpacing: "-0.01em" }}>All checks passed.</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end" }}>
                  <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 40, fontWeight: 400, lineHeight: 1, color: E_PINK }}>{revealed}<span style={{ color: "#475569" }}>/{total}</span></div>
                  <div style={{ fontSize: 9, letterSpacing: ".2em", color: "#94a3b8", marginTop: 3 }}>VERIFIED</div>
                </div>
              </div>

              {AUDIT_CHECKS.map((g, gi) => {
                let offset = 0;
                for (let k = 0; k < gi; k++) offset += AUDIT_CHECKS[k].items.length;
                return (
                  <div key={g.group} style={{ marginBottom: 14 }}>
                    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".18em", color: "#cbd5e1", padding: "8px 0", borderBottom: "1px solid rgba(255,255,255,.08)", marginBottom: 6 }} dangerouslySetInnerHTML={{ __html: g.group }} />
                    {g.items.map((it, ii) => {
                      const idx = offset + ii;
                      const shown = revealed > idx;
                      return (
                        <div key={ii} style={{
                          display: "flex", alignItems: "center", gap: 10,
                          padding: "6px 4px",
                          opacity: shown ? 1 : 0.25,
                          transform: shown ? "translateY(0)" : "translateY(4px)",
                          transition: "all .25s ease-out",
                        }}>
                          <div style={{
                            width: 18, height: 18, borderRadius: 99,
                            background: shown ? "rgba(34,197,94,.18)" : "rgba(255,255,255,.06)",
                            color: shown ? "#22c55e" : "#475569",
                            display: "grid", placeItems: "center", flexShrink: 0,
                          }}>
                            {shown ? <Icon name="check" size={12} /> : <Icon name="clock" size={11} />}
                          </div>
                          <div style={{ fontSize: 12.5, color: shown ? "#e2e8f0" : "#475569" }}>{it}</div>
                        </div>
                      );
                    })}
                  </div>
                );
              })}

              <div style={{ marginTop: "auto", paddingTop: 16, borderTop: "1px solid rgba(255,255,255,.08)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <div style={{ fontSize: 11, color: "#94a3b8" }}>Wed, May 13 2026 · 7:00 PM CET</div>
                <button style={{ background: E_PINK, color: "#fff", border: "none", padding: "10px 18px", borderRadius: 8, fontSize: 12, fontWeight: 700, letterSpacing: ".06em", display: "inline-flex", alignItems: "center", gap: 8 }}>
                  <Icon name="clock" size={13} color="#fff" /> SCHEDULE CAMPAIGN
                </button>
              </div>
            </div>

            {/* Email preview */}
            <div style={{
              background: E_CREAM, borderRadius: 18, padding: 28, display: "flex", justifyContent: "center", alignItems: "flex-start",
              border: "1px solid " + E_CREAM_BORDER, overflow: "hidden",
            }}>
              <div style={{ transform: "scale(1.05)", transformOrigin: "top center" }}>
                <GeneratedEmailPreview />
              </div>
            </div>
          </div>
          </ScaleFrame>

          <div style={{ marginTop: 30, textAlign: "center", fontSize: 12.5, color: "#94a3b8", display: "inline-flex", alignItems: "center", gap: 14, justifyContent: "center", width: "100%" }}>
            <span style={{ width: 40, height: 1, background: E_CREAM_BORDER }} />
            12 deliverability checks · 8 content checks · subject scoring · spam-trigger detection
            <span style={{ width: 40, height: 1, background: E_CREAM_BORDER }} />
          </div>
        </div>
      </section>
    );
  };

  // ============== MAIN EMAIL SECTION ==============
  const EmailSection = () => (
    <>
      <EmailIntro />
      <GalleryArtifact />
      <AIStudioArtifact />
      <ImportFlow />
      {typeof CampaignWizardArtifact !== "undefined" ? <CampaignWizardArtifact /> : <CampaignAuditArtifact />}
    </>
  );

  window.EmailSection = EmailSection;

  /* ===== campaign_wizard.jsx ===== */

  // ============== CAMPAIGN WIZARD ARTIFACT (live, multi-step) ==============
  const CW_NAME = "Black Friday - Aurea Hotels (EN)";

  const CW_SEGMENTS = [
    { n: "Loyalty Members: Gold & Platinum", c: "8,420", d: "Repeat guests with 3+ stays" },
    { n: "Past Guests: Mediterranean Resorts", c: "12,108", d: "Stayed in Ibiza, Mallorca or Marbella" },
    { n: "Newsletter Opt-In: EN", c: "24,630", d: "English-speaking subscribers" },
    { n: "High-Spend Travelers", c: "3,945", d: "ADR above €420 in last 24 months" },
    { n: "Bleisure Guests: Mid-week", c: "2,712", d: "Mon\u2013Thu business stays" },
    { n: "Family Travelers: Summer", c: "9,184", d: "Booked 2+ adults & 1+ child" },
  ];

  const CW_AUDIT = [
    { g: "Content Integrity", items: ["Template has sufficient content", "All links have valid href values", "No placeholder domains detected", "All images have alt text"] },
    { g: "Deliverability", items: ["Unsubscribe link present", "Preferences link present", 'Domain "aureahotels.com" is verified'] },
    { g: "Audience & Settings", items: ["8,420 recipients will receive this campaign", "Subject line length is good (52 chars)", "No spam trigger words detected", "Sender name and reply-to set", "Booking Protection: Active Booking enabled"] },
  ];

  const CW_STEPS = ["Basics", "Goal", "Audience", "Subject", "Settings", "Schedule", "Review"];

  const CampaignWizardArtifact = () => {
    const [ref, seen] = useInView(0.15);
    const [step, setStep] = eUseState(0);
    const [typed, setTyped] = eUseState("");
    const [revealed, setRevealed] = eUseState(0);
    const totalChecks = CW_AUDIT.reduce((a, g) => a + g.items.length, 0);

    eUseEffect(() => {
      if (!seen) return;
      let cancel = false;
      const wait = (ms) => new Promise(r => setTimeout(r, ms));
      (async () => {
        while (!cancel) {
          // Basics
          setStep(0); setTyped(""); setRevealed(0);
          await wait(900);
          for (let i = 1; i <= CW_NAME.length; i++) {
            if (cancel) return;
            setTyped(CW_NAME.slice(0, i));
            await wait(28);
          }
          await wait(1100);
          setStep(1); await wait(2200);
          setStep(2); await wait(2800);
          setStep(3); await wait(2000);
          setStep(4); await wait(2000);
          setStep(5); await wait(2000);
          setStep(6); setRevealed(0);
          for (let i = 1; i <= totalChecks; i++) {
            if (cancel) return;
            setRevealed(i);
            await wait(220);
          }
          await wait(4500);
        }
      })();
      return () => { cancel = true; };
    }, [seen]);

    const STEP_ICONS = ["edit", "tag", "users", "type", "settings", "clock", "check"];
    const stepLabel = (i) => CW_STEPS[i];
    const stepSubs = ["Name your campaign", "Select campaign goal", "Choose target segment", "Write subject line", "Configure sender", "Set send time", "Final review"];

    return (
      <section ref={ref} style={{ background: "#fff", padding: "100px 24px 100px" }}>
        <div style={{ maxWidth: 1320, margin: "0 auto" }}>
          <div className="jrn-artifact-header" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1fr)", alignItems: "end", gap: 48, marginBottom: 36 }}>
            <div>
              <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 18 }}>04 &middot; CAMPAIGN WIZARD &amp; AI AUDIT</div>
              <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(24px, 4vw, 56px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
                Catch the mistake <span style={{ fontStyle: "italic", color: E_PINK }}>before send.</span>
              </h3>
            </div>
            <div style={{ paddingBottom: 8 }}>
              <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", margin: 0, maxWidth: 540 }}>
                Seven guided steps walk teams from naming a campaign to a final 12-point audit, with realistic hotel segments, booking-protection rules, and deliverability checks built in.
              </p>
            </div>
          </div>

          {/* Wizard step strip */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "16px 22px", background: E_CREAM, borderRadius: 12, marginBottom: 18 }}>
            {CW_STEPS.map((s, i) => {
              const active = i === step;
              const done = i < step;
              return (
                <React.Fragment key={s}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4, minWidth: 0 }}>
                    <div style={{
                      width: 30, height: 30, borderRadius: 99,
                      background: active ? E_PINK : "#fff",
                      border: `2px solid ${active || done ? E_PINK : "#e2e8f0"}`,
                      display: "grid", placeItems: "center",
                      color: active ? "#fff" : done ? E_PINK : "#94a3b8",
                      transition: "all .3s",
                    }}>
                      {done ? <Icon name="check" size={14} /> : active ? <Icon name={STEP_ICONS[i] === "edit" ? "userEdit" : STEP_ICONS[i] === "settings" ? "sliders" : STEP_ICONS[i]} size={14} color="#fff"/> : <span style={{ fontSize: 11, fontWeight: 700 }}>{i + 1}</span>}
                    </div>
                    <span style={{ fontSize: 11, fontWeight: active ? 700 : 500, color: active ? E_INK : done ? "#475569" : "#94a3b8" }}>{s}</span>
                  </div>
                  {i < CW_STEPS.length - 1 && <div style={{ flex: 1, height: 1.5, background: done ? E_PINK : "#e2e8f0", margin: "0 8px", marginTop: -16 }} />}
                </React.Fragment>
              );
            })}
          </div>

          {/* Wizard body */}
          <div style={{
            background: "#fff", border: "1px solid " + E_CREAM_BORDER, borderRadius: 18,
            padding: "28px 32px", boxShadow: "0 24px 60px -30px rgba(15,23,42,.18)",
            minHeight: 520, maxHeight: 560, overflow: "auto", position: "relative",
          }}>
            <div style={{ marginBottom: 22 }}>
              <div style={{ fontSize: 20, fontWeight: 700, color: E_INK, lineHeight: 1.1, letterSpacing: "-0.01em" }}>{stepLabel(step)}</div>
              <div style={{ fontSize: 13, color: "#64748b", marginTop: 4 }}>{stepSubs[step]}</div>
            </div>

            {step === 0 && (
              <div style={{ animation: "fadeIn .3s" }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Campaign Name</div>
                <div style={{ border: `1.5px solid ${E_PINK}`, borderRadius: 10, padding: "14px 18px", boxShadow: `0 0 0 4px ${E_PINK_TINT}`, display: "flex", alignItems: "center", gap: 10, background: "#fff" }}>
                  <Icon name="userEdit" size={14} color="#94a3b8" />
                  <span style={{ fontSize: 14, color: E_INK }}>{typed}<span style={{ color: E_PINK, animation: "blink 1s infinite" }}>|</span></span>
                </div>
                <div style={{ fontSize: 12, color: "#94a3b8", marginTop: 8 }}>Give your campaign a descriptive name (minimum 3 characters)</div>
              </div>
            )}

            {step === 1 && (
              <div style={{ animation: "fadeIn .3s", display: "flex", flexDirection: "column", gap: 10 }}>
                {[
                  { n: "Promotional", t: "PROMOTIONAL", d: "Sales, discounts, special offers", ic: "tag", on: true },
                  { n: "Re-engagement", t: "PROMOTIONAL", d: "Win back inactive guests", ic: "userPlus" },
                  { n: "Newsletter", t: "NEWSLETTER", d: "Updates, news, curated content", ic: "bell" },
                  { n: "Announcement", t: "ANNOUNCEMENT", d: "New features, service updates, important news", ic: "flag" },
                  { n: "Pre-Arrival", t: "TRANSACTIONAL", d: "Welcome, check-in info, upsells", ic: "mail" },
                ].map((g, i) => (
                  <div key={i} style={{ padding: "14px 16px", border: g.on ? `1.5px solid ${E_PINK}` : "1px solid #e2e8f0", borderRadius: 10, background: g.on ? E_PINK_SOFT : "#fff", display: "flex", alignItems: "center", gap: 14 }}>
                    <div style={{ width: 22, height: 22, borderRadius: 99, border: g.on ? "none" : "1.5px solid #cbd5e1", background: g.on ? E_PINK : "transparent", display: "grid", placeItems: "center", flexShrink: 0 }}>
                      {g.on && <Icon name="check" size={12} color="#fff" />}
                    </div>
                    <Icon name={g.ic} size={16} color={g.on ? E_PINK : "#94a3b8"} />
                    <div style={{ flex: 1 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        <span style={{ fontSize: 14, fontWeight: 700, color: g.on ? E_PINK : E_INK }}>{g.n}</span>
                        <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".1em", padding: "3px 7px", borderRadius: 5, background: "#f1f5f9", color: "#64748b" }}>{g.t}</span>
                      </div>
                      <div style={{ fontSize: 12, color: "#64748b", marginTop: 2 }}>{g.d}</div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {step === 2 && (
              <div style={{ animation: "fadeIn .3s" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: E_INK }}>Select Audience Segment</div>
                  <div style={{ fontSize: 11, color: "#94a3b8" }}>6 of 20 segments</div>
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 18 }}>
                  {CW_SEGMENTS.map((s, i) => {
                    const on = i === 0;
                    return (
                      <div key={i} style={{ padding: "10px 14px", border: on ? `1.5px solid ${E_PINK}` : "1px solid #e2e8f0", borderRadius: 9, background: on ? E_PINK_SOFT : "#fff", display: "flex", alignItems: "center", gap: 12 }}>
                        <div style={{ width: 18, height: 18, borderRadius: 99, border: on ? "none" : "1.5px solid #cbd5e1", background: on ? E_PINK : "transparent", display: "grid", placeItems: "center", flexShrink: 0 }}>
                          {on && <Icon name="check" size={10} color="#fff" />}
                        </div>
                        <Icon name="users" size={13} color={on ? E_PINK : "#94a3b8"} />
                        <div style={{ flex: 1 }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                            <span style={{ fontSize: 13, fontWeight: 700, color: on ? E_PINK : E_INK }}>{s.n}</span>
                            <span style={{ fontSize: 10.5, padding: "2px 7px", borderRadius: 5, background: on ? "#fff" : "#f1f5f9", color: "#64748b", fontWeight: 600 }}>{s.c} contacts</span>
                          </div>
                          <div style={{ fontSize: 11.5, color: "#64748b", marginTop: 2 }}>{s.d}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
                {/* Booking Protection */}
                <div style={{ border: "1px solid " + E_CREAM_BORDER, borderRadius: 10, padding: 16 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
                    <Icon name="bookmark" size={14} color={E_INK} />
                    <span style={{ fontSize: 13, fontWeight: 700, color: E_INK }}>Booking Protection</span>
                  </div>
                  {[
                    { n: "Active Booking", d: "Exclude guests with any active booking (no time limit)", on: true },
                    { n: "Within Time Period", d: "Exclude guests with bookings within a specific number of days" },
                    { n: "No Protection", d: "Send to all guests regardless of bookings" },
                  ].map((b, i) => (
                    <div key={i} style={{ padding: "10px 12px", border: b.on ? `1.5px solid ${E_PINK}` : "1px solid #e2e8f0", borderRadius: 8, background: b.on ? E_PINK_SOFT : "#fff", display: "flex", alignItems: "center", gap: 10, marginTop: i ? 6 : 0 }}>
                      <div style={{ width: 16, height: 16, borderRadius: 99, border: b.on ? "none" : "1.5px solid #cbd5e1", background: b.on ? E_PINK : "transparent", display: "grid", placeItems: "center", flexShrink: 0 }}>
                        {b.on && <Icon name="check" size={9} color="#fff" />}
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12.5, fontWeight: 700, color: b.on ? E_PINK : E_INK }}>{b.n}</div>
                        <div style={{ fontSize: 11, color: "#64748b" }}>{b.d}</div>
                      </div>
                    </div>
                  ))}
                </div>
                <div style={{ marginTop: 12, padding: "10px 14px", background: E_PINK_SOFT, border: `1px solid ${E_PINK_TINT}`, borderRadius: 8, display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: E_INK }}>
                  <Icon name="users" size={13} color={E_PINK} />
                  <span><b>Estimated reach:</b> 8,420 contacts <span style={{ color: "#64748b" }}>(excluding guests with active bookings)</span></span>
                </div>
              </div>
            )}

            {step === 3 && (
              <div style={{ animation: "fadeIn .3s", display: "flex", flexDirection: "column", gap: 16 }}>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Subject Line</div>
                  <div style={{ border: `1.5px solid ${E_PINK}`, borderRadius: 10, padding: "14px 16px", boxShadow: `0 0 0 4px ${E_PINK_TINT}`, fontSize: 14, color: E_INK }}>Black Friday at Aurea: Up to 35% Off Beachfront Stays</div>
                  <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 6 }}>52 characters \u00b7 ideal length</div>
                </div>
                <div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Preview Text</div>
                  <div style={{ border: "1px solid #e2e8f0", borderRadius: 10, padding: "12px 16px", fontSize: 13, color: "#475569" }}>Three nights of indulgence on the Mediterranean. Book before Nov 30.</div>
                </div>
                <div style={{ padding: "12px 14px", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 8, display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "#166534" }}>
                  <Icon name="check" size={13} color="#22c55e" /> No spam trigger words detected
                </div>
              </div>
            )}

            {step === 4 && (
              <div style={{ animation: "fadeIn .3s", display: "flex", flexDirection: "column", gap: 14 }}>
                {[
                  { l: "Sender Name", v: "Aurea Hotels" },
                  { l: "From Address", v: "stay@aureahotels.com" },
                  { l: "Reply-To", v: "concierge@aureahotels.com" },
                ].map((f, i) => (
                  <div key={i}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: "#475569", marginBottom: 6 }}>{f.l}</div>
                    <div style={{ border: "1px solid #e2e8f0", borderRadius: 8, padding: "11px 14px", fontSize: 13, color: E_INK }}>{f.v}</div>
                  </div>
                ))}
                <div style={{ padding: "10px 14px", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 8, display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "#166534" }}>
                  <Icon name="check" size={13} color="#22c55e" /> Domain "aureahotels.com" is verified
                </div>
              </div>
            )}

            {step === 5 && (
              <div style={{ animation: "fadeIn .3s", display: "flex", flexDirection: "column", gap: 12 }}>
                {[
                  { n: "Send Immediately", d: "Campaign will start sending as soon as you confirm", ic: "bolt" },
                  { n: "Schedule for Later", d: "Choose a specific date and time to send", ic: "calendarPlus", on: true },
                ].map((o, i) => (
                  <div key={i} style={{ padding: "14px 16px", border: o.on ? `1.5px solid ${E_PINK}` : "1px solid #e2e8f0", borderRadius: 10, background: o.on ? E_PINK_SOFT : "#fff", display: "flex", alignItems: "center", gap: 12 }}>
                    <Icon name={o.ic} size={16} color={o.on ? E_PINK : "#94a3b8"} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 700, color: o.on ? E_PINK : E_INK }}>{o.n}</div>
                      <div style={{ fontSize: 12, color: "#64748b" }}>{o.d}</div>
                    </div>
                  </div>
                ))}
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#475569", marginBottom: 6 }}>DATE</div>
                    <div style={{ border: "1px solid #e2e8f0", borderRadius: 8, padding: "10px 14px", fontSize: 13, color: E_INK, display: "flex", alignItems: "center", gap: 8 }}><Icon name="calendarPlus" size={13} color="#94a3b8"/> November 27th, 2026</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 11, fontWeight: 600, color: "#475569", marginBottom: 6 }}>TIME</div>
                    <div style={{ border: "1px solid #e2e8f0", borderRadius: 8, padding: "10px 14px", fontSize: 13, color: E_INK }}>09:00 \u00b7 Europe/Madrid</div>
                  </div>
                </div>
                <div style={{ padding: "10px 14px", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 8, display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "#166534" }}>
                  <Icon name="calendarCheck" size={13} color="#22c55e" /> Scheduled for: Friday, November 27th, 2026 at 9:00 AM
                </div>
              </div>
            )}

            {step === 6 && (
              <div style={{ animation: "fadeIn .3s" }}>
                <div style={{ padding: "12px 16px", background: "#f0fdf4", border: "1px solid #bbf7d0", borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <Icon name="check" size={16} color="#22c55e" />
                    <span style={{ fontSize: 13.5, fontWeight: 700, color: "#166534" }}>All checks passed, ready to send</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: "#166534" }}>{revealed}<span style={{ opacity: .5 }}>/{totalChecks}</span></div>
                </div>
                {CW_AUDIT.map((g, gi) => {
                  let off = 0; for (let k = 0; k < gi; k++) off += CW_AUDIT[k].items.length;
                  return (
                    <div key={gi} style={{ marginBottom: 14 }}>
                      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".1em", color: E_INK, padding: "6px 0", borderBottom: "1px solid #f1f5f9", marginBottom: 4, textTransform: "uppercase" }}>{g.g}</div>
                      {g.items.map((it, ii) => {
                        const idx = off + ii;
                        const on = revealed > idx;
                        return (
                          <div key={ii} style={{ display: "flex", alignItems: "center", gap: 10, padding: "5px 4px", opacity: on ? 1 : .35, transition: "all .2s" }}>
                            <div style={{ width: 16, height: 16, borderRadius: 99, background: on ? "#dcfce7" : "#f1f5f9", color: on ? "#22c55e" : "#cbd5e1", display: "grid", placeItems: "center", flexShrink: 0 }}>
                              {on ? <Icon name="check" size={10} /> : <Icon name="clock" size={9} />}
                            </div>
                            <div style={{ fontSize: 12.5, color: on ? E_INK : "#94a3b8" }}>{it}</div>
                          </div>
                        );
                      })}
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Bottom action bar */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 4px", marginTop: 16 }}>
            <div style={{ display: "flex", gap: 10 }}>
              <button style={{ height: 36, padding: "0 14px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#fff", fontSize: 12, fontWeight: 600, color: "#475569", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="x" size={12}/> Exit</button>
              <button style={{ height: 36, padding: "0 14px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#fff", fontSize: 12, fontWeight: 600, color: "#475569" }}>Save Draft</button>
            </div>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <span style={{ fontSize: 11, color: "#94a3b8" }}>Step {step + 1} of {CW_STEPS.length}</span>
              <button style={{ height: 36, padding: "0 14px", borderRadius: 8, border: "1px solid #e2e8f0", background: "#fff", fontSize: 12, fontWeight: 600, color: "#475569" }}>Back</button>
              <button style={{ height: 36, padding: "0 18px", borderRadius: 8, border: "none", background: step === 6 ? E_PINK : E_INK, color: "#fff", fontSize: 12, fontWeight: 700, display: "inline-flex", alignItems: "center", gap: 6 }}>
                {step === 6 ? <><Icon name="clock" size={12} color="#fff"/> Schedule Campaign</> : <>Next <Icon name="login" size={11} color="#fff"/></>}
              </button>
            </div>
          </div>
          </ScaleFrame>
        </div>
        <style>{`
          @keyframes blink { 50% { opacity: 0 } }
        `}</style>
      </section>
    );
  };

  window.CampaignWizardArtifact = CampaignWizardArtifact;

  /* ===== whatsapp.jsx ===== */

  // ============== WHATSAPP SECTION (intro + AI Studio) ==============
  // Matches the pink/cream/dark aesthetic used by email.jsx, relies on the
  // E_PINK / E_INK / useInView / eUseState / eUseEffect / eUseRef helpers
  // already defined in email.jsx (loaded earlier in the page).

  // WhatsApp brand
  const WA_GREEN = "#25D366";
  const WA_GREEN_DEEP = "#128C7E";
  const WA_BUBBLE_BG = "#202C33";
  const WA_CHAT_BG = "#0B141A";
  const WA_HEADER_BG = "#1F2C33";
  const WA_OUT_BUBBLE = "#005C4B";

  // ============== PHONE FRAME (reusable) ==============
  const WAPhone = ({ children, time = "04:48 PM", height = 600 }) => (
    <div style={{
      width: 280, background: WA_CHAT_BG, borderRadius: 38,
      padding: "10px 8px 8px", border: "8px solid #0a0e12",
      boxShadow: "0 30px 60px -20px rgba(0,0,0,.45), 0 8px 24px rgba(0,0,0,.18)",
      position: "relative", flexShrink: 0,
    }}>
      {/* Status bar */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "4px 14px 8px", color: "#fff", fontSize: 11, fontWeight: 600 }}>
        <span>{time}</span>
        <div style={{ width: 80, height: 22, background: "#000", borderRadius: 99, position: "relative" }}>
          <div style={{ position: "absolute", right: 8, top: 6, width: 10, height: 10, borderRadius: 99, background: "#1a1a1a", border: "1px solid #333" }} />
        </div>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
          <svg width="14" height="10" viewBox="0 0 14 10" fill="#fff"><rect x="0" y="6" width="2" height="4"/><rect x="3" y="4" width="2" height="6"/><rect x="6" y="2" width="2" height="8"/><rect x="9" y="0" width="2" height="10"/></svg>
          <svg width="14" height="10" viewBox="0 0 14 10" fill="#fff"><path d="M7 2.5a4 4 0 014 4h-1a3 3 0 00-6 0H3a4 4 0 014-4z"/><circle cx="7" cy="7.5" r="1.2"/></svg>
          <div style={{ width: 22, height: 10, border: "1.2px solid #fff", borderRadius: 2, position: "relative", padding: 1 }}>
            <div style={{ width: "100%", height: "100%", background: "#fff", borderRadius: 1 }} />
            <div style={{ position: "absolute", right: -3, top: 2, width: 2, height: 4, background: "#fff", borderRadius: "0 1px 1px 0" }} />
          </div>
        </span>
      </div>
      {/* Chat header */}
      <div style={{ background: WA_HEADER_BG, padding: "10px 12px", display: "flex", alignItems: "center", gap: 10, borderRadius: "14px 14px 0 0" }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4"><polyline points="15 18 9 12 15 6"/></svg>
        <div style={{ width: 32, height: 32, borderRadius: 99, background: WA_GREEN, color: "#fff", display: "grid", placeItems: "center", fontWeight: 700, fontSize: 13 }}>B</div>
        <div style={{ flex: 1 }}>
          <div style={{ color: "#fff", fontSize: 13.5, fontWeight: 600 }}>Business Name</div>
          <div style={{ color: "#a8b3ba", fontSize: 11 }}>online</div>
        </div>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2"/></svg>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0122 16.92z"/></svg>
        <span style={{ color: "#fff", fontSize: 16, lineHeight: 1, transform: "translateY(-2px)" }}>⋮</span>
      </div>
      {/* Body */}
      <div style={{
        background: WA_CHAT_BG, height, padding: "14px 10px",
        backgroundImage: "radial-gradient(circle at 20% 20%, rgba(255,255,255,.012) 1px, transparent 1px), radial-gradient(circle at 70% 60%, rgba(255,255,255,.012) 1px, transparent 1px)",
        backgroundSize: "40px 40px",
        overflow: "hidden", position: "relative",
      }}>
        {children}
      </div>
      {/* Composer */}
      <div style={{ background: WA_HEADER_BG, padding: "8px 10px", display: "flex", alignItems: "center", gap: 6, borderRadius: "0 0 14px 14px" }}>
        <div style={{ flex: 1, background: "#2a3942", borderRadius: 99, padding: "7px 12px", fontSize: 11, color: "#8696a0" }}>Type a message</div>
        <div style={{ width: 30, height: 30, borderRadius: 99, background: WA_GREEN, display: "grid", placeItems: "center" }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="#fff"><path d="M12 2a3 3 0 00-3 3v7a3 3 0 006 0V5a3 3 0 00-3-3zM5 12a7 7 0 0014 0M12 19v3"/></svg>
        </div>
      </div>
    </div>
  );

  // ============== WHATSAPP TEMPLATE BUBBLE ==============
  const WATemplateBubble = ({ header, body, footer, buttons, hasImage, time = "04:48 PM" }) => (
    <div style={{
      background: WA_BUBBLE_BG, borderRadius: 8, borderTopLeftRadius: 0,
      padding: hasImage ? 4 : "8px 10px 6px", color: "#e9edef", fontSize: 12, lineHeight: 1.45,
      width: "94%", boxShadow: "0 1px 0.5px rgba(0,0,0,.13)",
    }}>
      {hasImage && (
        <div style={{ width: "100%", height: 120, borderRadius: 6, marginBottom: 6, backgroundImage: "url(\"/preview/homepage-v3/assets/wa-template-hotel-seaview.jpg\")", backgroundSize: "cover", backgroundPosition: "center" }}/>
      )}
      <div style={{ padding: hasImage ? "0 8px 6px" : 0 }}>
        {header && <div style={{ fontWeight: 700, color: "#fff", marginBottom: 4 }}>{header}</div>}
        {body && <div style={{ whiteSpace: "pre-line" }}>{body}</div>}
        {footer && <div style={{ marginTop: 6, fontSize: 11, color: "#8696a0" }}>{footer}</div>}
        <div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 4, fontSize: 10, color: "#8696a0", marginTop: 4 }}>
          {time}
          <svg width="14" height="10" viewBox="0 0 14 10" fill="#53bdeb"><path d="M0 5L2 7L7 1.5M5 5L7 7L13 1"/></svg>
        </div>
      </div>
      {buttons && buttons.length > 0 && (
        <div style={{ marginTop: 6, borderTop: "1px solid rgba(255,255,255,.08)", paddingTop: 6, marginLeft: hasImage ? 4 : 0, marginRight: hasImage ? 4 : 0, marginBottom: hasImage ? 4 : 0 }}>
          {buttons.map((b, i) => (
            <div key={i} style={{ padding: "7px 0", textAlign: "center", color: "#53bdeb", fontSize: 12, fontWeight: 500, borderTop: i > 0 ? "1px solid rgba(255,255,255,.08)" : "none", display: "inline-flex", alignItems: "center", gap: 6, justifyContent: "center", width: "100%" }}>
              {b.icon === "link" && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#53bdeb" strokeWidth="2.4"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>}
              {b.icon === "phone" && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#53bdeb" strokeWidth="2.4"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0122 16.92z"/></svg>}
              {b.icon === "reply" && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#53bdeb" strokeWidth="2.4"><polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 00-4-4H4"/></svg>}
              {b.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );

  // ============== WHATSAPP INTRO ==============
  const WhatsAppIntro = () => (
    <section style={{ background: E_CREAM, padding: "120px 24px 40px", textAlign: "center" }}>
      <div style={{ maxWidth: 880, margin: "0 auto" }}>
        <div style={{ fontSize: 12.5, fontWeight: 600, letterSpacing: ".24em", color: E_PINK, marginBottom: 22, display: "inline-flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 28, height: 1.5, background: E_PINK }} /> WHATSAPP &middot; OFFICIAL META TECH PROVIDER <span style={{ width: 28, height: 1.5, background: E_PINK }} />
        </div>
        <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(30px, 5.4vw, 76px)", lineHeight: 1.0, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
          Approved on the first try.
        </h2>
        <h2 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(30px, 5.4vw, 76px)", lineHeight: 1.0, fontWeight: 400, fontStyle: "italic", color: E_PINK, margin: "0 0 24px", letterSpacing: "-0.01em" }}>
          Sent at the right hour.
        </h2>
        <p style={{ fontSize: 17, lineHeight: 1.55, color: "#475569", maxWidth: 760, margin: "0 auto 28px" }}>
          We audit every template against Meta&rsquo;s policy <em>before</em> submission, auto-throttle broadcasts to stay inside the rate limits, and pause sends during each guest&rsquo;s quiet hours, so your messages reach inboxes, not complaint queues.
        </p>
        {/* Trust strip */}
        <div style={{ display: "inline-flex", flexWrap: "wrap", gap: 10, justifyContent: "center" }}>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid " + E_CREAM_BORDER, borderRadius: 99, padding: "9px 16px", fontSize: 13, color: E_INK, fontWeight: 500 }}>
            <span style={{ width: 18, height: 18, borderRadius: 99, background: WA_GREEN, display: "grid", placeItems: "center" }}>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="#fff"><path d="M20.52 3.449C12.831-3.984.106 1.407.101 11.893c0 2.096.549 4.142 1.595 5.945L0 24l6.335-1.652a11.882 11.882 0 005.71 1.447h.006c10.493 0 16.965-12.5 11.987-19.875A12.062 12.062 0 0020.52 3.449z"/></svg>
            </span>
            Official Meta Tech Provider
          </div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid " + E_CREAM_BORDER, borderRadius: 99, padding: "9px 16px", fontSize: 13, color: E_INK, fontWeight: 500 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="2.4"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>
            Auto-submission to Meta
          </div>
          <div style={{ display: "inline-flex", alignItems: "center", gap: 8, background: "#fff", border: "1px solid " + E_CREAM_BORDER, borderRadius: 99, padding: "9px 16px", fontSize: 13, color: E_INK, fontWeight: 500 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="2.4"><path d="M9 11H5a2 2 0 00-2 2v7h6v-9zM15 7h-6v13h6V7zM21 13h-4a2 2 0 00-2 2v5h6v-7z"/></svg>
            AI compliance score before send
          </div>
        </div>
      </div>
    </section>
  );

  window.WhatsAppIntro = WhatsAppIntro;
  window.WAPhone = WAPhone;
  window.WATemplateBubble = WATemplateBubble;
  window.WA_GREEN = WA_GREEN;
  window.WA_GREEN_DEEP = WA_GREEN_DEEP;
  window.WA_BUBBLE_BG = WA_BUBBLE_BG;
  window.WA_CHAT_BG = WA_CHAT_BG;
  window.WA_HEADER_BG = WA_HEADER_BG;

  /* ===== whatsapp_studio.jsx ===== */

  // ============== WHATSAPP AI TEMPLATE STUDIO ARTIFACT ==============
  // 5-step wizard: Use Case → Prompt → Options → Generate → Results
  // Loops automatically.

  const WA_USE_CASES = [
    { name: "Welcome Message", icon: "msg", desc: "Greet new guests after booking confirmation" },
    { name: "Booking Confirmation", icon: "cal", desc: "Confirm reservation details with all information" },
    { name: "Check-in Day Reminder", icon: "key", desc: "Remind guests about check-in on arrival day" },
    { name: "Checkout Reminder", icon: "logout", desc: "Remind guests about checkout time and process" },
    { name: "Seasonal Promotion", icon: "gift", desc: "Promote seasonal packages and deals" },
    { name: "Feedback Request", icon: "msg", desc: "Request guest feedback after stay" },
  ];

  const WA_CATEGORIES = [
    { name: "Welcome & Onboarding", desc: "First impressions and guest onboarding messages", count: 2, icon: "msg" },
    { name: "Booking & Reservations", desc: "Confirmations, modifications, and cancellations", count: 3, icon: "cal" },
    { name: "Check-in", desc: "Arrival day messages and room ready notifications", count: 2, icon: "key" },
    { name: "Check-out", desc: "Departure reminders and post-stay messages", count: 2, icon: "logout" },
    { name: "Offers & Promotions", desc: "Marketing promotions and special offers", count: 3, icon: "gift" },
    { name: "Feedback & Reviews", desc: "Collect feedback and encourage reviews", count: 2, icon: "msg" },
    { name: "Reminders & Alerts", desc: "Appointment and service reminders", count: 3, icon: "bell" },
    { name: "Service & Support", desc: "Service confirmations and issue resolution", count: 2, icon: "support" },
  ];

  const WA_GEN_CHECKS = [
    "Analyzing your prompt",
    "Building context",
    "Generating templates",
    "Scoring compliance & quality",
    "Finalizing results",
  ];

  const WA_TYPING_PROMPT = "Booking confirmation with reservation details and confirmation number for guests at our 5-star resort. Include check-in/out dates, room type, total amount, and a clear cancellation policy.";

  const WAStepIcon = ({ name, color = "#475569", size = 16 }) => {
    const stroke = { fill: "none", stroke: color, strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round" };
    const filled = { fill: color };
    if (name === "msg") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>;
    if (name === "cal") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>;
    if (name === "key") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 11-7.778 7.778 5.5 5.5 0 017.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>;
    if (name === "logout") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/></svg>;
    if (name === "gift") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><polyline points="20 12 20 22 4 22 4 12"/><rect x="2" y="7" width="20" height="5"/><line x1="12" y1="22" x2="12" y2="7"/><path d="M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z"/></svg>;
    if (name === "bell") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 01-3.46 0"/></svg>;
    if (name === "support") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><path d="M3 18v-6a9 9 0 0118 0v6"/><path d="M21 19a2 2 0 01-2 2h-1v-6h3zM3 19a2 2 0 002 2h1v-6H3z"/></svg>;
    if (name === "check") return <svg width={size} height={size} viewBox="0 0 24 24" {...stroke}><polyline points="20 6 9 17 4 12"/></svg>;
    if (name === "spark") return <svg width={size} height={size} viewBox="0 0 24 24" {...filled}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>;
    return null;
  };

  // Brand fuchsia only, alias to E_PINK from email.jsx so all "AI" / "approval" surfaces use brand
  const WA_AI_PURPLE = E_PINK;
  const WA_AI_PURPLE_SOFT = E_PINK_SOFT;
  // Override green-deep usage in OUR UI (not in the actual WhatsApp phone bubble) with fuchsia
  const WA_OK = E_PINK;
  const WA_OK_SOFT = E_PINK_SOFT;

  const WAStudioArtifact = () => {
    const [ref, seen] = useInView(0.15);
    // Phases: 0 idle, 1 use-case grid, 2 selected booking confirmation,
    // 3 prompt typing, 4 options, 5 generating (with checklist filling),
    // 6 results revealed, 7 settle, then loop
    const [phase, setPhase] = eUseState(0);
    const [loopKey, setLoopKey] = eUseState(0);
    const [typed, setTyped] = eUseState("");
    const [genStep, setGenStep] = eUseState(0);
    const [genProgress, setGenProgress] = eUseState(0);

    eUseEffect(() => {
      if (!seen) return;
      const timeline = [
        [400, 1],   // step 1 use case appears
        [1800, 2],  // booking confirmation selected
        [2900, 3],  // step 2 prompt typing
        [6500, 4],  // step 3 options
        [8400, 5],  // step 4 generating
        [13200, 6], // step 5 results
        [21000, 7], // settle
        [25000, 0], // loop back
      ];
      const ts = timeline.map(([d, p]) => setTimeout(() => setPhase(p), d));
      ts.push(setTimeout(() => setLoopKey(k => k + 1), timeline[timeline.length - 1][0] + 100));
      return () => ts.forEach(clearTimeout);
    }, [seen, loopKey]);

    // Reset on loop
    eUseEffect(() => {
      if (phase === 0) {
        setTyped(""); setGenStep(0); setGenProgress(0);
      }
    }, [phase]);

    // Typing animation
    eUseEffect(() => {
      if (phase !== 3) return;
      let i = 0;
      const id = setInterval(() => {
        i += 3;
        setTyped(WA_TYPING_PROMPT.slice(0, i));
        if (i >= WA_TYPING_PROMPT.length) clearInterval(id);
      }, 28);
      return () => clearInterval(id);
    }, [phase]);

    // Generation checklist + progress
    eUseEffect(() => {
      if (phase !== 5) return;
      const stepIds = WA_GEN_CHECKS.map((_, i) => setTimeout(() => setGenStep(i + 1), 700 + i * 800));
      const progId = setInterval(() => {
        setGenProgress((p) => (p >= 100 ? 100 : p + 2.5));
      }, 100);
      return () => { stepIds.forEach(clearTimeout); clearInterval(progId); };
    }, [phase]);

    const stepNum = phase >= 6 ? 5 : phase >= 5 ? 4 : phase >= 4 ? 3 : phase >= 3 ? 2 : 1;
    const stepName = ["", "Choose a Use Case", "Choose a Use Case", "Describe Your Template", "Configure Options", "Generating...", "Review Results", "Review Results"][phase] || "Choose a Use Case";

    return (
      <section ref={ref} style={{ background: E_CREAM, padding: "60px 24px 80px" }}>
        <div style={{ maxWidth: 1340, margin: "0 auto" }}>
          {/* Section header */}
          <div style={{ textAlign: "center", marginBottom: 36 }}>
            <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".22em", color: WA_AI_PURPLE, marginBottom: 14 }}>
              AI TEMPLATE STUDIO
            </div>
            <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(23px, 3.6vw, 50px)", lineHeight: 1.05, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
              Describe the message.<br/>
              <span style={{ fontStyle: "italic", color: WA_AI_PURPLE }}>We&rsquo;ll handle the policy.</span>
            </h3>
            <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", maxWidth: 620, margin: "18px auto 0" }}>
              One sentence in: an audited, variable-mapped, Meta-ready template out. No more rewriting bodies to dodge category rejections.
            </p>
          </div>

          {/* Studio artifact */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{
            background: "#fff", borderRadius: 18,
            boxShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
            border: "1px solid rgba(15,23,42,.06)", overflow: "hidden",
            height: 880, display: "grid", gridTemplateColumns: "240px 1fr",
          }}>
            {/* Sidebar: progress steps */}
            <div style={{ borderRight: "1px solid #f1f5f9", padding: "26px 20px", background: "#fafafa" }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8", marginBottom: 18 }}>PROGRESS</div>
              {["Use Case", "Prompt", "Options", "Generate", "Results"].map((label, i) => {
                const idx = i + 1;
                const sub = ["Choose template type", "Describe what you need", "Customize generation", "AI creates templates", "Review and select"][i];
                const done = stepNum > idx;
                const active = stepNum === idx;
                return (
                  <div key={i} style={{
                    display: "flex", alignItems: "flex-start", gap: 10, padding: "10px 10px",
                    marginBottom: 4, borderRadius: 8,
                    background: active ? "#f1f5f9" : "transparent",
                    transition: "background .3s",
                  }}>
                    <div style={{
                      width: 22, height: 22, borderRadius: 99, flexShrink: 0,
                      display: "grid", placeItems: "center", fontSize: 11, fontWeight: 700,
                      background: done ? E_INK : active ? E_INK : "#e2e8f0",
                      color: done || active ? "#fff" : "#94a3b8",
                    }}>
                      {done ? <WAStepIcon name="check" size={12} color="#fff"/> : idx}
                    </div>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 600, color: active || done ? E_INK : "#94a3b8" }}>{label}</div>
                      <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 2 }}>{sub}</div>
                    </div>
                  </div>
                );
              })}

              {/* Selections card (visible from step 3 onwards) */}
              {phase >= 4 && (
                <div style={{ marginTop: 24, padding: 14, background: "#fff", borderRadius: 10, border: "1px solid #f1f5f9", animation: "fadeIn .4s" }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: E_INK, marginBottom: 10 }}>Your Selections</div>
                  <div style={{ fontSize: 11, color: "#64748b", marginBottom: 2 }}>Use Case</div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Booking Confirmation</div>
                  <div style={{ fontSize: 11, color: "#64748b", marginBottom: 2 }}>Category</div>
                  <div style={{ display: "inline-block", fontSize: 10, fontWeight: 700, letterSpacing: ".1em", color: E_PINK, background: E_PINK_SOFT, padding: "3px 8px", borderRadius: 4, marginBottom: 8 }}>UTILITY</div>
                  <div style={{ fontSize: 11, color: "#64748b", marginBottom: 2 }}>Language</div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>English</div>
                  <div style={{ fontSize: 11, color: "#64748b", marginBottom: 2 }}>Variants</div>
                  <div style={{ fontSize: 12, fontWeight: 600, color: E_INK }}>1</div>
                </div>
              )}
            </div>

            {/* Main */}
            <div style={{ padding: "26px 32px", overflow: "hidden", position: "relative" }}>
              {/* Top: step number + label */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8, fontSize: 13 }}>
                <div style={{ color: "#64748b" }}>Step {stepNum} of 5</div>
                <div style={{ color: E_INK, fontWeight: 600 }}>{stepName}</div>
              </div>
              {/* Progress bar */}
              <div style={{ height: 4, background: "#f1f5f9", borderRadius: 99, overflow: "hidden", marginBottom: 24 }}>
                <div style={{ width: (stepNum / 5) * 100 + "%", height: "100%", background: E_INK, transition: "width .5s" }} />
              </div>

              {/* === STEP CONTENT === */}
              {/* Step 1: Use Case grid */}
              {phase >= 1 && phase <= 2 && (
                <div style={{ animation: "fadeIn .4s" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 6px" }}>What would you like to create?</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 18px" }}>Choose a use case to get started with AI-powered suggestions, or skip to write your own prompt.</p>
                  {/* Search */}
                  <div style={{ background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 10, padding: "11px 14px", display: "flex", alignItems: "center", gap: 8, marginBottom: 22 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    <span style={{ fontSize: 12.5, color: "#94a3b8" }}>Search use cases...</span>
                  </div>
                  {/* Popular Templates */}
                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 12, display: "flex", alignItems: "center", gap: 6 }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill={E_PINK}><path d="M12 2l1.5 5H19l-4 3 1.5 5-4.5-3.2L7.5 15 9 10 5 7h5.5z"/></svg>
                    Popular Templates
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, marginBottom: 22 }}>
                    {WA_USE_CASES.map((uc, i) => {
                      const isSelected = phase >= 2 && uc.name === "Booking Confirmation";
                      return (
                        <div key={i} style={{
                          border: "1px solid " + (isSelected ? E_INK : "#f1f5f9"),
                          borderRadius: 10, padding: "12px 14px", background: isSelected ? "#f8fafc" : "#fff",
                          boxShadow: isSelected ? "0 0 0 3px rgba(15,23,42,.06)" : "none",
                          transition: "all .3s",
                        }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                            <div style={{ width: 28, height: 28, borderRadius: 8, background: "#f8fafc", display: "grid", placeItems: "center" }}>
                              <WAStepIcon name={uc.icon} size={14}/>
                            </div>
                            <div style={{ flex: 1 }}>
                              <div style={{ fontSize: 12.5, fontWeight: 600, color: E_INK }}>{uc.name}</div>
                            </div>
                          </div>
                          <div style={{ fontSize: 11, color: "#64748b", marginTop: 6, lineHeight: 1.4 }}>{uc.desc}</div>
                        </div>
                      );
                    })}
                  </div>
                  {/* Browse by Category */}
                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 12 }}>Browse by Category</div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
                    {WA_CATEGORIES.slice(0, 8).map((cat, i) => (
                      <div key={i} style={{ border: "1px solid #f1f5f9", borderRadius: 10, padding: "12px 12px", background: "#fff" }}>
                        <div style={{ width: 26, height: 26, borderRadius: 7, background: "#f8fafc", display: "grid", placeItems: "center", marginBottom: 8 }}>
                          <WAStepIcon name={cat.icon} size={13}/>
                        </div>
                        <div style={{ fontSize: 11.5, fontWeight: 600, color: E_INK, marginBottom: 3 }}>{cat.name}</div>
                        <div style={{ fontSize: 10, color: "#64748b", lineHeight: 1.35, marginBottom: 8 }}>{cat.desc}</div>
                        <div style={{ display: "inline-block", fontSize: 10, color: "#475569", background: "#f1f5f9", padding: "2px 7px", borderRadius: 99, fontWeight: 500 }}>{cat.count} templates</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Step 2: Prompt */}
              {phase === 3 && (
                <div style={{ animation: "fadeIn .4s" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 6px" }}>Describe Your Template</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 18px" }}>Tell us what you want to create. Be specific about the purpose, tone, and any variables you need.</p>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
                    <span style={{ fontSize: 12, fontWeight: 600, color: E_INK }}>Your Prompt</span>
                    <span style={{ fontSize: 11, color: "#94a3b8" }}>{typed.length} characters</span>
                  </div>
                  <div style={{ border: "2px solid " + WA_AI_PURPLE, borderRadius: 10, padding: 14, minHeight: 180, fontSize: 13, lineHeight: 1.5, color: E_INK, background: "#fff" }}>
                    {typed}<span style={{ color: WA_AI_PURPLE, animation: "blink 1s infinite" }}>|</span>
                  </div>
                  <div style={{ marginTop: 12, display: "inline-flex", alignItems: "center", gap: 8, padding: "8px 14px", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12.5, color: E_INK, fontWeight: 500 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={WA_AI_PURPLE} strokeWidth="2.4"><path d="M15 4V2M15 16v-2M8 9h2M20 9h2M17.8 11.8L19 13M15 9h.01M17.8 6.2L19 5M3 21l9-9M12.2 6.2L11 5"/></svg>
                    Enhance with AI
                  </div>
                  <div style={{ marginTop: 22, padding: 16, border: "1px solid #f1f5f9", borderRadius: 10 }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: E_INK, marginBottom: 10 }}>Example Prompts</div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                      {[
                        "Welcome message for new hotel guests with room num...",
                        "Booking confirmation with reservation details and ...",
                        "Special offer for returning guests with 20% discou...",
                        "Check-out reminder with express checkout option",
                        "Restaurant reservation confirmation with time and ...",
                        "Spa appointment reminder with preparation instruct...",
                      ].map((p, i) => (
                        <div key={i} style={{ fontSize: 11.5, color: "#475569", background: "#f8fafc", border: "1px solid #f1f5f9", padding: "5px 10px", borderRadius: 99 }}>{p}</div>
                      ))}
                    </div>
                  </div>
                </div>
              )}

              {/* Step 3: Options (brief) */}
              {phase === 4 && (
                <div style={{ animation: "fadeIn .4s" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 6px" }}>Customize Generation</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 24px" }}>Fine-tune category, language, and variants before AI generation.</p>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Category</div>
                      <div style={{ display: "flex", gap: 8 }}>
                        {["Marketing", "Utility", "Authentication"].map((c, i) => {
                          const sel = c === "Utility";
                          return (
                            <div key={i} style={{
                              flex: 1, padding: "10px 12px", textAlign: "center",
                              border: "1.5px solid " + (sel ? E_PINK : "#f1f5f9"),
                              background: sel ? E_PINK_SOFT : "#fff",
                              borderRadius: 8, fontSize: 12, fontWeight: 600,
                              color: sel ? E_PINK : "#475569",
                            }}>{c}</div>
                          );
                        })}
                      </div>
                    </div>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Language</div>
                      <div style={{ padding: "10px 12px", border: "1.5px solid #f1f5f9", borderRadius: 8, fontSize: 12.5, color: E_INK, fontWeight: 600 }}>English</div>
                    </div>
                  </div>
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Number of Variants</div>
                    <div style={{ display: "flex", gap: 8 }}>
                      {[1, 2, 3].map((n) => {
                        const sel = n === 1;
                        return (
                          <div key={n} style={{
                            flex: 1, padding: "12px 12px", textAlign: "center",
                            border: "1.5px solid " + (sel ? E_INK : "#f1f5f9"),
                            background: sel ? "#f8fafc" : "#fff",
                            borderRadius: 8, fontSize: 13, fontWeight: 600, color: E_INK,
                          }}>{n}</div>
                        );
                      })}
                    </div>
                  </div>
                  <div style={{ marginBottom: 14 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>Tone</div>
                    <div style={{ display: "flex", gap: 8 }}>
                      {["Friendly", "Professional", "Warm", "Concise"].map((t, i) => {
                        const sel = t === "Warm";
                        return (
                          <div key={i} style={{
                            padding: "8px 14px",
                            border: "1.5px solid " + (sel ? E_INK : "#f1f5f9"),
                            background: sel ? "#f8fafc" : "#fff",
                            borderRadius: 99, fontSize: 12, fontWeight: 600, color: E_INK,
                          }}>{t}</div>
                        );
                      })}
                    </div>
                  </div>
                  <div style={{ marginTop: 22, padding: 14, background: WA_AI_PURPLE_SOFT, border: "1px solid " + WA_AI_PURPLE, borderRadius: 10, fontSize: 12, color: "#581c87", display: "flex", gap: 10, alignItems: "flex-start" }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill={WA_AI_PURPLE} style={{ flexShrink: 0, marginTop: 1 }}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>
                    <div><b>Smart suggestion:</b> Utility templates have a 23% higher Meta approval rate than Marketing for confirmation messages.</div>
                  </div>
                </div>
              )}

              {/* Step 4: Generating */}
              {phase === 5 && (
                <div style={{ animation: "fadeIn .4s", textAlign: "center", padding: "20px 0" }}>
                  <div style={{
                    width: 90, height: 90, margin: "0 auto 20px", borderRadius: 99,
                    background: WA_AI_PURPLE_SOFT, display: "grid", placeItems: "center",
                    position: "relative", animation: "float 2s ease-in-out infinite",
                  }}>
                    <svg width="38" height="38" viewBox="0 0 24 24" fill={WA_AI_PURPLE}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>
                    <div style={{
                      position: "absolute", right: -2, bottom: -2,
                      width: 28, height: 28, borderRadius: 99, background: WA_AI_PURPLE, color: "#fff",
                      fontSize: 14, fontWeight: 700, display: "grid", placeItems: "center",
                      border: "3px solid #fff",
                    }}>C</div>
                  </div>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 6px" }}>Generating Your Templates</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 30px" }}>Our AI is crafting your template based on your specifications.</p>

                  <div style={{ maxWidth: 500, margin: "0 auto", padding: 20, background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 12 }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10, fontSize: 12 }}>
                      <span style={{ fontWeight: 600, color: E_INK }}>Overall Progress</span>
                      <span style={{ fontWeight: 700, color: E_INK }}>{Math.round(genProgress)}%</span>
                    </div>
                    <div style={{ height: 5, background: "#e2e8f0", borderRadius: 99, overflow: "hidden", marginBottom: 18 }}>
                      <div style={{ width: genProgress + "%", height: "100%", background: E_INK, transition: "width .25s linear" }} />
                    </div>
                    {WA_GEN_CHECKS.map((c, i) => {
                      const done = genStep > i + 1;
                      const active = genStep === i + 1;
                      return (
                        <div key={i} style={{
                          display: "flex", alignItems: "center", gap: 10,
                          padding: "10px 12px", borderRadius: 8, marginBottom: 6,
                          background: active ? "#f1f5f9" : "transparent",
                          opacity: !done && !active && i + 1 > genStep ? 0.4 : 1,
                          transition: "all .25s",
                        }}>
                          <div style={{ width: 20, height: 20, borderRadius: 99, background: done || active ? E_INK : "#e2e8f0", display: "grid", placeItems: "center" }}>
                            {done ? <WAStepIcon name="check" size={11} color="#fff"/> : active ? (
                              <span style={{ width: 8, height: 8, border: "1.5px solid #fff", borderTopColor: "transparent", borderRadius: 99, animation: "spin 0.8s linear infinite", display: "block" }}/>
                            ) : <span style={{ width: 6, height: 6, borderRadius: 99, background: "#94a3b8", display: "block" }}/>}
                          </div>
                          <div style={{ fontSize: 13, color: E_INK, fontWeight: active ? 600 : 500 }}>{c}</div>
                        </div>
                      );
                    })}
                  </div>
                  <div style={{ marginTop: 20, fontSize: 11, color: "#94a3b8" }}>Tip: You can generate multiple variants to A/B test different approaches.</div>
                </div>
              )}

              {/* Step 5: Results */}
              {phase >= 6 && (
                <div style={{ animation: "fadeIn .5s" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
                    <div>
                      <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Your Generated Templates</h4>
                      <p style={{ fontSize: 13, color: "#64748b", margin: 0 }}>Review your generated template and customize as needed.</p>
                    </div>
                    <div style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 14px", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12, color: E_INK, fontWeight: 500 }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2.4"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 11-2.12-9.36L23 10"/></svg>
                      Regenerate
                    </div>
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 18 }}>
                    {/* Phone preview */}
                    <div style={{ background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 12, padding: 22, position: "relative" }}>
                      <div style={{ position: "absolute", top: 14, left: 18, fontSize: 11, fontWeight: 600, color: E_INK }}>Template Preview</div>
                      <div style={{ position: "absolute", top: 12, right: 16, fontSize: 9, fontWeight: 700, letterSpacing: ".1em", background: E_PINK_SOFT, color: E_PINK, padding: "3px 8px", borderRadius: 4 }}>UTILITY</div>
                      <div style={{ display: "flex", justifyContent: "center", marginTop: 22 }}>
                        <WAPhone height={400} time="04:48 PM">
                          <div style={{ animation: "fadeInUp .6s .4s both" }}>
                            <WATemplateBubble
                              header="Reservation Confirmed"
                              body={"Dear {{1}},\n\nThank you for your booking. Your reservation has been successfully confirmed and we look forward to hosting you.\n\nReservation Number: {{2}}\nCheck-in: {{3}}\nCheck-out: {{4}}\nRoom Type: {{5}}\nTotal Amount: {{6}}\n\nCancellation Policy: Free cancellation is available until {{7}}. Cancellations made after this date will incur charges as per our policy.\n\nShould you have any questions or require assistance with your stay,"}
                              time="04:48 PM"
                            />
                          </div>
                        </WAPhone>
                      </div>
                    </div>

                    {/* Right: scores + details */}
                    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                      {/* Scores */}
                      <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 12, padding: 18 }}>
                        <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 16 }}>Quality Scores</div>
                        {[
                          { label: "Compliance Score", val: 100, color: E_PINK, sub: "Likelihood of Meta approval" },
                          { label: "Quality Score", val: 94, color: E_PINK, sub: "Overall template quality" },
                        ].map((s, i) => (
                          <div key={i} style={{ marginBottom: i === 0 ? 14 : 0 }}>
                            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
                              <span style={{ fontSize: 11.5, color: E_INK, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 5 }}>
                                <svg width="11" height="11" viewBox="0 0 24 24" fill={s.color}>{i === 0 ? <path d="M12 2L4 6v6c0 5.5 3.8 10.7 8 12 4.2-1.3 8-6.5 8-12V6z"/> : <path d="M12 2l3 6 6 1-4 4 1 6-6-3-6 3 1-6-4-4 6-1z"/>}</svg>
                                {s.label}
                              </span>
                              <span style={{ fontSize: 13, fontWeight: 700, color: s.color }}>{s.val}/100</span>
                            </div>
                            <div style={{ height: 5, background: "#f1f5f9", borderRadius: 99, overflow: "hidden", marginBottom: 4 }}>
                              <div style={{ width: phase >= 6 ? s.val + "%" : "0%", height: "100%", background: s.color, transition: "width 1.4s cubic-bezier(.4,1,.4,1) " + (i * 0.2) + "s" }} />
                            </div>
                            <div style={{ fontSize: 10.5, color: "#94a3b8" }}>{s.sub}</div>
                          </div>
                        ))}
                      </div>

                      {/* Template Details */}
                      <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 12, padding: 18 }}>
                        <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 12 }}>Template Details</div>
                        <div style={{ display: "flex", gap: 4, padding: 3, background: "#f8fafc", borderRadius: 8, marginBottom: 14 }}>
                          {["Info", "Variables", "AI Notes"].map((t, i) => (
                            <div key={i} style={{ flex: 1, textAlign: "center", padding: "6px 8px", fontSize: 11.5, fontWeight: 600, color: i === 0 ? E_INK : "#94a3b8", background: i === 0 ? "#fff" : "transparent", borderRadius: 6, boxShadow: i === 0 ? "0 1px 2px rgba(0,0,0,.05)" : "none" }}>{t}</div>
                          ))}
                        </div>
                        <div style={{ fontSize: 10.5, color: "#94a3b8", marginBottom: 3 }}>Suggested Name</div>
                        <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 10, fontFamily: "monospace", background: "#f8fafc", padding: "5px 8px", borderRadius: 6 }}>confirmed_reservation_summary</div>
                        <div style={{ fontSize: 10.5, color: "#94a3b8", marginBottom: 3 }}>Language</div>
                        <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 10 }}>en</div>
                        <div style={{ fontSize: 10.5, color: "#94a3b8", marginBottom: 3 }}>Body Length</div>
                        <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 10 }}>475 characters</div>
                        <div style={{ fontSize: 10.5, color: "#94a3b8", marginBottom: 3 }}>Buttons</div>
                        <div style={{ fontSize: 12, fontWeight: 600, color: E_INK }}>3</div>
                      </div>

                      <div style={{ display: "flex", gap: 8, marginTop: "auto" }}>
                        <div style={{ flex: 1, padding: "10px 12px", textAlign: "center", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12, fontWeight: 600, color: E_INK }}>Save as Draft</div>
                        <div style={{ flex: 1, padding: "10px 12px", textAlign: "center", background: E_INK, color: "#fff", borderRadius: 8, fontSize: 12, fontWeight: 600, display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill={WA_AI_PURPLE}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>
                          Use This Template
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Idle */}
              {phase === 0 && (
                <div style={{ display: "grid", placeItems: "center", height: 500 }}>
                  <div style={{ textAlign: "center", color: "#94a3b8" }}>
                    <div style={{ width: 64, height: 64, borderRadius: 16, background: WA_AI_PURPLE_SOFT, display: "grid", placeItems: "center", margin: "0 auto 14px" }}>
                      <svg width="30" height="30" viewBox="0 0 24 24" fill={WA_AI_PURPLE}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>
                    </div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: E_INK }}>AI Template Studio</div>
                    <div style={{ fontSize: 12, marginTop: 4 }}>Watch a one-line prompt become an audited, Meta-ready template, live.</div>
                  </div>
                </div>
              )}
            </div>
          </div>
          </ScaleFrame>

          <div style={{ textAlign: "center", marginTop: 18, fontSize: 12, color: "#94a3b8" }}>
            Five guided steps. Approval-aware AI. Editable output that lands directly in your template library.
          </div>
        </div>

        <style>{`
          @keyframes spin { to { transform: rotate(360deg); } }
          @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
        `}</style>
      </section>
    );
  };

  window.WAStudioArtifact = WAStudioArtifact;

  /* ===== whatsapp_editor.jsx ===== */

  // ============== WHATSAPP TEMPLATE EDITOR ARTIFACT ==============
  // 3-step flow: Setup → Design → Review (with AI compliance audit)
  // Animated through editing the body, switching the header type, adding
  // buttons, then a final compliance audit that scores 100/100.

  const WA_COMPLIANCE_CHECKS = [
    "Template name follows Meta guidelines",
    "Body text is within character limit",
    "Variables are sequential",
    "Body does not start with a variable",
    "Body does not end with a variable",
    "All variables have sample values",
    "Buttons configured correctly",
    "Template name is unique",
  ];

  const WA_BODY_TEXT = `Dear {{1}},

  Thank you for your booking. Your reservation has been successfully confirmed and we look forward to hosting you.

  Reservation Number: {{2}}
  Check-in: {{3}}
  Check-out: {{4}}
  Room Type: {{5}}
  Total Amount: {{6}}

  Cancellation Policy: Free cancellation is available until {{7}}. Cancellations made after this date will incur charges as per our policy.

  Should you have any questions or require assistance with your stay, please feel free to reach out to us anytime.`;

  const WA_SAMPLE_VALUES = [
    { var: "{{1}}", val: "John" },
    { var: "{{2}}", val: "UHK-987478" },
    { var: "{{3}}", val: "27th of August" },
    { var: "{{4}}", val: "2nd of September" },
    { var: "{{5}}", val: "Villa Sea View" },
    { var: "{{6}}", val: "3,567 EUR" },
    { var: "{{7}}", val: "25th of August" },
  ];

  const WAEditTemplateArtifact = () => {
    const [ref, seen] = useInView(0.15);
    // Phases:
    // 0 idle, 1 Setup briefly, 2 Design (typing body), 3 Add buttons,
    // 4 Switch header type to Image, 5 Footer fills,
    // 6 Review step (variables fill), 7 Compliance audit running,
    // 8 Likely Approved revealed, 9 settle, then loop
    const [phase, setPhase] = eUseState(0);
    const [loopKey, setLoopKey] = eUseState(0);
    const [body, setBody] = eUseState("");
    const [footerText, setFooterText] = eUseState("");
    const [headerText, setHeaderText] = eUseState("");
    const [auditStep, setAuditStep] = eUseState(0);
    const [filledVars, setFilledVars] = eUseState(0);

    eUseEffect(() => {
      if (!seen) return;
      const t = [
        [400, 1],   // Setup briefly
        [1700, 2],  // Design - typing header + body
        [5800, 3],  // Buttons appear
        [7400, 4],  // Switch header to image
        [8800, 5],  // Footer fills
        [10200, 6], // Move to Review (variables fill)
        [13800, 7], // Compliance running
        [17200, 8], // Likely Approved
        [20500, 9], // Submitting to Meta (WABA submission overlay)
        [24500, 10],// Approved success
        [29500, 0], // loop
      ];
      const ts = t.map(([d, p]) => setTimeout(() => setPhase(p), d));
      ts.push(setTimeout(() => setLoopKey(k => k + 1), t[t.length - 1][0] + 100));
      return () => ts.forEach(clearTimeout);
    }, [seen, loopKey]);

    // Reset on loop
    eUseEffect(() => {
      if (phase === 0) {
        setBody(""); setFooterText(""); setHeaderText(""); setAuditStep(0); setFilledVars(0);
      }
    }, [phase]);

    // Header text typing
    eUseEffect(() => {
      if (phase < 2) return;
      const target = "Reservation Confirmed";
      let i = 0;
      const id = setInterval(() => {
        i++;
        setHeaderText(target.slice(0, i));
        if (i >= target.length) clearInterval(id);
      }, 60);
      return () => clearInterval(id);
    }, [phase >= 2]);

    // Body typing
    eUseEffect(() => {
      if (phase < 2) return;
      let i = 0;
      const id = setInterval(() => {
        i += 8;
        setBody(WA_BODY_TEXT.slice(0, i));
        if (i >= WA_BODY_TEXT.length) clearInterval(id);
      }, 25);
      return () => clearInterval(id);
    }, [phase >= 2]);

    // Footer text typing
    eUseEffect(() => {
      if (phase < 5) return;
      const target = "We look forward to welcoming you";
      let i = 0;
      const id = setInterval(() => {
        i++;
        setFooterText(target.slice(0, i));
        if (i >= target.length) clearInterval(id);
      }, 50);
      return () => clearInterval(id);
    }, [phase >= 5]);

    // Variables fill in Review
    eUseEffect(() => {
      if (phase < 6) return;
      const ids = WA_SAMPLE_VALUES.map((_, i) => setTimeout(() => setFilledVars(i + 1), i * 280));
      return () => ids.forEach(clearTimeout);
    }, [phase >= 6]);

    // Audit checks
    eUseEffect(() => {
      if (phase < 7) return;
      const ids = WA_COMPLIANCE_CHECKS.map((_, i) => setTimeout(() => setAuditStep(i + 1), i * 320));
      return () => ids.forEach(clearTimeout);
    }, [phase >= 7]);

    const stepNum = phase >= 6 ? 3 : phase >= 2 ? 2 : 1;
    const stepLabels = ["Setup", "Design", "Review"];

    // Header type, text until phase 4, image from phase 4 onwards
    const headerIsImage = phase >= 4;

    return (
      <section ref={ref} style={{ background: "#fef9f4", padding: "60px 24px 80px" }}>
        <div style={{ maxWidth: 1340, margin: "0 auto" }}>
          {/* Section header */}
          <div style={{ textAlign: "center", marginBottom: 36 }}>
            <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".22em", color: E_PINK, marginBottom: 14 }}>
              TEMPLATE EDITOR &middot; COMPLIANCE AUDIT
            </div>
            <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(23px, 3.6vw, 50px)", lineHeight: 1.05, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
              See your approval odds<br/>
              <span style={{ fontStyle: "italic", color: E_PINK }}>before Meta does.</span>
            </h3>
            <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", maxWidth: 640, margin: "18px auto 0" }}>
              Every header, body, and button is scored against Meta&rsquo;s policy in real time. Fix what flags red, then auto-submit when the score hits 100.
            </p>
          </div>

          {/* Editor card */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{
            background: "#fff", borderRadius: 18,
            boxShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
            border: "1px solid rgba(15,23,42,.06)", overflow: "hidden",
            height: 880, display: "flex", flexDirection: "column",
            position: "relative",
          }}>

            {/* WABA Submission overlay */}
            {phase === 9 && (
              <div style={{
                position: "absolute", inset: 0, zIndex: 10,
                background: "rgba(254,249,244,.96)", backdropFilter: "blur(6px)",
                display: "grid", placeItems: "center", animation: "fadeIn .35s",
              }}>
                <div style={{ textAlign: "center", maxWidth: 520, padding: "0 24px" }}>
                  <div style={{ width: 96, height: 96, margin: "0 auto 22px", borderRadius: 99, background: "#fff", display: "grid", placeItems: "center", boxShadow: "0 12px 40px -10px rgba(237,77,134,.4)", position: "relative" }}>
                    <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="2"><path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0118.8-4.3M22 12.5a10 10 0 01-18.8 4.2"/></svg>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".22em", color: E_PINK, marginBottom: 10 }}>SUBMITTING TO META</div>
                  <h4 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(20px, 2.6vw, 36px)", fontWeight: 400, color: E_INK, margin: "0 0 10px", letterSpacing: "-0.01em" }}>Pushing to <span style={{ fontStyle: "italic", color: E_PINK }}>WhatsApp Business API…</span></h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 22px" }}>Forwarding the audited template to Meta for review.</p>
                  <div style={{ width: 360, height: 4, background: "#f1f5f9", borderRadius: 99, overflow: "hidden", margin: "0 auto 18px" }}>
                    <div style={{ height: "100%", width: "40%", background: "linear-gradient(90deg, transparent, " + E_PINK + ", transparent)", animation: "wabaShimmer 1.4s linear infinite" }} />
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "stretch", maxWidth: 360, margin: "0 auto", textAlign: "left" }}>
                    {[
                      { l: "Validating template structure", d: 0 },
                      { l: "Uploading to WABA endpoint", d: 900 },
                      { l: "Awaiting Meta acknowledgment", d: 1900 },
                    ].map((s, i) => (
                      <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "9px 12px", background: "#fff", border: "1px solid " + E_PINK_SOFT, borderRadius: 8, fontSize: 12, color: E_INK, animation: `fadeInUp .4s ${s.d}ms both` }}>
                        <span style={{ width: 14, height: 14, border: "2px solid " + E_PINK, borderTopColor: "transparent", borderRadius: 99, animation: "spin .8s linear infinite", display: "inline-block" }} />
                        {s.l}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {/* Approval success overlay */}
            {phase === 10 && (
              <div style={{
                position: "absolute", inset: 0, zIndex: 10,
                background: "linear-gradient(180deg, " + E_PINK_SOFT + " 0%, #fef9f4 60%)",
                display: "grid", placeItems: "center", animation: "fadeIn .35s",
                overflow: "hidden",
              }}>
                {/* Confetti dots */}
                {Array.from({ length: 24 }).map((_, i) => (
                  <span key={i} style={{
                    position: "absolute",
                    left: (i * 37 % 100) + "%",
                    top: -20,
                    width: 8, height: 8, borderRadius: 99,
                    background: i % 3 === 0 ? E_PINK : i % 3 === 1 ? E_PINK_TINT : E_INK,
                    animation: `confetti ${2.5 + (i % 5) * 0.3}s ${i * 0.08}s linear infinite`,
                    opacity: 0.85,
                  }} />
                ))}
                <div style={{ textAlign: "center", maxWidth: 560, padding: "0 24px", position: "relative", zIndex: 2 }}>
                  <div style={{ width: 110, height: 110, margin: "0 auto 24px", borderRadius: 99, background: "#fff", display: "grid", placeItems: "center", boxShadow: "0 18px 50px -12px rgba(237,77,134,.45)", position: "relative", animation: "popIn .55s cubic-bezier(.18,.89,.32,1.28)" }}>
                    <div style={{ position: "absolute", inset: -8, borderRadius: 99, border: "2px solid " + E_PINK_TINT, animation: "ringPulse 1.6s ease-out infinite" }} />
                    <div style={{ position: "absolute", inset: -16, borderRadius: 99, border: "1.5px solid " + E_PINK_TINT, animation: "ringPulse 1.6s ease-out .4s infinite", opacity: 0.6 }} />
                    <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="5 12 10 17 19 7" style={{ strokeDasharray: 30, strokeDashoffset: 30, animation: "drawCheck .6s .25s forwards" }} />
                    </svg>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".22em", color: E_PINK, marginBottom: 10 }}>APPROVED BY META</div>
                  <h4 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 46, fontWeight: 400, color: E_INK, margin: "0 0 12px", letterSpacing: "-0.01em", lineHeight: 1.05 }}>Your template is <span style={{ fontStyle: "italic", color: E_PINK }}>live on WhatsApp.</span></h4>
                  <p style={{ fontSize: 14, color: "#475569", margin: "0 0 26px", lineHeight: 1.55 }}>Meta accepted <b style={{ color: E_INK }}>booking_confirmation_v3</b> in under 24 hours. Ready to broadcast.</p>
                  <div style={{ display: "inline-flex", gap: 16, padding: "14px 24px", background: "#fff", border: "1px solid " + E_PINK_SOFT, borderRadius: 12, alignItems: "center" }}>
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>STATUS</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_PINK, display: "inline-flex", alignItems: "center", gap: 6, marginTop: 3 }}>
                        <span style={{ width: 7, height: 7, borderRadius: 99, background: E_PINK, animation: "pulse 1.4s ease-in-out infinite" }} /> APPROVED
                      </div>
                    </div>
                    <div style={{ width: 1, height: 32, background: E_PINK_SOFT }} />
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>QUALITY</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 3 }}>HIGH · 100/100</div>
                    </div>
                    <div style={{ width: 1, height: 32, background: E_PINK_SOFT }} />
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>CATEGORY</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 3 }}>UTILITY · EN</div>
                    </div>
                  </div>
                  <div style={{ marginTop: 22, display: "inline-flex", alignItems: "center", gap: 10 }}>
                    <div style={{ padding: "10px 18px", background: E_INK, color: "#fff", borderRadius: 8, fontSize: 12.5, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 6 }}>
                      Use in broadcast
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4"><polyline points="9 18 15 12 9 6"/></svg>
                    </div>
                    <div style={{ padding: "10px 16px", background: "#fff", color: E_INK, border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 12.5, fontWeight: 500 }}>View in Library</div>
                  </div>
                </div>
              </div>
            )}

            {/* Header bar with stepper */}
            <div style={{ padding: "20px 28px", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8", marginBottom: 4 }}>WHATSAPP TEMPLATE</div>
                <div style={{ fontSize: 22, fontWeight: 700, color: E_INK, fontFamily: "inherit" }}>Edit Template</div>
                <div style={{ fontSize: 12, color: "#64748b", marginTop: 3 }}>Review and submit your AI-generated template</div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 0 }}>
                {stepLabels.map((l, i) => {
                  const idx = i + 1;
                  const done = stepNum > idx;
                  const active = stepNum === idx;
                  return (
                    <React.Fragment key={i}>
                      <div style={{
                        display: "inline-flex", alignItems: "center", gap: 8,
                        padding: "9px 16px", borderRadius: 10,
                        background: done ? "#f1f5f9" : active ? E_INK : "transparent",
                        color: done ? E_INK : active ? "#fff" : "#94a3b8",
                        fontSize: 13, fontWeight: 600,
                        transition: "all .3s",
                      }}>
                        <span style={{
                          width: 20, height: 20, borderRadius: 99,
                          background: done ? E_INK : active ? "rgba(255,255,255,.2)" : "transparent",
                          border: !done && !active ? "1.5px solid #cbd5e1" : "none",
                          display: "grid", placeItems: "center", color: "#fff", fontSize: 11, fontWeight: 700,
                        }}>
                          {done ? <WAStepIcon name="check" size={11} color="#fff"/> : idx}
                        </span>
                        {l}
                      </div>
                      {i < 2 && <div style={{ width: 32, height: 1, background: "#e2e8f0" }} />}
                    </React.Fragment>
                  );
                })}
                <div style={{ marginLeft: 18, fontSize: 11, color: "#64748b", display: "inline-flex", alignItems: "center", gap: 6 }}>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>
                  Draft saved {phase >= 7 ? "1m ago" : "166h ago"}
                </div>
              </div>
            </div>

            {/* Body */}
            <div style={{ flex: 1, padding: "26px 28px", display: "grid", gridTemplateColumns: "1fr 320px", gap: 28, overflow: "hidden" }}>
              {/* Left: form */}
              <div style={{ overflow: "hidden", position: "relative" }}>
                {/* === DESIGN STEP === */}
                {phase < 6 && (
                  <div style={{ animation: "fadeIn .4s" }}>
                    <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Design Your Template</h4>
                    <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 18px" }}>Build your message with the visual editor. The phone preview updates in real-time.</p>

                    {/* Top meta strip */}
                    <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: "10px 14px", display: "flex", alignItems: "center", gap: 18, marginBottom: 18, fontSize: 12 }}>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"/></svg>
                        <span style={{ background: "#dbeafe", color: "#1e3a8a", padding: "2px 8px", borderRadius: 4, fontWeight: 600, fontSize: 11 }}>Utility</span>
                      </span>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "#475569" }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
                        Standard
                      </span>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, color: "#475569" }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2c2.5 2.7 4 6.4 4 10s-1.5 6.7-4 10c-2.5-3.3-4-7-4-10s1.5-7.3 4-10z"/></svg>
                        English <span style={{ color: "#94a3b8" }}>(en)</span>
                      </span>
                      <span style={{ marginLeft: "auto", fontSize: 11.5, color: WA_AI_PURPLE, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 5 }}>
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={WA_AI_PURPLE} strokeWidth="2.4"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 113 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                        Edit
                      </span>
                    </div>

                    {/* Header & Footer side-by-side */}
                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
                      {/* Header */}
                      <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 14 }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                          <span style={{ fontSize: 12.5, fontWeight: 700, color: E_INK }}>Header (Optional)</span>
                          <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".1em", color: "#475569", background: "#f1f5f9", padding: "3px 7px", borderRadius: 4 }}>OPTIONAL</span>
                        </div>
                        {/* Type dropdown */}
                        <div style={{ border: "1.5px solid " + (headerIsImage ? E_INK : WA_AI_PURPLE), borderRadius: 8, padding: "8px 10px", display: "flex", alignItems: "center", gap: 8, marginBottom: 10, fontSize: 12, fontWeight: 600 }}>
                          {headerIsImage ? (
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                          ) : (
                            <span style={{ width: 14, height: 14, fontWeight: 700, fontSize: 13, color: E_INK, fontFamily: "Georgia, serif", lineHeight: 1, marginTop: 1 }}>T</span>
                          )}
                          {headerIsImage ? "Image" : "Text"}
                          <span style={{ flex: 1, fontWeight: 400, fontSize: 11, color: "#94a3b8" }}>- {headerIsImage ? "JPG or PNG image" : "Text header (60 chars max)"}</span>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><polyline points="6 9 12 15 18 9"/></svg>
                        </div>
                        {!headerIsImage ? (
                          <>
                            <div style={{ border: "1px solid #f1f5f9", borderRadius: 6, padding: "8px 10px", fontSize: 12, color: E_INK, minHeight: 22 }}>
                              {headerText}<span style={{ color: WA_AI_PURPLE, animation: "blink 1s infinite" }}>{phase < 4 && headerText.length < 22 ? "|" : ""}</span>
                            </div>
                            <div style={{ fontSize: 10, color: "#94a3b8", textAlign: "right", marginTop: 4 }}>{headerText.length}/60</div>
                          </>
                        ) : (
                          <div style={{ background: "#fffbeb", border: "1px dashed #fbbf24", borderRadius: 6, padding: "10px 12px", fontSize: 11, color: "#92400e", display: "flex", alignItems: "center", gap: 8, animation: "fadeIn .4s" }}>
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                            You'll upload the actual image file in the review step.
                          </div>
                        )}
                      </div>
                      {/* Footer */}
                      <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 14 }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                          <span style={{ fontSize: 12.5, fontWeight: 700, color: E_INK }}>Footer (Optional)</span>
                          <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".1em", color: "#475569", background: "#f1f5f9", padding: "3px 7px", borderRadius: 4 }}>60 CHARS MAX</span>
                        </div>
                        <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, color: "#64748b", marginBottom: 8 }}>
                          <span style={{ width: 12, height: 12, border: "1.5px solid #cbd5e1", borderRadius: 3, display: "inline-block" }} />
                          Add unsubscribe text
                        </div>
                        <div style={{ border: "1px solid #f1f5f9", borderRadius: 6, padding: "8px 10px", fontSize: 12, color: E_INK, minHeight: 22 }}>
                          {footerText}<span style={{ color: WA_AI_PURPLE, animation: "blink 1s infinite" }}>{phase === 5 && footerText.length < 32 ? "|" : ""}</span>
                        </div>
                        <div style={{ fontSize: 10, color: "#94a3b8", textAlign: "right", marginTop: 4 }}>{footerText.length}/60</div>
                      </div>
                    </div>

                    {/* Message Body */}
                    <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 14, marginBottom: 14 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                        <span style={{ fontSize: 12.5, fontWeight: 700, color: E_INK }}>Message Body</span>
                        <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: WA_AI_PURPLE, fontWeight: 600, padding: "5px 10px", border: "1px solid " + WA_AI_PURPLE_SOFT, borderRadius: 6 }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill={WA_AI_PURPLE}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>
                          Insert Variable
                        </div>
                      </div>
                      {/* Toolbar */}
                      <div style={{ display: "flex", gap: 4, padding: "5px 6px", background: "#f8fafc", borderRadius: 6, marginBottom: 8, fontSize: 11, color: "#64748b" }}>
                        {["B", "I", "S", "</>", "≡", "1.", "“"].map((t, i) => (
                          <span key={i} style={{ padding: "4px 8px", fontWeight: i < 3 ? 700 : 400, fontStyle: i === 1 ? "italic" : "normal", textDecoration: i === 2 ? "line-through" : "none" }}>{t}</span>
                        ))}
                        <span style={{ padding: "4px 8px", display: "inline-flex", alignItems: "center", gap: 3 }}>😀<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><polyline points="6 9 12 15 18 9"/></svg></span>
                      </div>
                      <div style={{ border: "1px solid #f1f5f9", borderRadius: 6, padding: "10px 12px", fontSize: 12, color: E_INK, lineHeight: 1.5, minHeight: 160, maxHeight: 160, overflow: "hidden", whiteSpace: "pre-wrap", fontFamily: "inherit" }}>
                        {body}<span style={{ color: WA_AI_PURPLE, animation: "blink 1s infinite" }}>{phase >= 2 && body.length < WA_BODY_TEXT.length ? "|" : ""}</span>
                      </div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 8, fontSize: 11, color: "#64748b" }}>
                        <div>
                          <span style={{ color: "#94a3b8" }}>Variables: </span>
                          {[1, 2, 3, 4, 5, 6, 7].map((n) => (
                            <span key={n} style={{ display: "inline-block", padding: "2px 7px", marginRight: 4, background: WA_AI_PURPLE_SOFT, color: WA_AI_PURPLE, borderRadius: 4, fontSize: 10, fontWeight: 600, fontFamily: "monospace" }}>{`{{${n}}}`}</span>
                          ))}
                        </div>
                        <div style={{ color: "#94a3b8" }}>{body.length}/1024</div>
                      </div>
                    </div>

                    {/* Buttons */}
                    <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 14 }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                        <span style={{ fontSize: 12.5, fontWeight: 700, color: E_INK }}>Buttons (Optional)</span>
                        <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".1em", color: "#475569", background: "#f1f5f9", padding: "3px 7px", borderRadius: 4 }}>UP TO 3 BUTTONS</span>
                      </div>
                      {phase >= 3 && [
                        { icon: "msg", label: "View Full Details", color: WA_AI_PURPLE, soft: WA_AI_PURPLE_SOFT, n: 17 },
                        { icon: "phone", label: "Call Reception", color: E_PINK, soft: E_PINK_SOFT, n: 14 },
                        { icon: "link", label: "Manage Booking", color: "#2563eb", soft: "#dbeafe", n: 14 },
                      ].map((b, i) => (
                        <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 0", borderBottom: i < 2 ? "1px solid #f1f5f9" : "none", animation: "fadeInUp .4s " + (i * 0.1) + "s both" }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="#cbd5e1"><circle cx="6" cy="6" r="2"/><circle cx="6" cy="12" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="12" cy="6" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="18" r="2"/></svg>
                          <div style={{ width: 26, height: 26, background: b.soft, borderRadius: 6, display: "grid", placeItems: "center" }}>
                            {b.icon === "msg" && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={b.color} strokeWidth="2"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/></svg>}
                            {b.icon === "phone" && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={b.color} strokeWidth="2"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0122 16.92z"/></svg>}
                            {b.icon === "link" && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={b.color} strokeWidth="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6M15 3h6v6M10 14L21 3"/></svg>}
                          </div>
                          <div style={{ flex: 1, padding: "6px 10px", border: "1px solid #f1f5f9", borderRadius: 6, fontSize: 12, color: E_INK, fontWeight: 500 }}>{b.label}</div>
                          <div style={{ fontSize: 11, color: "#94a3b8" }}>{b.n}/25</div>
                          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#cbd5e1" strokeWidth="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
                        </div>
                      ))}
                      {phase >= 3 && (
                        <div style={{ marginTop: 8, padding: "9px 12px", background: "#fffbeb", border: "1px solid #fbbf24", borderRadius: 6, fontSize: 11, color: "#92400e", display: "flex", alignItems: "center", gap: 8 }}>
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                          You'll add the URLs and phone numbers in the review step.
                        </div>
                      )}
                    </div>
                  </div>
                )}

                {/* === REVIEW STEP === */}
                {phase >= 6 && (
                  <div style={{ animation: "fadeIn .4s" }}>
                    <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Preview &amp; Review</h4>
                    <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 18px" }}>Provide sample values for your variables and review the compliance checklist before submitting.</p>

                    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 14 }}>
                      {/* Sample Values */}
                      <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 14 }}>
                        <div style={{ fontSize: 12.5, fontWeight: 700, color: E_INK, marginBottom: 10, display: "inline-flex", alignItems: "center", gap: 6 }}>
                          <svg width="13" height="13" viewBox="0 0 24 24" fill={WA_AI_PURPLE}><path d="M12 2l1.5 5L18 8l-4 3 1.5 5-3.5-3-3.5 3 1.5-5-4-3 4.5-1z"/></svg>
                          Sample Values
                        </div>
                        {WA_SAMPLE_VALUES.map((s, i) => {
                          const filled = filledVars > i;
                          return (
                            <div key={i} style={{ marginBottom: 8 }}>
                              <div style={{ fontSize: 10, color: "#94a3b8", marginBottom: 3, fontFamily: "monospace" }}>{s.var}</div>
                              <div style={{
                                border: "1px solid " + (filled ? E_PINK_SOFT : "#f1f5f9"),
                                background: filled ? E_PINK_SOFT : "#fff",
                                borderRadius: 6, padding: "6px 10px", fontSize: 12, color: E_INK,
                                minHeight: 22, transition: "all .25s",
                              }}>{filled ? s.val : ""}</div>
                            </div>
                          );
                        })}
                      </div>

                      {/* Right column: Button details + Compliance + Approval */}
                      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                        {/* Button details */}
                        <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 14 }}>
                          <div style={{ fontSize: 12.5, fontWeight: 700, color: E_INK, marginBottom: 10, display: "inline-flex", alignItems: "center", gap: 6 }}>
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#2563eb" strokeWidth="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6M15 3h6v6M10 14L21 3"/></svg>
                            Button Details
                          </div>
                          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                            <div>
                              <div style={{ fontSize: 10.5, color: "#64748b", marginBottom: 3, display: "inline-flex", alignItems: "center", gap: 4 }}>
                                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2"><path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.37 1.9.72 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.35 1.85.59 2.81.72A2 2 0 0122 16.92z"/></svg>
                                Call Reception &middot; Phone
                              </div>
                              <div style={{ border: "1px solid #f1f5f9", borderRadius: 6, padding: "6px 10px", fontSize: 12, color: E_INK }}>+1234567890</div>
                            </div>
                            <div>
                              <div style={{ fontSize: 10.5, color: "#64748b", marginBottom: 3, display: "inline-flex", alignItems: "center", gap: 4 }}>
                                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6M15 3h6v6M10 14L21 3"/></svg>
                                Manage Booking &middot; URL
                              </div>
                              <div style={{ border: "1px solid #f1f5f9", borderRadius: 6, padding: "6px 10px", fontSize: 11, color: E_INK, fontFamily: "monospace" }}>https://yourhotel.com/manage/{`{{1}}`}</div>
                            </div>
                          </div>
                          <div style={{ fontSize: 10.5, color: "#94a3b8", marginTop: 6 }}>You can use {`{{1}}`} for dynamic URL parameters</div>
                        </div>

                        {/* Compliance checklist + Approval status */}
                        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                          {/* Compliance */}
                          <div style={{ background: "#fff", border: "1px solid #f1f5f9", borderRadius: 10, padding: 12 }}>
                            <div style={{ fontSize: 11.5, fontWeight: 700, color: E_INK, marginBottom: 8, display: "inline-flex", alignItems: "center", gap: 6 }}>
                              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#2563eb" strokeWidth="2"><path d="M12 2L4 6v6c0 5.5 3.8 10.7 8 12 4.2-1.3 8-6.5 8-12V6z"/></svg>
                              Compliance Checklist
                            </div>
                            {WA_COMPLIANCE_CHECKS.map((c, i) => {
                              const done = auditStep > i;
                              return (
                                <div key={i} style={{ display: "flex", alignItems: "center", gap: 6, padding: "3px 0", fontSize: 10.5, color: done ? E_INK : "#94a3b8", transition: "color .3s" }}>
                                  <div style={{ width: 14, height: 14, borderRadius: 99, background: done ? E_PINK_SOFT : "#f1f5f9", display: "grid", placeItems: "center", flexShrink: 0, transition: "background .3s" }}>
                                    {done ? <WAStepIcon name="check" size={9} color={E_PINK}/> : <span style={{ width: 5, height: 5, borderRadius: 99, background: "#cbd5e1" }}/>}
                                  </div>
                                  {c}
                                </div>
                              );
                            })}
                          </div>
                          {/* Approval Status */}
                          <div style={{
                            background: phase >= 8 ? E_PINK_SOFT : "#fff",
                            border: "1px solid " + (phase >= 8 ? E_PINK : "#f1f5f9"),
                            borderRadius: 10, padding: 12,
                            display: "flex", flexDirection: "column", justifyContent: "center",
                            transition: "all .4s",
                          }}>
                            <div style={{ fontSize: 11.5, fontWeight: 700, color: E_INK, marginBottom: 12, display: "inline-flex", alignItems: "center", gap: 6 }}>
                              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                              Approval Status
                            </div>
                            {phase >= 8 ? (
                              <div style={{ display: "flex", alignItems: "center", gap: 12, animation: "fadeIn .5s" }}>
                                <div style={{
                                  width: 56, height: 56, borderRadius: 99,
                                  border: "3px solid " + E_PINK, display: "grid", placeItems: "center",
                                  fontSize: 18, fontWeight: 700, color: E_PINK, flexShrink: 0,
                                }}>100</div>
                                <div>
                                  <div style={{ fontSize: 12, fontWeight: 700, color: E_PINK, display: "inline-flex", alignItems: "center", gap: 5, marginBottom: 4 }}>
                                    <WAStepIcon name="check" size={11} color={E_PINK}/>
                                    Likely Approved
                                  </div>
                                  <div style={{ fontSize: 10.5, color: "#475569", lineHeight: 1.4 }}>
                                    Your template meets all Meta guidelines and is ready for submission.
                                  </div>
                                </div>
                              </div>
                            ) : (
                              <div style={{ fontSize: 11, color: "#94a3b8", fontStyle: "italic" }}>
                                Running compliance checks&hellip;
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* Submit bar */}
                    <div style={{ marginTop: 16, padding: "12px 14px", background: phase >= 8 ? "linear-gradient(90deg, " + E_PINK_SOFT + ", #fff)" : "#f8fafc", border: "1px solid " + (phase >= 8 ? E_PINK : "#f1f5f9"), borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                      <div style={{ fontSize: 12, color: "#475569" }}>
                        {phase >= 8 ? <><b style={{ color: E_PINK }}>Ready.</b> Auto-submit to Meta with one click. Approval typically within 24h.</> : "Audit running…"}
                      </div>
                      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "9px 16px", background: phase >= 8 ? WA_GREEN : "#cbd5e1", color: "#fff", borderRadius: 8, fontSize: 12.5, fontWeight: 700 }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="#fff"><path d="M20.52 3.449C12.831-3.984.106 1.407.101 11.893c0 2.096.549 4.142 1.595 5.945L0 24l6.335-1.652a11.882 11.882 0 005.71 1.447h.006c10.493 0 16.965-12.5 11.987-19.875A12.062 12.062 0 0020.52 3.449z"/></svg>
                        Submit to Meta
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Right: Live phone preview */}
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
                <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, color: E_INK, fontWeight: 600 }}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/></svg>
                  {phase >= 6 ? "Preview with Sample Values" : "Live Preview"}
                </div>
                <WAPhone height={400} time="04:48 PM">
                  <div style={{ animation: "fadeIn .4s" }}>
                    <WATemplateBubble
                      header={!headerIsImage ? headerText : undefined}
                      hasImage={headerIsImage}
                      body={
                        phase >= 6
                          ? body.replace(/\{\{(\d+)\}\}/g, (_, n) => {
                              const idx = parseInt(n) - 1;
                              return filledVars > idx ? WA_SAMPLE_VALUES[idx].val : `{{${n}}}`;
                            })
                          : body
                      }
                      footer={footerText}
                      buttons={phase >= 3 ? [
                        { icon: "reply", label: "View Full Details" },
                        { icon: "phone", label: "Call Reception" },
                        { icon: "link", label: "Manage Booking" },
                      ] : null}
                      time="04:48 PM"
                    />
                  </div>
                </WAPhone>
                <div style={{ fontSize: 10.5, color: "#94a3b8", textAlign: "center", maxWidth: 240, lineHeight: 1.4 }}>
                  This is how your message will appear on WhatsApp. Variables will be replaced with actual values.
                </div>
              </div>
            </div>
          </div>
          </ScaleFrame>

          <div style={{ textAlign: "center", marginTop: 18, fontSize: 12, color: "#94a3b8" }}>
            AI-audited before it ever reaches Meta &middot; only high-probability templates get submitted.
          </div>
        </div>
        <style>{`
          @keyframes spin { to { transform: rotate(360deg); } }
          @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
          @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
          @keyframes fadeInUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
          @keyframes popIn { 0% { transform: scale(.7); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }
          @keyframes drawCheck { to { stroke-dashoffset: 0; } }
          @keyframes ringPulse { 0% { transform: scale(.95); opacity: .9; } 100% { transform: scale(1.4); opacity: 0; } }
          @keyframes wabaShimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(360%); } }
          @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
          @keyframes confetti { 0% { transform: translateY(-40px) rotate(0); opacity: 0; } 8% { opacity: 1; } 100% { transform: translateY(640px) rotate(540deg); opacity: 0; } }
        `}</style>
      </section>
    );
  };

  window.WAEditTemplateArtifact = WAEditTemplateArtifact;

  /* ===== whatsapp_broadcast.jsx ===== */

  // ============== WHATSAPP BROADCAST WIZARD ARTIFACT ==============
  // 5 steps: Setup → Template → Content → Audience → Schedule
  // Animated through a complete win-back broadcast.

  const WAB_TYPING_NAME = "Win back · 365 days after booking";

  const WAB_TEMPLATES = [
    { name: "returning_guest_exclusive_discount", body: "Dear {{1}}, we've missed you! As a valued returning guest, we're delighted to offer you an exclusive 25% discount on…", tags: ["MARKETING", "IMAGE", "1 btn"], cat: "marketing" },
    { name: "post_stay_thankyou_v3", body: "Hi {{1}}, thank you for staying with us at {{2}} – we hope you had a wonderful experience. Your feedback means the world…", tags: ["MARKETING", "2 vars", "2 btns"], cat: "marketing" },
    { name: "booking_confirmed_v3", body: "Hi {{1}}, your reservation at {{2}} is confirmed. Check-in: {{3}} Confirmation: {{4}} Need anything before your trip? Reply he…", tags: ["MARKETING", "4 vars", "2 btns"], cat: "marketing" },
    { name: "vip_arrival_welcome_notification", body: "Dear {{1}}, We are delighted to welcome you as our distinguished guest arriving on {{2}}. As a valued VIP, we hav…", tags: ["MARKETING", "2 btns"], cat: "marketing" },
    { name: "guest_experience_feedback_collection", body: "Hello {{1}}, Thank you for choosing to stay with us. We genuinely value your feedback and would love to hear abou…", tags: ["MARKETING", "IMAGE", "2 btns"], cat: "marketing" },
    { name: "post_check_in_ai_assistant_introduction", body: "Hello {{1}}! 🎉 Welcome to your room {{2}}. Your personal AI concierge is ready to serve you 24/7! Get instant help with:…", tags: ["MARKETING", "1 btn"], cat: "marketing" },
  ];

  const WAB_FIELDS = [
    { group: "Guest Information", n: 7, fields: [{ icon: "user", name: "First Name", eg: "John" }] },
    { group: "Reservation Details", n: 22, fields: [
      { icon: "hash", name: "Confirmation Number", eg: "CONF-12345" },
      { icon: "cal", name: "Check-in Date", eg: "March 15, 2024" },
      { icon: "cal", name: "Check-out Date", eg: "March 18, 2024" },
    ]},
  ];

  const WAB_VAR_MAPPINGS = [
    { var: "{{1}}", icon: "user", field: "First Name", preview: "John" },
    { var: "{{2}}", icon: "hash", field: "Confirmation Number", preview: "CONF-12345" },
    { var: "{{3}}", icon: "cal", field: "Check-in Date", preview: "March 15, 2024" },
    { var: "{{4}}", icon: "cal", field: "Check-out Date", preview: "March 18, 2024" },
  ];

  const WABroadcastArtifact = () => {
    const [ref, seen] = useInView(0.15);
    // Phases:
    // 0 idle, 1 Setup typing, 2 Template list, 3 Template selected,
    // 4 Content (var mapping animating), 5 Audience (counter ticking),
    // 6 Schedule (click Schedule + checklist green), 7 settle, loop
    const [phase, setPhase] = eUseState(0);
    const [loopKey, setLoopKey] = eUseState(0);
    const [name, setName] = eUseState("");
    const [varStep, setVarStep] = eUseState(0);
    const [audCount, setAudCount] = eUseState(0);
    const [checkStep, setCheckStep] = eUseState(0);
    const [pickerOpen, setPickerOpen] = eUseState(false);
    const [sendProg, setSendProg] = eUseState(0);
    const [sendCount, setSendCount] = eUseState(0);

    eUseEffect(() => {
      if (!seen) return;
      const t = [
        [400, 1],   // Setup typing
        [3500, 2],  // Template list visible
        [5400, 3],  // Template selected
        [6800, 4],  // Content / var mapping
        [13800, 5], // Audience
        [17500, 6], // Schedule
        [22500, 7], // Sending overlay
        [27500, 8], // Success
        [33000, 0], // loop
      ];
      const ts = t.map(([d, p]) => setTimeout(() => setPhase(p), d));
      ts.push(setTimeout(() => setLoopKey(k => k + 1), t[t.length - 1][0] + 100));
      return () => ts.forEach(clearTimeout);
    }, [seen, loopKey]);

    // Reset on loop
    eUseEffect(() => {
      if (phase === 0) {
        setName(""); setVarStep(0); setAudCount(0); setCheckStep(0); setPickerOpen(false); setSendProg(0); setSendCount(0);
      }
    }, [phase]);

    // Type name
    eUseEffect(() => {
      if (phase < 1) return;
      let i = 0;
      const id = setInterval(() => {
        i++;
        setName(WAB_TYPING_NAME.slice(0, i));
        if (i >= WAB_TYPING_NAME.length) clearInterval(id);
      }, 55);
      return () => clearInterval(id);
    }, [phase >= 1]);

    // Variable mapping (4 vars filling in sequence with picker briefly open on var 2)
    eUseEffect(() => {
      if (phase !== 4) return;
      const ids = [];
      // var 1 (auto first name) immediate
      ids.push(setTimeout(() => setVarStep(1), 400));
      // open picker for var 2
      ids.push(setTimeout(() => setPickerOpen(true), 1400));
      // map var 2
      ids.push(setTimeout(() => { setPickerOpen(false); setVarStep(2); }, 3000));
      // var 3
      ids.push(setTimeout(() => setVarStep(3), 4000));
      // var 4
      ids.push(setTimeout(() => setVarStep(4), 5000));
      return () => ids.forEach(clearTimeout);
    }, [phase]);

    // Audience counter tick
    eUseEffect(() => {
      if (phase < 5) return;
      const target = 28263;
      let cur = 0;
      const id = setInterval(() => {
        cur += Math.ceil(target / 40);
        if (cur >= target) { cur = target; clearInterval(id); }
        setAudCount(cur);
      }, 40);
      return () => clearInterval(id);
    }, [phase >= 5]);

    // Checklist for Schedule step
    eUseEffect(() => {
      if (phase < 6) return;
      const ids = Array.from({ length: 5 }, (_, i) => setTimeout(() => setCheckStep(i + 1), i * 320));
      return () => ids.forEach(clearTimeout);
    }, [phase >= 6]);

    // Sending overlay progress + counter
    eUseEffect(() => {
      if (phase !== 7) return;
      const target = 28263;
      const startedAt = Date.now();
      const dur = 4200;
      const id = setInterval(() => {
        const t = Math.min(1, (Date.now() - startedAt) / dur);
        setSendProg(Math.round(t * 100));
        setSendCount(Math.round(t * target));
        if (t >= 1) clearInterval(id);
      }, 60);
      return () => clearInterval(id);
    }, [phase]);

    // Step number based on phase
    const step = phase >= 6 ? 5 : phase >= 5 ? 4 : phase >= 4 ? 3 : phase >= 2 ? 2 : 1;
    const stepNames = ["Setup", "Template", "Content", "Audience", "Schedule"];
    const stepIcons = [
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2c2.5 2.7 4 6.4 4 10s-1.5 6.7-4 10c-2.5-3.3-4-7-4-10s1.5-7.3 4-10z"/></svg>,
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>,
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 20h9M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>,
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>,
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
    ];

    return (
      <section ref={ref} style={{ background: E_CREAM, padding: "60px 24px 100px" }}>
        <div style={{ maxWidth: 1340, margin: "0 auto" }}>
          {/* Section header */}
          <div style={{ textAlign: "center", marginBottom: 36 }}>
            <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: ".22em", color: E_PINK, marginBottom: 14 }}>
              BROADCAST WIZARD
            </div>
            <h3 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(23px, 3.6vw, 50px)", lineHeight: 1.05, fontWeight: 400, color: E_INK, margin: 0, letterSpacing: "-0.01em" }}>
              From idea to inbox in five steps.<br/>
              <span style={{ fontStyle: "italic", color: E_PINK }}>Without waking a single guest.</span>
            </h3>
            <p style={{ fontSize: 16, lineHeight: 1.55, color: "#475569", maxWidth: 660, margin: "18px auto 0" }}>
              Pick a template, map the variables, target the segment. We&rsquo;ll throttle to Meta&rsquo;s rate limits, defer per-guest DND windows, and tag every send with UTM, before you hit confirm.
            </p>
          </div>

          {/* Wizard frame */}
          <ScaleFrame nativeWidth={1100}>
          <div style={{
            background: "#fff", borderRadius: 18,
            boxShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
            border: "1px solid rgba(15,23,42,.06)", overflow: "hidden",
            height: 880, display: "flex", flexDirection: "column",
            position: "relative",
          }}>

            {/* Sending overlay */}
            {phase === 7 && (
              <div style={{
                position: "absolute", inset: 0, zIndex: 10,
                background: "rgba(254,249,244,.96)", backdropFilter: "blur(6px)",
                display: "grid", placeItems: "center", animation: "fadeIn .35s",
              }}>
                <div style={{ textAlign: "center", maxWidth: 540, padding: "0 24px" }}>
                  <div style={{ width: 96, height: 96, margin: "0 auto 22px", borderRadius: 99, background: "#fff", display: "grid", placeItems: "center", boxShadow: "0 12px 40px -10px rgba(237,77,134,.4)", position: "relative" }}>
                    <svg width="42" height="42" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="2" style={{ animation: "sendNudge 1.4s ease-in-out infinite" }}><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".22em", color: E_PINK, marginBottom: 10 }}>SENDING BROADCAST</div>
                  <h4 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(20px, 2.6vw, 36px)", fontWeight: 400, color: E_INK, margin: "0 0 10px", letterSpacing: "-0.01em" }}>Queueing your <span style={{ fontStyle: "italic", color: E_PINK }}>28,263 messages…</span></h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 22px" }}>Throttling to WhatsApp’s rate limits, respecting per-guest DND.</p>
                  <div style={{ width: 420, maxWidth: "100%", margin: "0 auto" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 8 }}>
                      <span>{sendCount.toLocaleString()} of 28,263 queued</span>
                      <span>{sendProg}%</span>
                    </div>
                    <div style={{ width: "100%", height: 6, background: "#f1f5f9", borderRadius: 99, overflow: "hidden", marginBottom: 18 }}>
                      <div style={{ height: "100%", width: sendProg + "%", background: "linear-gradient(90deg, " + E_PINK_TINT + ", " + E_PINK + ")", transition: "width .15s linear" }} />
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, fontSize: 11, color: "#64748b" }}>
                      <div style={{ background: "#fff", border: "1px solid " + E_PINK_SOFT, borderRadius: 8, padding: "8px 10px" }}>
                        <div style={{ fontSize: 10, color: "#94a3b8" }}>RATE</div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 2 }}>250 msg/s</div>
                      </div>
                      <div style={{ background: "#fff", border: "1px solid " + E_PINK_SOFT, borderRadius: 8, padding: "8px 10px" }}>
                        <div style={{ fontSize: 10, color: "#94a3b8" }}>DND HELD</div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 2 }}>1,142</div>
                      </div>
                      <div style={{ background: "#fff", border: "1px solid " + E_PINK_SOFT, borderRadius: 8, padding: "8px 10px" }}>
                        <div style={{ fontSize: 10, color: "#94a3b8" }}>FAILED</div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 2 }}>0</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Success overlay */}
            {phase === 8 && (
              <div style={{
                position: "absolute", inset: 0, zIndex: 10,
                background: "linear-gradient(180deg, " + E_PINK_SOFT + " 0%, #fef9f4 60%)",
                display: "grid", placeItems: "center", animation: "fadeIn .35s",
                overflow: "hidden",
              }}>
                {Array.from({ length: 26 }).map((_, i) => (
                  <span key={i} style={{
                    position: "absolute",
                    left: ((i * 41) % 100) + "%",
                    top: -20,
                    width: 8, height: 8, borderRadius: 99,
                    background: i % 3 === 0 ? E_PINK : i % 3 === 1 ? E_PINK_TINT : E_INK,
                    animation: `confetti ${2.6 + (i % 5) * 0.3}s ${i * 0.07}s linear infinite`,
                    opacity: 0.85,
                  }} />
                ))}
                <div style={{ textAlign: "center", maxWidth: 580, padding: "0 24px", position: "relative", zIndex: 2 }}>
                  <div style={{ width: 110, height: 110, margin: "0 auto 24px", borderRadius: 99, background: "#fff", display: "grid", placeItems: "center", boxShadow: "0 18px 50px -12px rgba(237,77,134,.45)", position: "relative", animation: "popIn .55s cubic-bezier(.18,.89,.32,1.28)" }}>
                    <div style={{ position: "absolute", inset: -8, borderRadius: 99, border: "2px solid " + E_PINK_TINT, animation: "ringPulse 1.6s ease-out infinite" }} />
                    <div style={{ position: "absolute", inset: -16, borderRadius: 99, border: "1.5px solid " + E_PINK_TINT, animation: "ringPulse 1.6s ease-out .4s infinite", opacity: 0.6 }} />
                    <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                      <polyline points="5 12 10 17 19 7" style={{ strokeDasharray: 30, strokeDashoffset: 30, animation: "drawCheck .6s .25s forwards" }} />
                    </svg>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".22em", color: E_PINK, marginBottom: 10 }}>BROADCAST DELIVERED</div>
                  <h4 style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 46, fontWeight: 400, color: E_INK, margin: "0 0 12px", letterSpacing: "-0.01em", lineHeight: 1.05 }}>28,263 guests, <span style={{ fontStyle: "italic", color: E_PINK }}>one warm hello.</span></h4>
                  <p style={{ fontSize: 14, color: "#475569", margin: "0 0 26px", lineHeight: 1.55 }}>Win-back queued and sending now, 1,142 deferred until DND windows lift.</p>
                  <div style={{ display: "inline-flex", gap: 16, padding: "14px 24px", background: "#fff", border: "1px solid " + E_PINK_SOFT, borderRadius: 12, alignItems: "center" }}>
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>SENT</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_PINK, marginTop: 3 }}>27,121</div>
                    </div>
                    <div style={{ width: 1, height: 32, background: E_PINK_SOFT }} />
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>DEFERRED (DND)</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 3 }}>1,142</div>
                    </div>
                    <div style={{ width: 1, height: 32, background: E_PINK_SOFT }} />
                    <div style={{ textAlign: "left" }}>
                      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>FAILED</div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginTop: 3 }}>0</div>
                    </div>
                  </div>
                  <div style={{ marginTop: 22, display: "inline-flex", alignItems: "center", gap: 10 }}>
                    <div style={{ padding: "10px 18px", background: E_INK, color: "#fff", borderRadius: 8, fontSize: 12.5, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 6 }}>
                      View live report
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4"><polyline points="9 18 15 12 9 6"/></svg>
                    </div>
                    <div style={{ padding: "10px 16px", background: "#fff", color: E_INK, border: "1px solid #e2e8f0", borderRadius: 8, fontSize: 12.5, fontWeight: 500 }}>Schedule another</div>
                  </div>
                </div>
              </div>
            )}
            {/* Top: breadcrumb + title */}
            <div style={{ padding: "20px 28px 14px", borderBottom: "1px solid #f1f5f9" }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: ".14em", color: "#94a3b8" }}>
                MESSAGING <span style={{ margin: "0 6px", color: "#cbd5e1" }}>›</span>
                BROADCASTS <span style={{ margin: "0 6px", color: "#cbd5e1" }}>›</span>
                <span style={{ color: E_PINK }}>NEW</span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2.4"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg>
                <div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: E_INK }}>Create Broadcast</div>
                  <div style={{ fontSize: 12, color: "#64748b" }}>Send a message to multiple contacts at once</div>
                </div>
              </div>
            </div>

            {/* Stepper */}
            <div style={{ padding: "20px 28px", borderBottom: "1px solid #f1f5f9", display: "flex", alignItems: "center", gap: 0 }}>
              {stepNames.map((n, i) => {
                const idx = i + 1;
                const done = step > idx;
                const active = step === idx;
                return (
                  <React.Fragment key={i}>
                    <div style={{
                      flex: i === stepNames.length - 1 ? 0 : 1,
                      display: "flex", alignItems: "center", gap: 8,
                    }}>
                      <div style={{
                        display: "inline-flex", alignItems: "center", gap: 8,
                        padding: "9px 16px", borderRadius: 10,
                        background: done ? E_PINK_SOFT : active ? E_INK : "transparent",
                        color: done ? E_PINK : active ? "#fff" : "#94a3b8",
                        fontSize: 13, fontWeight: 600, transition: "all .3s",
                        whiteSpace: "nowrap",
                      }}>
                        <span style={{ display: "inline-flex", color: "currentColor" }}>{done ? <WAStepIcon name="check" size={13} color={E_PINK}/> : stepIcons[i]}</span>
                        {n}
                      </div>
                      {i < stepNames.length - 1 && <div style={{ flex: 1, height: 2, background: done ? E_PINK : "#e2e8f0", transition: "background .3s" }} />}
                    </div>
                  </React.Fragment>
                );
              })}
            </div>

            {/* === STEP CONTENT === */}
            <div style={{ flex: 1, padding: "28px 32px", overflow: "hidden", position: "relative" }}>
              {/* Step 1: Setup */}
              {phase === 1 && (
                <div style={{ animation: "fadeIn .4s", maxWidth: 720, margin: "0 auto" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Setup Your Broadcast</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 22px" }}>Give your broadcast a name and select the language for your message.</p>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 6 }}>Broadcast Name *</div>
                    <div style={{ border: "2px solid " + WA_AI_PURPLE, borderRadius: 8, padding: "10px 12px", fontSize: 13, color: E_INK, minHeight: 22 }}>
                      {name}<span style={{ color: WA_AI_PURPLE, animation: "blink 1s infinite" }}>{name.length < WAB_TYPING_NAME.length ? "|" : ""}</span>
                    </div>
                  </div>
                  <div style={{ marginBottom: 16 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 6 }}>Description (optional)</div>
                    <div style={{ border: "1px solid #f1f5f9", borderRadius: 8, padding: "10px 12px", fontSize: 12.5, color: "#94a3b8", minHeight: 60, fontStyle: "italic" }}>Brief description of this broadcast…</div>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 16 }}>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 6 }}>Language *</div>
                      <div style={{ border: "1px solid #f1f5f9", borderRadius: 8, padding: "10px 12px", fontSize: 13, color: E_INK, fontWeight: 500, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        English
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><polyline points="6 9 12 15 18 9"/></svg>
                      </div>
                      <div style={{ fontSize: 11, color: "#94a3b8", marginTop: 5 }}>Only templates matching this language will be available.</div>
                    </div>
                    <div>
                      <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 6 }}>Hotel (optional)</div>
                      <div style={{ border: "1px solid #f1f5f9", borderRadius: 8, padding: "10px 12px", fontSize: 13, color: E_INK, fontWeight: 500, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        All hotels
                        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><polyline points="6 9 12 15 18 9"/></svg>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Step 2: Template */}
              {(phase === 2 || phase === 3) && (
                <div style={{ animation: "fadeIn .4s" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Select Template</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 16px" }}>Choose an approved template for your broadcast.</p>
                  <div style={{ background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 8, padding: "10px 14px", display: "flex", alignItems: "center", gap: 8, marginBottom: 14 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                    <span style={{ fontSize: 12.5, color: "#94a3b8" }}>Search templates by name or content...</span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14, fontSize: 12 }}>
                    <span style={{ color: "#64748b" }}>21 templates</span>
                    <span style={{ color: "#94a3b8" }}>Page 1 of 2</span>
                  </div>
                  <div style={{ background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 8, padding: 12, marginBottom: 14, fontSize: 11.5, color: "#475569", lineHeight: 1.5 }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontWeight: 600 }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                      About Template Categories
                    </span>
                    <div><b>Marketing templates</b> are designed for promotional messages and are recommended for broadcasts. <b>Utility templates</b> are for transactional messages and may have lower engagement rates for bulk sends.</div>
                  </div>

                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 10, display: "inline-flex", alignItems: "center", gap: 8 }}>
                    Marketing Templates
                    <span style={{ fontSize: 9.5, fontWeight: 700, letterSpacing: ".1em", color: E_PINK, background: E_PINK_SOFT, padding: "3px 7px", borderRadius: 4 }}>RECOMMENDED</span>
                    <span style={{ fontSize: 11, fontWeight: 600, color: "#64748b", background: "#f1f5f9", padding: "2px 8px", borderRadius: 99 }}>11</span>
                  </div>

                  <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 10, maxHeight: 380, overflow: "hidden" }}>
                    {WAB_TEMPLATES.map((t, i) => {
                      const isSelected = phase === 3 && t.name === "booking_confirmed_v3";
                      return (
                        <div key={i} style={{
                          border: "1.5px solid " + (isSelected ? E_INK : "#f1f5f9"),
                          background: isSelected ? "#f8fafc" : "#fff",
                          boxShadow: isSelected ? "0 0 0 3px rgba(15,23,42,.06)" : "none",
                          borderRadius: 10, padding: 12, transition: "all .3s",
                        }}>
                          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
                            {t.tags.includes("IMAGE") && (
                              <div style={{ width: 22, height: 22, background: "#dbeafe", borderRadius: 5, display: "grid", placeItems: "center" }}>
                                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#2563eb" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                              </div>
                            )}
                            <div style={{ fontSize: 12.5, fontWeight: 700, color: E_INK, fontFamily: "monospace" }}>{t.name}</div>
                          </div>
                          <div style={{ fontSize: 11, color: "#64748b", lineHeight: 1.4, height: 30, overflow: "hidden" }}>{t.body}</div>
                          <div style={{ display: "flex", gap: 5, marginTop: 8 }}>
                            {t.tags.map((tag, j) => {
                              const isCat = tag === "MARKETING";
                              return (
                                <span key={j} style={{
                                  fontSize: 9, fontWeight: 700, letterSpacing: ".06em",
                                  color: isCat ? E_PINK : "#475569",
                                  background: isCat ? E_PINK_SOFT : "#f1f5f9",
                                  padding: "3px 7px", borderRadius: 4,
                                }}>{tag}</span>
                              );
                            })}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              )}

              {/* Step 3: Content / variable mapping */}
              {phase === 4 && (
                <div style={{ animation: "fadeIn .4s" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Customize Content</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 22px" }}>Map variables to contact data and configure media for your broadcast.</p>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 28 }}>
                    <div>
                      <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 6 }}>Variable Mapping</div>
                      <div style={{ fontSize: 11.5, color: "#64748b", marginBottom: 16 }}>Map each variable to a contact field for personalization</div>
                      {WAB_VAR_MAPPINGS.map((m, i) => {
                        const filled = varStep > i;
                        const showPickerHere = pickerOpen && i === 1;
                        return (
                          <div key={i} style={{ marginBottom: 14, position: "relative" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                              <span style={{ fontSize: 12, color: "#475569", fontFamily: "monospace", width: 38, fontWeight: 600 }}>{m.var}</span>
                              <span style={{ color: "#fb923c", fontSize: 14 }}>○</span>
                              <div style={{
                                flex: 1, border: "1px solid " + (showPickerHere ? E_PINK : "#f1f5f9"),
                                background: filled ? E_PINK_SOFT : "#fff",
                                borderRadius: 8, padding: "8px 12px", display: "flex", alignItems: "center", gap: 8,
                                fontSize: 12.5, transition: "all .25s",
                              }}>
                                {filled ? (
                                  <>
                                    {m.icon === "user" && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>}
                                    {m.icon === "hash" && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></svg>}
                                    {m.icon === "cal" && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/></svg>}
                                    <span style={{ color: E_INK, fontWeight: 500 }}>{m.field}</span>
                                  </>
                                ) : (
                                  <span style={{ color: "#94a3b8" }}>Select field…</span>
                                )}
                                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4" style={{ marginLeft: "auto" }}><polyline points="6 9 12 15 18 9"/></svg>
                              </div>
                            </div>
                            {filled && <div style={{ fontSize: 11, color: "#64748b", marginLeft: 60, marginTop: 4 }}><span style={{ color: "#94a3b8" }}>Preview:</span> {m.preview}</div>}

                            {/* Picker dropdown */}
                            {showPickerHere && (
                              <div style={{
                                position: "absolute", left: 60, right: 0, top: 42, zIndex: 20,
                                background: "#fff", border: "1px solid #e2e8f0", borderRadius: 10,
                                boxShadow: "0 18px 40px -10px rgba(15,23,42,.25)",
                                animation: "fadeInUp .25s",
                              }}>
                                <div style={{ padding: 8, borderBottom: "1px solid #f1f5f9" }}>
                                  <div style={{ background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 8, padding: "6px 10px", display: "flex", alignItems: "center", gap: 8 }}>
                                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                                    <span style={{ fontSize: 11.5, color: "#94a3b8" }}>Search fields...</span>
                                  </div>
                                </div>
                                {WAB_FIELDS.map((g, gi) => (
                                  <div key={gi}>
                                    <div style={{ padding: "8px 12px", display: "flex", alignItems: "center", gap: 8, fontSize: 11.5, color: "#475569", borderBottom: "1px solid #f1f5f9", background: "#f8fafc" }}>
                                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                                      <b>{g.group}</b>
                                      <span style={{ marginLeft: "auto", fontSize: 10, color: "#94a3b8" }}>{g.n} fields</span>
                                    </div>
                                    {g.fields.map((f, fi) => {
                                      const isHot = f.name === "Confirmation Number";
                                      return (
                                        <div key={fi} style={{
                                          padding: "8px 12px", display: "flex", alignItems: "center", gap: 10,
                                          background: isHot ? E_PINK_SOFT : "transparent",
                                        }}>
                                          {f.icon === "hash" && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2"><line x1="4" y1="9" x2="20" y2="9"/><line x1="4" y1="15" x2="20" y2="15"/><line x1="10" y1="3" x2="8" y2="21"/><line x1="16" y1="3" x2="14" y2="21"/></svg>}
                                          {f.icon === "cal" && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/></svg>}
                                          <div style={{ flex: 1 }}>
                                            <div style={{ fontSize: 11.5, color: E_INK, fontWeight: 500 }}>{f.name}</div>
                                            <div style={{ fontSize: 10, color: "#94a3b8" }}>e.g., {f.eg}</div>
                                          </div>
                                        </div>
                                      );
                                    })}
                                  </div>
                                ))}
                              </div>
                            )}
                          </div>
                        );
                      })}

                      <div style={{ marginTop: 14, padding: "10px 12px", background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 11.5, color: "#475569", display: "flex", gap: 8, alignItems: "flex-start" }}>
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2" style={{ flexShrink: 0, marginTop: 1 }}><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                        Variables will be replaced with actual contact data when the broadcast is sent. Preview shows sample values.
                      </div>
                    </div>

                    {/* Right: Live phone preview */}
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                      <div style={{ fontSize: 11.5, fontWeight: 600, color: E_INK }}>Live Preview</div>
                      <WAPhone height={400} time="04:55 PM">
                        <WATemplateBubble
                          header="Booking Confirmed"
                          body={
                            [
                              `Hi ${varStep > 0 ? "John" : "{{1}}"}, your reservation at ${varStep > 1 ? "CONF-12345" : "{{2}}"} is confirmed.`,
                              ``,
                              `Check-in: ${varStep > 2 ? "March 15, 2024" : "{{3}}"}`,
                              `Confirmation: ${varStep > 3 ? "March 18, 2024" : "{{4}}"}`,
                              ``,
                              `Need anything before your trip? Reply here and our team will help with restaurant reservations, transfers, or any special arrangements.`,
                            ].join("\n")
                          }
                          time="04:55 PM"
                          buttons={[{ icon: "reply", label: "Yes, I'd like that" }, { icon: "reply", label: "No thanks" }]}
                        />
                      </WAPhone>
                      <div style={{ fontSize: 10, color: "#94a3b8" }}>Preview may differ from actual WhatsApp display</div>
                    </div>
                  </div>
                </div>
              )}

              {/* Step 4: Audience */}
              {phase === 5 && (
                <div style={{ animation: "fadeIn .4s", maxWidth: 920, margin: "0 auto" }}>
                  <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Select Audience</h4>
                  <p style={{ fontSize: 13, color: "#64748b", margin: "0 0 22px" }}>Choose which contacts will receive this broadcast.</p>

                  {/* Big counter */}
                  <div style={{ background: "linear-gradient(120deg, " + E_PINK_SOFT + ", #fff)", border: "1px solid " + E_PINK, borderRadius: 12, padding: "20px 24px", display: "flex", alignItems: "center", gap: 16, marginBottom: 18 }}>
                    <div style={{ width: 52, height: 52, borderRadius: 12, background: "#fff", display: "grid", placeItems: "center" }}>
                      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke={E_PINK} strokeWidth="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>
                    </div>
                    <div>
                      <div style={{ fontSize: 38, fontWeight: 700, color: E_INK, lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{audCount.toLocaleString()}</div>
                      <div style={{ fontSize: 13, color: "#64748b", marginTop: 4 }}>All opted-in contacts</div>
                    </div>
                  </div>

                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 10 }}>Selection Method</div>
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10, marginBottom: 18 }}>
                    {[
                      { name: "All Contacts", sub: "28,263 opted-in", icon: "users" },
                      { name: "Saved Segments", sub: "23 segments available", icon: "filter" },
                      { name: "Custom Filter", sub: "Build conditions", icon: "settings" },
                    ].map((m, i) => {
                      const sel = i === 0;
                      return (
                        <div key={i} style={{
                          border: "1.5px solid " + (sel ? E_INK : "#f1f5f9"),
                          background: sel ? "#f8fafc" : "#fff",
                          boxShadow: sel ? "0 0 0 3px rgba(15,23,42,.06)" : "none",
                          borderRadius: 10, padding: "14px 16px",
                          display: "flex", alignItems: "center", gap: 12,
                        }}>
                          <div style={{ width: 36, height: 36, background: sel ? "#fff" : "#f8fafc", borderRadius: 8, display: "grid", placeItems: "center" }}>
                            {m.icon === "users" && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8z"/></svg>}
                            {m.icon === "filter" && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>}
                            {m.icon === "settings" && <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 01-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 008 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H2a2 2 0 010-4h.09A1.65 1.65 0 004.6 8a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V2a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H22a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>}
                          </div>
                          <div>
                            <div style={{ fontSize: 13, fontWeight: 700, color: E_INK }}>{m.name}</div>
                            <div style={{ fontSize: 11, color: "#64748b" }}>{m.sub}</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  <div style={{ background: "#f8fafc", border: "1px solid #f1f5f9", borderRadius: 10, padding: "12px 14px", fontSize: 12, color: "#475569", display: "flex", gap: 10, alignItems: "flex-start", marginBottom: 18 }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#64748b" strokeWidth="2" style={{ flexShrink: 0, marginTop: 1 }}><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
                    <div><b>Broadcasting to all contacts</b><br/>This will send to all 28,263 opted-in contacts across all hotels. Contacts who have opted out will be automatically excluded.</div>
                  </div>

                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: E_INK }}>UTM Parameters</div>
                    <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".08em", color: "#475569", background: "#f1f5f9", padding: "3px 8px", borderRadius: 4 }}>FOR LINK TRACKING</div>
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
                    {[
                      { l: "Source", v: "whatsapp" },
                      { l: "Medium", v: "broadcast" },
                      { l: "Campaign", v: "win-back-365" },
                      { l: "Content (optional)", v: "cta-button" },
                    ].map((u, i) => (
                      <div key={i}>
                        <div style={{ fontSize: 11, fontWeight: 600, color: E_INK, marginBottom: 4 }}>{u.l}</div>
                        <div style={{ border: "1px solid #f1f5f9", borderRadius: 6, padding: "7px 10px", fontSize: 12, color: i === 3 ? "#94a3b8" : E_INK, fontFamily: "monospace" }}>{u.v}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Step 5: Schedule */}
              {phase >= 6 && (
                <div style={{ animation: "fadeIn .4s", maxWidth: 920, margin: "0 auto" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
                    <div>
                      <h4 style={{ fontSize: 22, fontWeight: 700, color: E_INK, margin: "0 0 4px" }}>Schedule &amp; Review</h4>
                      <p style={{ fontSize: 13, color: "#64748b", margin: 0 }}>Choose when to send your broadcast and review all settings.</p>
                    </div>
                    <div style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 14px", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12, color: E_INK, fontWeight: 500 }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2.4"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                      Send Test
                    </div>
                  </div>

                  <div style={{ fontSize: 13, fontWeight: 700, color: E_INK, marginBottom: 10 }}>When to send</div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 18 }}>
                    {[
                      { name: "Send Now", sub: "Start sending immediately", icon: "send" },
                      { name: "Schedule", sub: "Send at a specific time", icon: "clock" },
                    ].map((m, i) => {
                      const sel = i === 1;
                      return (
                        <div key={i} style={{
                          border: "1.5px solid " + (sel ? E_INK : "#f1f5f9"),
                          background: sel ? "#f8fafc" : "#fff",
                          boxShadow: sel ? "0 0 0 3px rgba(15,23,42,.06)" : "none",
                          borderRadius: 10, padding: "14px 16px",
                          display: "flex", alignItems: "center", gap: 12,
                        }}>
                          <div style={{ width: 32, height: 32, background: sel ? "#fff" : "#f8fafc", borderRadius: 8, display: "grid", placeItems: "center" }}>
                            {m.icon === "send" && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>}
                            {m.icon === "clock" && <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>}
                          </div>
                          <div>
                            <div style={{ fontSize: 13, fontWeight: 700, color: E_INK }}>{m.name}</div>
                            <div style={{ fontSize: 11, color: "#64748b" }}>{m.sub}</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  <div style={{ fontSize: 12, fontWeight: 600, color: E_INK, marginBottom: 6 }}>Select date and time</div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 200px", gap: 10, marginBottom: 18 }}>
                    <div style={{ border: "1px solid " + WA_AI_PURPLE, borderRadius: 8, padding: "10px 12px", display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: E_INK, fontWeight: 500 }}>
                      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={E_INK} strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/></svg>
                      May 20th, 2026
                    </div>
                    <div style={{ border: "1px solid " + WA_AI_PURPLE, borderRadius: 8, padding: "10px 12px", display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 12.5, color: E_INK, fontWeight: 500 }}>
                      11:00
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#94a3b8" strokeWidth="2.4"><polyline points="6 9 12 15 18 9"/></svg>
                    </div>
                  </div>

                  <div style={{ marginBottom: 18, display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", border: "1px solid #f1f5f9", borderRadius: 8 }}>
                    <div>
                      <div style={{ fontSize: 12.5, fontWeight: 600, color: E_INK }}>Respect Do Not Disturb</div>
                      <div style={{ fontSize: 11, color: "#64748b" }}>Delay messages to contacts in their DND hours</div>
                    </div>
                    <div style={{ marginLeft: "auto", width: 36, height: 20, background: WA_GREEN, borderRadius: 99, position: "relative" }}>
                      <div style={{ position: "absolute", right: 2, top: 2, width: 16, height: 16, borderRadius: 99, background: "#fff" }} />
                    </div>
                  </div>

                  {/* Pre-launch Checklist */}
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: E_INK }}>Pre-launch Checklist</div>
                    <div style={{ fontSize: 11, fontWeight: 700, color: E_PINK, background: E_PINK_SOFT, padding: "3px 10px", borderRadius: 4 }}>{checkStep >= 5 ? "ALL CLEAR" : "Reviewing…"}</div>
                  </div>
                  <div style={{ display: "grid", gap: 6 }}>
                    {[
                      { name: "Broadcast name", sub: "Name provided" },
                      { name: "Language selected", sub: "Language: en" },
                      { name: "Template selected", sub: "booking_confirmed_v3" },
                      { name: "Variable values", sub: "4 variable(s) filled" },
                      { name: "Audience selected", sub: "28,263 recipients" },
                    ].map((c, i) => {
                      const done = checkStep > i;
                      return (
                        <div key={i} style={{
                          background: done ? E_PINK_SOFT : "#f8fafc",
                          border: "1px solid " + (done ? E_PINK_SOFT : "#f1f5f9"),
                          borderRadius: 8, padding: "8px 12px",
                          display: "flex", alignItems: "center", gap: 10,
                          transition: "all .25s",
                        }}>
                          {done ? (
                            <WAStepIcon name="check" size={14} color={E_PINK}/>
                          ) : (
                            <span style={{ width: 14, height: 14, border: "1.5px solid #cbd5e1", borderRadius: 99, display: "inline-block" }} />
                          )}
                          <div>
                            <div style={{ fontSize: 12.5, fontWeight: 600, color: done ? E_PINK : "#94a3b8" }}>{c.name}</div>
                            <div style={{ fontSize: 11, color: done ? "#475569" : "#94a3b8" }}>{c.sub}</div>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  {/* Final action */}
                  {checkStep >= 5 && (
                    <div style={{ marginTop: 18, padding: "14px 16px", background: "linear-gradient(90deg, " + E_PINK_SOFT + ", #fff)", border: "1px solid " + E_PINK, borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "space-between", animation: "fadeIn .4s" }}>
                      <div style={{ fontSize: 12.5, color: "#475569" }}>
                        <b style={{ color: E_PINK }}>Scheduled for May 20, 2026 · 11:00.</b> Broadcast will queue 28,263 sends with DND awareness.
                      </div>
                      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "10px 18px", background: WA_GREEN, color: "#fff", borderRadius: 8, fontSize: 13, fontWeight: 700 }}>
                        <WAStepIcon name="check" size={13} color="#fff"/>
                        Confirm Broadcast
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Idle */}
              {phase === 0 && (
                <div style={{ display: "grid", placeItems: "center", height: 480 }}>
                  <div style={{ textAlign: "center", color: "#94a3b8" }}>
                    <div style={{ width: 64, height: 64, borderRadius: 16, background: E_PINK_SOFT, display: "grid", placeItems: "center", margin: "0 auto 14px" }}>
                      <svg width="30" height="30" viewBox="0 0 24 24" fill="#fff"><path d="M20.52 3.449C12.831-3.984.106 1.407.101 11.893c0 2.096.549 4.142 1.595 5.945L0 24l6.335-1.652a11.882 11.882 0 005.71 1.447h.006c10.493 0 16.965-12.5 11.987-19.875A12.062 12.062 0 0020.52 3.449z"/></svg>
                    </div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: E_INK }}>WhatsApp Broadcast Wizard</div>
                    <div style={{ fontSize: 12, marginTop: 4 }}>Watch a 28,263-send win-back assemble itself: DND-aware, rate-throttled, ready in minutes.</div>
                  </div>
                </div>
              )}
            </div>

            {/* Footer nav (visual only) */}
            <div style={{ padding: "14px 28px", borderTop: "1px solid #f1f5f9", display: "flex", justifyContent: "space-between" }}>
              <div style={{ display: "flex", gap: 8 }}>
                <div style={{ padding: "8px 14px", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12, color: "#475569", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 5 }}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2.4"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                  Exit
                </div>
                <div style={{ padding: "8px 14px", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12, color: "#475569", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 5 }}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2.4"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/></svg>
                  Save Draft
                </div>
              </div>
              <div style={{ display: "flex", gap: 8 }}>
                {step > 1 && <div style={{ padding: "8px 14px", border: "1px solid #f1f5f9", borderRadius: 8, fontSize: 12, color: "#475569", fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 5 }}>
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#475569" strokeWidth="2.4"><polyline points="15 18 9 12 15 6"/></svg>
                  Previous
                </div>}
                <div style={{ padding: "8px 18px", background: E_INK, color: "#fff", borderRadius: 8, fontSize: 12, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 5 }}>
                  {step === 5 ? "Confirm" : "Next"}
                  <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.4"><polyline points="9 18 15 12 9 6"/></svg>
                </div>
              </div>
            </div>
          </div>
          </ScaleFrame>

          <div style={{ textAlign: "center", marginTop: 18, fontSize: 12, color: "#94a3b8" }}>
            Pre-launch checklist &middot; DND-aware send &middot; UTM-tracked &middot; opt-out compliant
          </div>
        </div>

        <style>{`
          @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
          @keyframes fadeInUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
          @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
          @keyframes spin { to { transform: rotate(360deg); } }
          @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
          @keyframes popIn { 0% { transform: scale(.7); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }
          @keyframes drawCheck { to { stroke-dashoffset: 0; } }
          @keyframes ringPulse { 0% { transform: scale(.95); opacity: .9; } 100% { transform: scale(1.4); opacity: 0; } }
          @keyframes confetti { 0% { transform: translateY(-40px) rotate(0); opacity: 0; } 8% { opacity: 1; } 100% { transform: translateY(640px) rotate(540deg); opacity: 0; } }
          @keyframes sendNudge { 0%, 100% { transform: translate(0, 0); } 50% { transform: translate(3px, -3px); } }
        `}</style>
      </section>
    );
  };

  window.WABroadcastArtifact = WABroadcastArtifact;

  // ============== MAIN WHATSAPP SECTION ==============
  const WhatsAppSection = () => (
    <>
      <WhatsAppIntro />
      <WAStudioArtifact />
      <WAEditTemplateArtifact />
      <WABroadcastArtifact />
    </>
  );

  window.WhatsAppSection = WhatsAppSection;

  /* ===== analytics_charts.jsx ===== */

  // Chart primitives + theme tokens for the campaign analytics dashboard.
  // Pure SVG, no chart libs. Light + dark aware.

  const ANALYTICS_THEMES = {
    light: {
      pageBg: "#fef9f4",
      surface: "#ffffff",
      surfaceMuted: "#fafbfc",
      chip: "#f1f5f9",
      chipText: "#475569",
      text: "#0f172a",
      textSoft: "#334155",
      muted: "#64748b",
      micro: "#94a3b8",
      border: "#e5e7eb",
      borderSoft: "#eef0f3",
      divider: "#f1f5f9",
      track: "#eef2f7",
      glow: "rgba(15,23,42,.04)",
      cardShadow: "0 1px 2px rgba(15,23,42,.04), 0 8px 24px rgba(15,23,42,.04)",
      frameShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
    },
    dark: {
      pageBg: "#0b0d12",
      surface: "#14171f",
      surfaceMuted: "#11141b",
      chip: "#1f2937",
      chipText: "#cbd5e1",
      text: "#f1f5f9",
      textSoft: "#cbd5e1",
      muted: "#94a3b8",
      micro: "#64748b",
      border: "#222836",
      borderSoft: "#1a1f2a",
      divider: "#1c2230",
      track: "#1c2230",
      glow: "rgba(0,0,0,.4)",
      cardShadow: "0 1px 2px rgba(0,0,0,.5), 0 8px 24px rgba(0,0,0,.35)",
      frameShadow: "0 30px 80px -20px rgba(0,0,0,.6), 0 8px 24px rgba(0,0,0,.4)",
    },
  };

  const CHANNEL_ACCENTS = {
    email:    { primary: "#ED4D86", primaryDeep: "#be185d", soft: "rgba(237,77,134,.12)", softer: "rgba(237,77,134,.05)", ring: "rgba(237,77,134,.18)" },
    whatsapp: { primary: "#ED4D86", primaryDeep: "#be185d", soft: "rgba(237,77,134,.12)", softer: "rgba(237,77,134,.05)", ring: "rgba(237,77,134,.18)" },
    ai:       { primary: "#ED4D86", primaryDeep: "#be185d", soft: "rgba(237,77,134,.12)",  softer: "rgba(237,77,134,.05)",  ring: "rgba(237,77,134,.20)" },
  };

  // ============================================================
  // KPI Card with sparkline
  // ============================================================
  const KpiCard = ({ label, value, delta, deltaDir = "up", subtle, sparkData, t, accent }) => {
    const positive = deltaDir === "up";
    return (
      <div style={{
        background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12,
        padding: "16px 18px 12px", position: "relative", overflow: "hidden",
        minHeight: 116,
      }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".18em", color: t.muted, textTransform: "uppercase" }}>
          {label}
        </div>
        <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(20px, 2.6vw, 36px)", fontWeight: 400, color: t.text, lineHeight: 1.05, marginTop: 6, letterSpacing: "-0.01em" }}>
          {value}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 6, fontSize: 11.5, color: t.muted }}>
          <span style={{
            color: positive ? "#16a34a" : "#dc2626",
            fontWeight: 600, fontSize: 11.5,
            display: "inline-flex", alignItems: "center", gap: 3,
          }}>
            {positive ? "↑" : "↓"} {delta}
          </span>
          <span>{subtle || "vs last 30d"}</span>
        </div>
        {sparkData && (
          <div style={{ position: "absolute", left: 14, right: 14, bottom: 10, height: 28, pointerEvents: "none" }}>
            <Sparkline data={sparkData} color={accent.primary} fill={accent.soft} />
          </div>
        )}
      </div>
    );
  };

  // ============================================================
  // Sparkline
  // ============================================================
  const Sparkline = ({ data, color, fill, height = 28 }) => {
    const w = 200, h = height;
    const min = Math.min(...data), max = Math.max(...data);
    const range = max - min || 1;
    const stepX = w / (data.length - 1);
    const pts = data.map((v, i) => [i * stepX, h - ((v - min) / range) * (h - 4) - 2]);
    const path = pts.map((p, i) => (i === 0 ? `M${p[0]},${p[1]}` : `L${p[0]},${p[1]}`)).join(" ");
    const area = `${path} L${w},${h} L0,${h} Z`;
    return (
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height: "100%", display: "block" }}>
        <defs>
          <linearGradient id={`spark-${color}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity=".25" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d={area} fill={`url(#spark-${color})`} />
        <path d={path} fill="none" stroke={color} strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.4" fill={color} />
      </svg>
    );
  };

  // ============================================================
  // Area chart (the big call-volume style)
  // ============================================================
  const AreaChart = ({ data, labels, color, t, height = 220, currency }) => {
    const w = 700, h = height;
    const padL = 28, padR = 12, padT = 18, padB = 28;
    const min = 0, max = Math.max(...data) * 1.15;
    const range = max - min || 1;
    const stepX = (w - padL - padR) / (data.length - 1);
    const pts = data.map((v, i) => [padL + i * stepX, padT + (h - padT - padB) - ((v - min) / range) * (h - padT - padB)]);
    // smooth curve
    const path = pts.reduce((acc, p, i, arr) => {
      if (i === 0) return `M${p[0]},${p[1]}`;
      const prev = arr[i - 1];
      const cx = (prev[0] + p[0]) / 2;
      return `${acc} C${cx},${prev[1]} ${cx},${p[1]} ${p[0]},${p[1]}`;
    }, "");
    const area = `${path} L${pts[pts.length - 1][0]},${h - padB} L${pts[0][0]},${h - padB} Z`;
    const gridLines = 4;
    const fmt = (v) => currency ? `$${(v / 1000).toFixed(1)}k` : Math.round(v).toLocaleString();
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto", display: "block" }}>
        <defs>
          <linearGradient id={`area-${color}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity=".30" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        {/* gridlines */}
        {Array.from({ length: gridLines }).map((_, i) => {
          const y = padT + ((h - padT - padB) / (gridLines - 1)) * i;
          const v = max - ((max - min) / (gridLines - 1)) * i;
          return (
            <g key={i}>
              <line x1={padL} y1={y} x2={w - padR} y2={y} stroke={t.divider} strokeWidth="1" />
              <text x={padL - 6} y={y + 3} textAnchor="end" fontSize="9" fill={t.micro} fontFamily="Inter">
                {i === gridLines - 1 ? "" : fmt(v)}
              </text>
            </g>
          );
        })}
        <path d={area} fill={`url(#area-${color})`} />
        <path d={path} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        {/* end dot */}
        <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="4" fill={color} stroke={t.surface} strokeWidth="2" />
        {/* x labels */}
        {labels && labels.map((l, i) => (
          i % Math.ceil(labels.length / 6) === 0 || i === labels.length - 1 ? (
            <text key={i} x={padL + i * stepX} y={h - 8} textAnchor="middle" fontSize="9" fill={t.micro} fontFamily="Inter">{l}</text>
          ) : null
        ))}
      </svg>
    );
  };

  // ============================================================
  // Donut chart with center label
  // ============================================================
  const Donut = ({ segments, centerLabel, centerSub, color, t, size = 220 }) => {
    const cx = size / 2, cy = size / 2, r = size * 0.40, rInner = size * 0.30;
    const total = segments.reduce((s, x) => s + x.value, 0);
    let startAngle = -Math.PI / 2;
    const polar = (a, rr) => [cx + Math.cos(a) * rr, cy + Math.sin(a) * rr];
    const arcs = segments.map((s, i) => {
      const angle = (s.value / total) * Math.PI * 2;
      const endAngle = startAngle + angle;
      const large = angle > Math.PI ? 1 : 0;
      const [x1, y1] = polar(startAngle, r);
      const [x2, y2] = polar(endAngle, r);
      const [x3, y3] = polar(endAngle, rInner);
      const [x4, y4] = polar(startAngle, rInner);
      const path = `M${x1},${y1} A${r},${r} 0 ${large} 1 ${x2},${y2} L${x3},${y3} A${rInner},${rInner} 0 ${large} 0 ${x4},${y4} Z`;
      startAngle = endAngle;
      return { path, color: s.color || color, key: i };
    });
    return (
      <div style={{ display: "flex", justifyContent: "center", alignItems: "center", position: "relative" }}>
        <svg viewBox={`0 0 ${size} ${size}`} style={{ width: size, height: size, filter: `drop-shadow(0 8px 24px ${color}44)` }}>
          {arcs.map((a) => <path key={a.key} d={a.path} fill={a.color} />)}
        </svg>
        <div style={{ position: "absolute", textAlign: "center", pointerEvents: "none" }}>
          <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 32, fontWeight: 400, color: t.text, lineHeight: 1, fontStyle: "italic" }}>{centerLabel}</div>
          <div style={{ fontSize: 11, color: t.muted, marginTop: 4, letterSpacing: ".06em" }}>{centerSub}</div>
        </div>
      </div>
    );
  };

  // ============================================================
  // Progress list (Top intents / templates)
  // ============================================================
  const ProgressList = ({ items, t, accent }) => {
    const max = Math.max(...items.map(x => x.value));
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {items.map((it, i) => (
          <div key={i}>
            <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6 }}>
              <div style={{ fontSize: 13, color: t.text, fontWeight: 500 }}>{it.label}</div>
              <div style={{ fontSize: 12, color: t.muted, fontVariantNumeric: "tabular-nums" }}>{it.value.toLocaleString()}{it.suffix || ""}</div>
            </div>
            <div style={{ height: 6, background: t.track, borderRadius: 99, overflow: "hidden" }}>
              <div style={{
                height: "100%", width: `${(it.value / max) * 100}%`,
                background: it.color || `linear-gradient(90deg, ${accent.primary}, ${accent.primaryDeep})`,
                borderRadius: 99,
              }} />
            </div>
          </div>
        ))}
      </div>
    );
  };

  // ============================================================
  // Recent list (Recent calls / sends)
  // ============================================================
  const RecentList = ({ items, t }) => (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {items.map((it, i) => (
        <div key={i} style={{
          display: "flex", alignItems: "center", gap: 10, padding: "9px 0",
          borderBottom: i === items.length - 1 ? "none" : `1px solid ${t.divider}`,
        }}>
          <span style={{
            width: 8, height: 8, borderRadius: 99,
            background: it.dot || "#1f9d55", flexShrink: 0,
          }} />
          <span style={{ fontSize: 13, color: t.text, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{it.name}</span>
          <span style={{ fontSize: 12, color: t.muted, fontVariantNumeric: "tabular-nums" }}>{it.time}</span>
          <span style={{
            fontSize: 9.5, fontWeight: 700, letterSpacing: ".1em",
            padding: "3px 8px", borderRadius: 99,
            background: it.tagBg || t.chip, color: it.tagFg || t.chipText,
            textTransform: "uppercase",
          }}>{it.tag}</span>
        </div>
      ))}
    </div>
  );

  // ============================================================
  // Stacked horizontal bar (for engagement breakdown by hour-band)
  // ============================================================
  const StackedBars = ({ rows, segments, t, height = 220 }) => {
    const w = 700, h = height;
    const padL = 40, padR = 12, padT = 8, padB = 22;
    const barH = (h - padT - padB) / rows.length - 4;
    const max = Math.max(...rows.map(r => r.values.reduce((s, v) => s + v, 0)));
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto", display: "block" }}>
        {rows.map((r, i) => {
          const y = padT + i * (barH + 4);
          let x = padL;
          const total = r.values.reduce((s, v) => s + v, 0);
          const widthPx = ((w - padL - padR) * total) / max;
          return (
            <g key={i}>
              <text x={padL - 8} y={y + barH / 2 + 3} textAnchor="end" fontSize="10" fill={t.muted} fontFamily="Inter">{r.label}</text>
              {r.values.map((v, j) => {
                const segW = (v / total) * widthPx;
                const seg = (
                  <rect key={j} x={x} y={y} width={segW} height={barH} fill={segments[j].color}
                    rx={j === 0 ? 4 : 0} />
                );
                x += segW;
                return seg;
              })}
              <text x={x + 6} y={y + barH / 2 + 3} fontSize="10" fill={t.muted} fontFamily="Inter" fontVariantNumeric="tabular-nums">{total.toLocaleString()}</text>
            </g>
          );
        })}
      </svg>
    );
  };

  // ============================================================
  // Heatmap (best send time)
  // ============================================================
  const Heatmap = ({ matrix, days, hours, color, t }) => {
    const cell = 18, gap = 2;
    const w = hours.length * (cell + gap) + 30;
    const h = days.length * (cell + gap) + 22;
    const max = Math.max(...matrix.flat());
    return (
      <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: "auto", display: "block" }}>
        {hours.map((hr, i) =>
          i % 3 === 0 ? <text key={i} x={30 + i * (cell + gap) + cell / 2} y={10} textAnchor="middle" fontSize="8" fill={t.micro} fontFamily="Inter">{hr}</text> : null
        )}
        {days.map((d, r) => (
          <text key={r} x={24} y={22 + r * (cell + gap) + cell / 2 + 3} textAnchor="end" fontSize="9" fill={t.muted} fontFamily="Inter">{d}</text>
        ))}
        {matrix.map((row, r) =>
          row.map((v, c) => {
            const op = 0.08 + (v / max) * 0.92;
            return <rect key={`${r}-${c}`} x={30 + c * (cell + gap)} y={14 + r * (cell + gap)} width={cell} height={cell} rx="3" fill={color} opacity={op} />;
          })
        )}
      </svg>
    );
  };

  // ============================================================
  // Funnel
  // ============================================================
  const Funnel = ({ steps, color, t }) => {
    const max = steps[0].value;
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
        {steps.map((s, i) => {
          const pct = (s.value / max) * 100;
          const dropoff = i > 0 ? ((steps[i - 1].value - s.value) / steps[i - 1].value) * 100 : 0;
          return (
            <div key={i}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                <div style={{ fontSize: 13, color: t.text, fontWeight: 500 }}>{s.label}</div>
                <div style={{ display: "flex", gap: 12, alignItems: "baseline", fontVariantNumeric: "tabular-nums" }}>
                  <span style={{ fontSize: 12, color: t.muted }}>{((s.value / max) * 100).toFixed(1)}%</span>
                  <span style={{ fontSize: 13, color: t.text, fontWeight: 600 }}>{s.value.toLocaleString()}</span>
                </div>
              </div>
              <div style={{ height: 32, background: t.track, borderRadius: 6, overflow: "hidden", position: "relative" }}>
                <div style={{
                  height: "100%", width: `${pct}%`,
                  background: `linear-gradient(90deg, ${color} 0%, ${color}cc 100%)`,
                  display: "flex", alignItems: "center", padding: "0 10px",
                  color: "#fff", fontSize: 11, fontWeight: 600,
                }}>
                  {i > 0 && (
                    <span style={{ marginLeft: "auto", fontSize: 10, opacity: .9 }}>−{dropoff.toFixed(1)}% drop</span>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  // ============================================================
  // Card wrapper
  // ============================================================
  const Card = ({ title, subtitle, right, children, t, padding = "18px 20px", style }) => (
    <div style={{
      background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12,
      overflow: "hidden", display: "flex", flexDirection: "column", ...style,
    }}>
      {(title || right) && (
        <div style={{ padding, paddingBottom: 0, display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            {title && <div style={{ fontSize: 14, fontWeight: 600, color: t.text, letterSpacing: "-0.01em" }}>{title}</div>}
            {subtitle && <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".18em", color: t.micro, textTransform: "uppercase", marginTop: 4 }}>{subtitle}</div>}
          </div>
          {right && <div>{right}</div>}
        </div>
      )}
      <div style={{ padding, paddingTop: title ? 14 : padding, flex: 1 }}>
        {children}
      </div>
    </div>
  );

  window.ANALYTICS_THEMES = ANALYTICS_THEMES;
  window.CHANNEL_ACCENTS = CHANNEL_ACCENTS;
  Object.assign(window, { KpiCard, Sparkline, AreaChart, Donut, ProgressList, RecentList, StackedBars, Heatmap, Funnel, Card });

  /* ===== analytics_panels.jsx ===== */

  // Per-channel content panels for the analytics dashboard.

  // ============================================================
  // SEED DATA
  // ============================================================
  const EMAIL_DATA = {
    kpis: [
      { label: "Sends · 30d",      value: "184,290", delta: "12.4%", deltaDir: "up",   spark: [12,14,13,16,15,18,17,20,19,22,21,24,23,26,28] },
      { label: "Open rate",        value: "47.8%",   delta: "5.2%",  deltaDir: "up",   spark: [38,40,39,42,41,43,44,46,45,47,46,48,47,48,47.8] },
      { label: "Click-to-open",    value: "26.1%",   delta: "3.8%",  deltaDir: "up",   spark: [20,22,21,23,22,24,23,25,24,26,25,26,26,26,26.1] },
      { label: "Conversion rate",  value: "4.62%",   delta: "0.9%",  deltaDir: "up",   spark: [3.2,3.4,3.3,3.6,3.7,3.8,4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.6,4.62] },
    ],
    volume: {
      data: [320,280,210,190,170,180,260,420,640,820,940,1020,1080,1120,1180,1260,1340,1420,1480,1520,1480,1380,1240,980],
      labels: Array.from({length:24}, (_,i) => String(i).padStart(2,"0")),
      total: "27,884",
    },
    donut: {
      center: "47.8%",
      sub: "open rate",
      segments: [
        { label: "Opened",     value: 88090, color: "#ED4D86" },
        { label: "Clicked",    value: 23010, color: "#be185d" },
        { label: "Converted",  value: 8470,  color: "#831843" },
        { label: "Unopened",   value: 64720, color: "#fbcfe8" },
      ],
    },
    topItems: [
      { label: "Pre-stay · Welcome",          value: 28400 },
      { label: "Confirmation receipt",        value: 22700 },
      { label: "Day-of arrival",              value: 18200 },
      { label: "Post-stay · Review request",  value: 14600 },
      { label: "Win-back · 365 days",         value: 9800 },
      { label: "Restaurant offer · Members",  value: 6200 },
    ],
    recent: [
      { name: "Spring · 2-for-1 dinner",     time: "11:42 AM", tag: "OPEN 52.1%",  tagBg: "#ffe5ed", tagFg: "#be185d", dot: "#22c55e" },
      { name: "Pre-stay welcome (FR-FR)",    time: "10:30 AM", tag: "OPEN 49.3%",  tagBg: "#ffe5ed", tagFg: "#be185d", dot: "#22c55e" },
      { name: "Suite upgrade · Loyalty",     time: "09:14 AM", tag: "CLICK 18%",   tagBg: "#fef3c7", tagFg: "#a16207", dot: "#22c55e" },
      { name: "Booking confirmation",        time: "08:58 AM", tag: "DELIVERED",   tagBg: "#dcfce7", tagFg: "#15803d", dot: "#22c55e" },
      { name: "Concierge follow-up",         time: "08:42 AM", tag: "REPLIED",     tagBg: "#dbeafe", tagFg: "#1d4ed8", dot: "#22c55e" },
      { name: "Win-back · 365d cohort",      time: "08:30 AM", tag: "SCHEDULED",   tagBg: "#f1f5f9", tagFg: "#475569", dot: "#94a3b8" },
    ],
  };

  const WHATSAPP_DATA = {
    kpis: [
      { label: "Messages sent",  value: "62,180", delta: "18.6%", deltaDir: "up",   spark: [22,24,28,32,35,38,42,46,49,52,55,58,60,61,62] },
      { label: "Delivery rate",  value: "99.2%",  delta: "0.3%",  deltaDir: "up",   spark: [98.8,98.9,99,98.9,99.1,99,99.1,99.2,99.1,99.2,99.2,99.2,99.2,99.2,99.2] },
      { label: "Read rate",      value: "84.6%",  delta: "4.1%",  deltaDir: "up",   spark: [76,77,78,79,80,81,82,83,82,83,84,84,84,84,84.6] },
      { label: "Reply rate",     value: "21.4%",  delta: "2.8%",  deltaDir: "up",   spark: [14,15,16,16,17,17,18,19,19,20,20,21,21,21,21.4] },
    ],
    volume: {
      data: [80,60,40,30,28,35,90,180,280,360,420,470,510,540,560,580,610,640,680,710,690,640,520,360],
      labels: Array.from({length:24}, (_,i) => String(i).padStart(2,"0")),
      total: "8,760",
    },
    donut: {
      center: "84.6%",
      sub: "read rate",
      segments: [
        { label: "Read",      value: 52600, color: "#ED4D86" },
        { label: "Replied",   value: 13310, color: "#be185d" },
        { label: "Delivered", value: 9580,  color: "#fbcfe8" },
        { label: "Failed",    value: 690,   color: "#ffe5ed" },
      ],
    },
    topItems: [
      { label: "Booking confirmation · ES",  value: 18400 },
      { label: "Check-in instructions",      value: 14200 },
      { label: "Welcome · concierge",        value: 11600 },
      { label: "Spa upsell · 24h pre-stay",  value: 8200 },
      { label: "Late checkout offer",        value: 5400 },
      { label: "NPS · post-stay",            value: 4100 },
    ],
    recent: [
      { name: "Antoni Joan",     time: "8:35 PM",  tag: "REPLIED",     tagBg: "#ffe5ed", tagFg: "#be185d", dot: "#ED4D86" },
      { name: "Daniel Antich",   time: "8:30 PM",  tag: "READ",        tagBg: "#fbcfe8", tagFg: "#9d174d", dot: "#ED4D86" },
      { name: "Maria González",  time: "4:18 PM",  tag: "BOOKED",      tagBg: "#ffe5ed", tagFg: "#be185d", dot: "#ED4D86" },
      { name: "Lukas Müller",    time: "10:30 AM", tag: "READ",        tagBg: "#fbcfe8", tagFg: "#9d174d", dot: "#ED4D86" },
      { name: "Sofia Rossi",     time: "9:44 AM",  tag: "DELIVERED",   tagBg: "#f1f5f9", tagFg: "#475569", dot: "#94a3b8" },
      { name: "Ben Carter",      time: "8:44 AM",  tag: "REPLIED",     tagBg: "#ffe5ed", tagFg: "#be185d", dot: "#ED4D86" },
    ],
  };

  // ============================================================
  // CHANNEL PANEL, used for both Email + WhatsApp
  // ============================================================
  const ChannelPanel = ({ channel, t }) => {
    const data = channel === "email" ? EMAIL_DATA : WHATSAPP_DATA;
    const accent = channel === "email" ? CHANNEL_ACCENTS.email : CHANNEL_ACCENTS.whatsapp;
    const channelLabel = channel === "email" ? "Email" : "WhatsApp";

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {/* KPI ROW */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          {data.kpis.map((k, i) => (
            <KpiCard key={i} {...k} sparkData={k.spark} t={t} accent={accent} />
          ))}
        </div>

        {/* MAIN ROW: volume + donut */}
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 14 }}>
          <Card t={t} title={`${channelLabel} volume`} subtitle="Last 24 hours · bucketed hourly"
            right={<div style={{ fontSize: 11, color: t.muted, fontVariantNumeric: "tabular-nums" }}>{data.volume.total} TOTAL</div>}>
            <AreaChart data={data.volume.data} labels={data.volume.labels} color={accent.primary} t={t} height={200} />
          </Card>

          <Card t={t} title="Outcome mix" subtitle={`All outcomes · 30d`}>
            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <Donut segments={data.donut.segments} centerLabel={data.donut.center} centerSub={data.donut.sub} color={accent.primary} t={t} size={180} />
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {data.donut.segments.map((s, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: s.color }} />
                    <span style={{ color: t.text, flex: 1 }}>{s.label}</span>
                    <span style={{ color: t.muted, fontVariantNumeric: "tabular-nums" }}>{s.value.toLocaleString()}</span>
                  </div>
                ))}
              </div>
            </div>
          </Card>
        </div>

        {/* BOTTOM ROW: top items + recent */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Card t={t} title={channel === "email" ? "Top campaigns" : "Top templates"} subtitle="By volume · 30d">
            <ProgressList items={data.topItems} t={t} accent={accent} />
          </Card>
          <Card t={t} title={channel === "email" ? "Recent sends" : "Recent broadcasts"} subtitle="Live · last hour">
            <RecentList items={data.recent} t={t} />
          </Card>
        </div>
      </div>
    );
  };

  // ============================================================
  // AI INSIGHTS PANEL
  // ============================================================
  const AGENT_REPORTS = [
    {
      id: "anomaly", title: "Anomaly Detection", tag: "Anomaly", tagBg: "#fee2e2", tagFg: "#b91c1c",
      score: 94, status: "ok",
      summary: "No statistically significant anomalies detected across 124 campaigns this week. One outlier flagged: Spring · 2-for-1 (open rate 2.3σ above baseline), confirmed organic, not a tracking error.",
      details: [
        { k: "Campaigns scanned", v: "124" },
        { k: "Anomaly threshold", v: "2.0σ" },
        { k: "Outliers flagged", v: "1 (positive)" },
        { k: "False positives caught", v: "0" },
      ],
    },
    {
      id: "attribution", title: "Revenue Attribution", tag: "Revenue", tagBg: "#dcfce7", tagFg: "#15803d",
      score: 88, status: "ok",
      summary: "Time-decay attribution model (7-day window) attributes €184,200 in confirmed bookings to email + WhatsApp this month. Email assists 68% of WhatsApp-closed conversions; WhatsApp assists 41% of email-closed.",
      details: [
        { k: "Attribution model", v: "Time-decay · 7d window" },
        { k: "Attributed revenue", v: "€184,200" },
        { k: "Avg revenue / send", v: "€2.21" },
        { k: "Cross-channel assists", v: "54%" },
      ],
    },
    {
      id: "performance", title: "Performance Analyzer", tag: "Engagement", tagBg: "#dcfce7", tagFg: "#15803d",
      score: 86, status: "ok",
      summary: "Open rate (47.8%) and CTOR (26.1%) are 14% above the hospitality benchmark. Best performing slot: Tuesday 10:00 local. Worst: Sunday evening, recommend pausing weekend evening drops.",
      details: [
        { k: "Industry percentile", v: "Top 12%" },
        { k: "Best send window", v: "Tue 10:00 local" },
        { k: "Worst send window", v: "Sun 18:00–22:00" },
        { k: "Recommended action", v: "Pause Sun PM drops" },
      ],
    },
    {
      id: "ab", title: "A/B Test Synthesizer", tag: "Pattern", tagBg: "#dbeafe", tagFg: "#1d4ed8",
      score: 81, status: "ok",
      summary: "3 of 4 active A/B tests have reached significance. Subject line variant B (\"Your suite is ready\") wins by +18.4% open rate (p < 0.01, n=4,200). Promoting B to control.",
      details: [
        { k: "Tests active", v: "4" },
        { k: "Reached significance", v: "3" },
        { k: "Top winner uplift", v: "+18.4% opens" },
        { k: "Auto-promoted", v: "1" },
      ],
    },
    {
      id: "template", title: "Template Effectiveness", tag: "Content", tagBg: "#ede9fe", tagFg: "#6d28d9",
      score: 73, status: "warn",
      summary: "\"Win-back · 365d\" template has degraded for 3 consecutive weeks (open rate −9.2%). Subject line freshness score: 0.42. Recommend rotating creative, model suggests 4 variants ready to test.",
      details: [
        { k: "Templates analyzed", v: "38" },
        { k: "Degrading templates", v: "1" },
        { k: "Subject freshness", v: "0.42 / 1.00" },
        { k: "Variants ready", v: "4" },
      ],
    },
  ];

  const AgentRow = ({ report, t, expanded, onToggle }) => {
    const scoreColor = report.score >= 85 ? "#16a34a" : report.score >= 75 ? "#f59e0b" : "#dc2626";
    return (
      <div style={{ borderBottom: `1px solid ${t.divider}`, padding: "14px 4px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, cursor: "pointer" }} onClick={onToggle}>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{report.title}</span>
              <span style={{ fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 99, background: report.tagBg, color: report.tagFg, letterSpacing: ".04em" }}>{report.tag}</span>
              <div style={{ width: 80, height: 5, background: t.track, borderRadius: 99, overflow: "hidden" }}>
                <div style={{ height: "100%", width: `${report.score}%`, background: scoreColor, borderRadius: 99 }} />
              </div>
              <span style={{ fontSize: 11, color: t.muted, fontVariantNumeric: "tabular-nums" }}>{report.score}%</span>
            </div>
          </div>
          <span style={{ color: t.muted, fontSize: 12, transform: expanded ? "rotate(180deg)" : "none", transition: "transform .2s" }}>▾</span>
        </div>
        {expanded && (
          <div style={{ marginTop: 12, padding: "14px 16px", background: t.surfaceMuted, borderRadius: 8, border: `1px solid ${t.borderSoft}` }}>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: t.textSoft, marginBottom: 12 }}>
              {report.summary}
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: "8px 28px" }}>
              {report.details.map((d, i) => (
                <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: `1px dashed ${t.divider}`, fontSize: 12 }}>
                  <span style={{ color: t.muted }}>{d.k}</span>
                  <span style={{ color: t.text, fontWeight: 500, fontVariantNumeric: "tabular-nums" }}>{d.v}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  };

  const AiInsightsPanel = ({ t, channel }) => {
    const accent = CHANNEL_ACCENTS.ai;
    const [expanded, setExpanded] = React.useState("performance");
    const data = channel === "email" ? EMAIL_DATA : WHATSAPP_DATA;
    const channelLabel = channel === "email" ? "Email" : "WhatsApp";

    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {/* HEADER STRIP, Excellent badge + KPIs */}
        <div style={{
          background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12,
          padding: "20px 22px",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 18 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 14,
              background: `linear-gradient(135deg, ${accent.soft}, ${accent.softer})`,
              display: "flex", alignItems: "center", justifyContent: "center",
              border: `1px solid ${accent.ring}`,
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke={accent.primary} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9.5 2.5a3 3 0 0 0-3 3v.5a3 3 0 0 0-3 3v1a3 3 0 0 0 1 2.24V14a3 3 0 0 0 3 3v1a3 3 0 0 0 3 3h.5"/>
                <path d="M14.5 2.5a3 3 0 0 1 3 3v.5a3 3 0 0 1 3 3v1a3 3 0 0 1-1 2.24V14a3 3 0 0 1-3 3v1a3 3 0 0 1-3 3h-.5"/>
                <path d="M12 2.5v19"/>
              </svg>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{
                  background: "#dcfce7", color: "#15803d",
                  fontSize: 11, fontWeight: 700, letterSpacing: ".05em",
                  padding: "4px 12px", borderRadius: 99,
                }}>EXCELLENT</span>
                <span style={{ fontSize: 11, color: t.muted }}>Analyzed 2h ago · {channelLabel} channel</span>
              </div>
              <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 22, fontWeight: 400, color: t.text, marginTop: 6, fontStyle: "italic" }}>
                5 agents · 12 reports · seeded by 184k sends
              </div>
            </div>
            <button style={{
              background: "transparent", border: `1px solid ${t.border}`, color: t.text,
              padding: "8px 14px", borderRadius: 8, fontSize: 12.5, fontWeight: 500,
              cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6,
            }}>↻ Re-analyze</button>
          </div>

          {/* KPIs from this channel, AI summarized */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, paddingTop: 16, borderTop: `1px solid ${t.divider}` }}>
            {data.kpis.map((k, i) => (
              <div key={i} style={{ padding: "4px 0" }}>
                <div style={{ fontSize: 11, color: t.muted, marginBottom: 4 }}>{k.label}</div>
                <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(19px, 2.2vw, 30px)", color: t.text, fontWeight: 400, lineHeight: 1 }}>{k.value}</div>
                <div style={{ fontSize: 11, color: "#16a34a", fontWeight: 600, marginTop: 4 }}>↑ {k.delta}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Agents succeeded strip */}
        <div style={{
          background: t.surfaceMuted, border: `1px solid ${t.borderSoft}`, borderRadius: 10,
          padding: "10px 14px", display: "flex", alignItems: "center", gap: 14, fontSize: 12.5, color: t.muted,
        }}>
          <span style={{ width: 18, height: 18, borderRadius: 99, background: "#16a34a", display: "inline-flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 11 }}>✓</span>
          <span style={{ color: t.text, fontWeight: 600 }}>5/5 agents succeeded</span>
          <span style={{ color: t.micro }}>· 22s</span>
          <span style={{ marginLeft: "auto", color: t.micro }}>Avg confidence 84.4%</span>
        </div>

        {/* Agent Analysis Reports */}
        <Card t={t} title="Agent Analysis Reports" subtitle="5 agents · click any row to expand">
          {AGENT_REPORTS.map((r) => (
            <AgentRow key={r.id} report={r} t={t} expanded={expanded === r.id} onToggle={() => setExpanded(expanded === r.id ? null : r.id)} />
          ))}
        </Card>

        {/* Cross-Campaign Learnings */}
        <Card t={t} title="Cross-Campaign Learnings" subtitle="Based on 124 analyzed campaigns">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14 }}>
            {[
              { title: "Subject lines with first-name token", uplift: "+22.4%", metric: "open rate", note: "Across 38 campaigns · n=82,400" },
              { title: "Tuesday 10:00 local send window",     uplift: "+14.1%", metric: "engagement", note: "Strongest across all locales" },
              { title: "≤3 CTAs per email",                   uplift: "+8.7%",  metric: "click-through", note: "Falls off sharply past 4" },
            ].map((c, i) => (
              <div key={i} style={{ padding: 16, background: t.surfaceMuted, border: `1px solid ${t.borderSoft}`, borderRadius: 10 }}>
                <div style={{ fontSize: 13, color: t.text, fontWeight: 600, marginBottom: 8 }}>{c.title}</div>
                <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: 28, color: accent.primary, fontWeight: 400, lineHeight: 1, fontStyle: "italic" }}>{c.uplift}</div>
                <div style={{ fontSize: 11, color: t.muted, marginTop: 4 }}>{c.metric}</div>
                <div style={{ fontSize: 11, color: t.micro, marginTop: 10, paddingTop: 10, borderTop: `1px dashed ${t.divider}` }}>{c.note}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    );
  };

  window.ChannelPanel = ChannelPanel;
  window.AiInsightsPanel = AiInsightsPanel;

  // ============================================================
  // CAMPAIGN DETAIL PANEL, single campaign view
  // ============================================================
  const EMAIL_CAMPAIGN = {
    name: "Spring · 2-for-1 dinner · Members",
    status: "Sent",
    subject: "Two seats at Sàba, on us, this Sunday.",
    audience: "Loyalty Tier 2+ · ES, FR, IT",
    sentAt: "May 8, 2026 · 10:30 AM",
    recipients: 12480,
    kpis: [
      { label: "Open rate",       value: "52.1%",  delta: "8.4%",  spark: [42,44,43,46,47,49,48,50,51,52,52,52,52,52,52.1] },
      { label: "Click rate",      value: "18.6%",  delta: "4.2%",  spark: [10,11,12,12,13,14,14,15,16,17,17,18,18,18,18.6] },
      { label: "Bounce rate",     value: "0.4%",   delta: "0.2%",  deltaDir: "down", spark: [.8,.7,.7,.6,.6,.5,.5,.5,.5,.4,.4,.4,.4,.4,.4] },
      { label: "Conversion rate", value: "6.84%",  delta: "1.6%",  spark: [3.8,4.2,4.5,4.8,5.1,5.4,5.7,5.9,6.1,6.3,6.5,6.6,6.7,6.8,6.84] },
    ],
    timeline: [820,1240,1680,1920,2140,2080,1860,1620,1380,1180,980,840,720,640,580,520,480,440,420,400,380,360,340,320],
    funnel: [
      { label: "Delivered",  value: 12430 },
      { label: "Opened",     value: 6480 },
      { label: "Clicked",    value: 2320 },
      { label: "Booked",     value: 854 },
    ],
    links: [
      { label: "Reserve a table, primary CTA",  value: 1820 },
      { label: "View menu",                      value: 380 },
      { label: "Wine pairing add-on",            value: 92 },
      { label: "Unsubscribe",                    value: 28 },
    ],
  };

  const WA_CAMPAIGN = {
    name: "Check-in · Suite 412 · Müller",
    status: "Delivered",
    subject: "Hola Lukas, your check-in pack 🔑",
    audience: "Arrivals · May 10–14 · Mallorca",
    sentAt: "May 8, 2026 · 1:40 PM",
    recipients: 1840,
    kpis: [
      { label: "Delivery rate",   value: "99.8%",  delta: "0.4%",  spark: [99,99.2,99.3,99.4,99.5,99.6,99.6,99.7,99.7,99.8,99.8,99.8,99.8,99.8,99.8] },
      { label: "Read rate",       value: "94.2%",  delta: "6.8%",  spark: [82,84,85,87,88,89,90,91,92,93,93,94,94,94,94.2] },
      { label: "Reply rate",      value: "32.6%",  delta: "5.4%",  spark: [22,24,25,26,27,28,29,30,30,31,31,32,32,32,32.6] },
      { label: "Action rate",     value: "11.3%",  delta: "2.1%",  spark: [6,7,7,8,8,9,9,10,10,10,11,11,11,11,11.3] },
    ],
    timeline: [120,180,240,310,380,420,460,500,540,560,580,560,520,460,400,340,280,220,180,150,130,110,90,70],
    funnel: [
      { label: "Delivered",  value: 1836 },
      { label: "Read",       value: 1730 },
      { label: "Replied",    value: 599 },
      { label: "Action",     value: 208 },
    ],
    links: [
      { label: "Open digital key",       value: 412 },
      { label: "Add to Apple Wallet",    value: 188 },
      { label: "Concierge chat",         value: 96 },
      { label: "View hotel map",         value: 64 },
    ],
  };

  const CampaignDetailPanel = ({ channel, t }) => {
    const cd = channel === "email" ? EMAIL_CAMPAIGN : WA_CAMPAIGN;
    const accent = channel === "email" ? CHANNEL_ACCENTS.email : CHANNEL_ACCENTS.whatsapp;
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {/* HEADER */}
        <div style={{ background: t.surface, border: `1px solid ${t.border}`, borderRadius: 12, padding: "20px 22px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
            <button style={{ background: "transparent", border: `1px solid ${t.border}`, color: t.muted, padding: "4px 8px", borderRadius: 6, fontSize: 12, cursor: "pointer" }}>← Campaigns</button>
            <span style={{ fontSize: 11, padding: "3px 9px", borderRadius: 99, background: "#dcfce7", color: "#15803d", fontWeight: 700, letterSpacing: ".05em" }}>{cd.status.toUpperCase()}</span>
            <span style={{ fontSize: 11, padding: "3px 9px", borderRadius: 99, background: accent.soft, color: accent.primaryDeep, fontWeight: 700, letterSpacing: ".05em" }}>{channel === "email" ? "EMAIL" : "WHATSAPP"}</span>
          </div>
          <div style={{ fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(20px, 2.6vw, 36px)", fontWeight: 400, color: t.text, lineHeight: 1.05, letterSpacing: "-0.01em" }}>{cd.name}</div>
          <div style={{ display: "flex", gap: 24, marginTop: 12, flexWrap: "wrap", fontSize: 12.5, color: t.muted }}>
            <div><span style={{ color: t.micro }}>Subject · </span><span style={{ color: t.text }}>{cd.subject}</span></div>
            <div><span style={{ color: t.micro }}>Audience · </span><span style={{ color: t.text }}>{cd.audience}</span></div>
            <div><span style={{ color: t.micro }}>Sent · </span><span style={{ color: t.text }}>{cd.sentAt}</span></div>
            <div><span style={{ color: t.micro }}>Recipients · </span><span style={{ color: t.text, fontVariantNumeric: "tabular-nums" }}>{cd.recipients.toLocaleString()}</span></div>
          </div>
        </div>

        {/* KPIs */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          {cd.kpis.map((k, i) => (
            <KpiCard key={i} {...k} sparkData={k.spark} t={t} accent={accent} subtle="vs benchmark" />
          ))}
        </div>

        {/* Timeline + Funnel */}
        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 14 }}>
          <Card t={t} title={channel === "email" ? "Opens over time" : "Reads over time"} subtitle="First 24h since send · hourly buckets">
            <AreaChart data={cd.timeline} labels={Array.from({length:24}, (_,i)=>String(i)+"h")} color={accent.primary} t={t} height={210} />
          </Card>
          <Card t={t} title="Engagement funnel" subtitle="From delivery to conversion">
            <Funnel steps={cd.funnel} color={accent.primary} t={t} />
          </Card>
        </div>

        {/* Links + Recipients */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Card t={t} title={channel === "email" ? "Link clicks" : "CTA actions"} subtitle="Top 4 destinations">
            <ProgressList items={cd.links} t={t} accent={accent} />
          </Card>
          <Card t={t} title="Recent recipients" subtitle="Live activity">
            <RecentList items={(channel === "email" ? EMAIL_DATA : WHATSAPP_DATA).recent} t={t} />
          </Card>
        </div>
      </div>
    );
  };

  window.CampaignDetailPanel = CampaignDetailPanel;

  /* ===== analytics.jsx ===== */

  // Campaign analytics section, section header + dashboard frame.
  // Tabs: Email · WhatsApp · AI Insights. Light/dark via Tweaks.

  const { useState: useAnalyticsState, useEffect: useAnalyticsEffect } = React;

  // --- Channel tab icons ---
  const EmailGlyph = ({ size = 14, color }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/>
    </svg>
  );
  const WhatsappGlyph = ({ size = 14, color }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 11.5a8.5 8.5 0 0 1-12.83 7.34L3 21l2.16-5.15A8.5 8.5 0 1 1 21 11.5z"/>
    </svg>
  );
  const AiGlyph = ({ size = 14, color }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 2l2.4 5 5.6.8-4 3.9.9 5.6L12 14.8 7.1 17.3l.9-5.6-4-3.9 5.6-.8z"/>
    </svg>
  );
  const SunGlyph = ({ size = 14, color }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
    </svg>
  );
  const MoonGlyph = ({ size = 14, color }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
    </svg>
  );

  const ANALYTICS_TABS = [
    { id: "email",    label: "Email",       icon: EmailGlyph,    accentKey: "email" },
    { id: "whatsapp", label: "WhatsApp",    icon: WhatsappGlyph, accentKey: "whatsapp" },
    { id: "ai",       label: "AI Insights", icon: AiGlyph,       accentKey: "ai" },
  ];

  const RANGES = ["7d", "30d", "90d", "YTD"];

  const SUBTABS = {
    email:    [{ id: "all", label: "All campaigns" }, { id: "one", label: "Single campaign" }],
    whatsapp: [{ id: "all", label: "All campaigns" }, { id: "one", label: "Single campaign" }],
    ai:       [{ id: "email", label: "Email" },      { id: "whatsapp", label: "WhatsApp" }],
  };

  const AnalyticsDashboard = ({ theme = "light" }) => {
    const [tab, setTab] = useAnalyticsState("email");
    const [sub, setSub] = useAnalyticsState({ email: "all", whatsapp: "all", ai: "email" });
    const [range, setRange] = useAnalyticsState("30d");
    const t = ANALYTICS_THEMES[theme];
    const accent = CHANNEL_ACCENTS[ANALYTICS_TABS.find(x => x.id === tab).accentKey];
    const setSubFor = (key, val) => setSub(s => ({ ...s, [key]: val }));

    // Subtle fade when tab changes
    const [tick, setTick] = useAnalyticsState(0);
    useAnalyticsEffect(() => { setTick(x => x + 1); }, [tab, sub]);

    return (
      <div style={{
        background: t.surface, color: t.text,
        borderRadius: 16, overflow: "hidden",
        border: `1px solid ${t.border}`,
        boxShadow: t.frameShadow,
        transition: "background .25s, color .25s, border-color .25s",
      }}>
        {/* TAB BAR */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "14px 18px", borderBottom: `1px solid ${t.divider}`,
          background: theme === "dark" ? t.surfaceMuted : "#fcfcfd",
          gap: 16, flexWrap: "wrap",
        }}>
          {/* Channel tabs */}
          <div style={{ display: "flex", alignItems: "center", gap: 4, padding: 4, background: t.chip, borderRadius: 10 }}>
            {ANALYTICS_TABS.map((tt) => {
              const active = tab === tt.id;
              const ttAccent = CHANNEL_ACCENTS[tt.accentKey];
              const Icon = tt.icon;
              return (
                <button key={tt.id} onClick={() => setTab(tt.id)} style={{
                  background: active ? t.surface : "transparent",
                  border: "none",
                  color: active ? ttAccent.primary : t.muted,
                  padding: "8px 14px", borderRadius: 7,
                  fontSize: 13, fontWeight: 600, cursor: "pointer",
                  display: "inline-flex", alignItems: "center", gap: 8,
                  boxShadow: active ? `0 1px 2px ${t.glow}` : "none",
                  transition: "color .15s, background .15s",
                }}>
                  <Icon size={13} color={active ? ttAccent.primary : t.muted} />
                  {tt.label}
                </button>
              );
            })}
          </div>

          {/* Range + meta */}
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 4, padding: 3, background: t.chip, borderRadius: 8 }}>
              {RANGES.map((r) => {
                const active = range === r;
                return (
                  <button key={r} onClick={() => setRange(r)} style={{
                    background: active ? accent.primary : "transparent",
                    color: active ? "#fff" : t.muted,
                    border: "none", padding: "6px 12px", borderRadius: 5,
                    fontSize: 11.5, fontWeight: 600, cursor: "pointer",
                    fontVariantNumeric: "tabular-nums",
                  }}>{r}</button>
                );
              })}
            </div>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: t.muted }}>
              <span style={{ width: 7, height: 7, borderRadius: 99, background: "#22c55e", boxShadow: "0 0 0 4px rgba(34,197,94,.15)" }} />
              Live
            </div>
          </div>
        </div>

        {/* SUB-TAB STRIP */}
        <div style={{
          display: "flex", alignItems: "center", gap: 4,
          padding: "10px 18px", borderBottom: `1px solid ${t.divider}`,
          background: theme === "dark" ? t.surfaceMuted : "#fff",
        }}>
          {SUBTABS[tab].map(st => {
            const active = sub[tab] === st.id;
            return (
              <button key={st.id} onClick={() => setSubFor(tab, st.id)} style={{
                background: "transparent", border: "none",
                color: active ? accent.primary : t.muted,
                padding: "6px 12px", borderRadius: 6,
                fontSize: 12.5, fontWeight: 600, cursor: "pointer",
                borderBottom: active ? `2px solid ${accent.primary}` : "2px solid transparent",
                marginBottom: -11, paddingBottom: 10,
              }}>{st.label}</button>
            );
          })}
        </div>

        {/* CONTENT */}
        <div key={tick} style={{ padding: 18, background: theme === "dark" ? t.surfaceMuted : "#fafbfc", animation: "fadeIn .3s ease" }}>
          {tab === "email"    && sub.email === "all"     && <ChannelPanel channel="email"    t={t} />}
          {tab === "email"    && sub.email === "one"     && <CampaignDetailPanel channel="email"    t={t} />}
          {tab === "whatsapp" && sub.whatsapp === "all"  && <ChannelPanel channel="whatsapp" t={t} />}
          {tab === "whatsapp" && sub.whatsapp === "one"  && <CampaignDetailPanel channel="whatsapp" t={t} />}
          {tab === "ai"       && <AiInsightsPanel t={t} channel={sub.ai} />}
        </div>

        {/* FOOTER */}
        <div style={{
          padding: "12px 20px", borderTop: `1px solid ${t.divider}`,
          display: "flex", alignItems: "center", justifyContent: "space-between",
          fontSize: 11.5, color: t.muted, background: theme === "dark" ? t.surfaceMuted : "#fcfcfd",
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: 99, background: accent.primary }} /> snapshot · {range}
            </span>
            <span>sync · 4s ago</span>
            <span>184,290 sends · 14 properties</span>
          </div>
          <div style={{ display: "flex", gap: 14 }}>
            <a href="#" style={{ color: t.muted, textDecoration: "none" }}>Export</a>
            <a href="#" style={{ color: t.muted, textDecoration: "none" }}>CSV</a>
            <a href="#" style={{ color: t.muted, textDecoration: "none" }}>PDF</a>
            <a href="#" style={{ color: t.muted, textDecoration: "none" }}>Schedule report</a>
          </div>
        </div>
      </div>
    );
  };

  // ============================================================
  // SECTION (with header + theme toggle)
  // ============================================================
  const ANALYTICS_DEFAULTS = /*EDITMODE-BEGIN-ANALYTICS*/{
    "analyticsTheme": "dark"
  }/*EDITMODE-END-ANALYTICS*/;

  const AnalyticsSection = () => {
    const [theme, setTheme] = useAnalyticsState(ANALYTICS_DEFAULTS.analyticsTheme === "dark" ? "dark" : "light");
    const isDark = theme === "dark";
    const sectionBg = isDark
      ? "#0a0c10"
      : "linear-gradient(180deg, #fef9f4 0%, #fdf2f8 100%)";
    const headlineColor = isDark ? "#f1f5f9" : "#0f172a";
    const accentColor = "#ED4D86";
    const subColor = isDark ? "#94a3b8" : "#475569";

    return (
      <section style={{
        background: sectionBg, padding: "100px 24px 100px",
        transition: "background .25s",
      }} data-screen-label="Campaign Analytics">
        <div style={{ maxWidth: 1480, margin: "0 auto" }}>
          {/* Eyebrow */}
          <div style={{ textAlign: "center", marginBottom: 18 }}>
            <span style={{
              fontSize: 12.5, fontWeight: 600, letterSpacing: ".24em",
              color: accentColor, display: "inline-flex", alignItems: "center", gap: 10,
            }}>
              <span style={{ width: 28, height: 1.5, background: accentColor }} /> CAMPAIGN ANALYTICS <span style={{ width: 28, height: 1.5, background: accentColor }} />
            </span>
          </div>
          {/* Headline */}
          <h2 style={{
            fontFamily: '"Instrument Serif", "Cormorant Garamond", Georgia, serif', fontSize: "clamp(30px, 5.4vw, 76px)", lineHeight: 1.0, fontWeight: 400,
            margin: "0 0 8px", textAlign: "center", color: headlineColor, letterSpacing: "-0.01em",
          }}>
            Every send, <span style={{ fontStyle: "italic", color: accentColor }}>measured, attributed, lifted.</span>
          </h2>
          <p style={{
            maxWidth: 660, margin: "20px auto 0", textAlign: "center",
            fontSize: 16.5, lineHeight: 1.55, color: subColor,
          }}>
            Volume, deliverability, attribution and reply intent across every email and WhatsApp campaign, with AI agents flagging anomalies, attributing revenue and synthesising A/B tests in the background.
          </p>

          {/* Dashboard */}
          <div style={{ marginTop: 36 }}>
            <ScaleFrame nativeWidth={1100}>
              <AnalyticsDashboard theme={theme} />
            </ScaleFrame>
          </div>

          <div style={{ textAlign: "center", marginTop: 24, fontSize: 13, color: isDark ? "#64748b" : "#94a3b8" }}>
            Click any tab to switch channel · agent rows expand for full report
          </div>
        </div>
      </section>
    );
  };

  window.AnalyticsSection = AnalyticsSection;

  /* ===== app.jsx ===== */

  // Main app, wires hero + wizard + builder

  // The headline was a hardcoded fontSize:88 that never shrank, so on a phone
  // it burned ~2 screens before any content. Every other platform page shares
  // styles.css's .h-display/.eyebrow/.lead/.btn, which already carry the
  // responsive clamp() and a wrapping CTA row — rebuilt on those so this hero
  // scales like the rest of the site.
  const Hero = () => (
    <section style={{
      background: "linear-gradient(180deg, #fdf6f0 0%, #ffe5ed 60%, #fef9f4 100%)",
      padding: "56px 24px", textAlign: "center", position: "relative", overflow: "hidden",
    }}>
      <div className="container">
        {/* Breadcrumb */}
        <div style={{ fontSize: 14, color: "#64748b", marginBottom: 18 }}>
          Home <span style={{ margin: "0 8px", color: "#cbd5e1" }}>/</span>
          Platform <span style={{ margin: "0 8px", color: "#cbd5e1" }}>/</span>
          <span style={{ color: "#ED4D86" }}>Journeys &amp; Campaigns</span>
        </div>
        {/* Eyebrow */}
        <div className="eyebrow" style={{ justifyContent: "center", color: "#ED4D86" }}>
          Journeys &amp; Campaigns
        </div>
        {/* Headline */}
        <h1 className="h-display" style={{ marginTop: 22 }}>
          Every guest, a story.<br />
          <span className="italic-accent">Every story, a journey.</span>
        </h1>
        {/* Subhead */}
        <p className="lead" style={{ maxWidth: 640, margin: "24px auto 0" }}>
          Omnichannel journeys built for hospitality. WhatsApp, email and SMS orchestrated with hotel-native triggers, AI concierge handoffs and conditional logic that knows the difference between a check-in and a no-show.
        </p>
        {/* CTAs */}
        <div className="flex gap-3 wrap center" style={{ marginTop: 32 }}>
          <a href={DEMO_URL} className="btn btn-primary">Book a demo <span className="arrow">→</span></a>
          <button className="btn btn-ghost" style={{ background: "transparent", cursor: "pointer" }}>Explore the engine</button>
        </div>
        {/* Pill chip */}
        <div style={{ marginTop: 40, display: "inline-flex", alignItems: "center", gap: 10, background: "#fff", border: "1px solid #ffe5ed", borderRadius: 99, padding: "8px 18px", fontSize: 13.5, color: "#0f172a", fontWeight: 500, boxShadow: "0 4px 16px rgba(237,77,134,.10)", maxWidth: "100%", boxSizing: "border-box", flexWrap: "wrap", justifyContent: "center" }}>
          <span style={{ color: "#ED4D86", fontSize: 16, flexShrink: 0 }}>+</span>
          <span>Win-back · 365 days after booking · live in canvas below</span>
        </div>
      </div>
    </section>
  );

  const App = () => {
    // 1=setup, 2=template, 3=trigger, 4=builder
    const [step, setStep] = useState(4); // jump straight to builder for the showcase
    const data = JOURNEY_DATA;

    const goBackToList = () => setStep(1);

    if (step === 4) {
      return (
        <div style={{ background: "#fafafa" }}>
          <Hero />
          {/* Artifact frame — the real Builder at its native 1480px, shrunk to
              fit via <ScaleFrame> exactly like every other artifact on this
              page. A phone therefore sees the SAME canvas a desktop does, just
              smaller: same palette, same nodes, same branch edges. */}
          <div style={{ padding: "0 24px 80px", background: "#fef9f4" }}>
            <ScaleFrame nativeWidth={1480} style={{ maxWidth: 1480, margin: "0 auto" }}>
              <div style={{
                height: 960, background: "#fff",
                borderRadius: 18, overflow: "hidden",
                boxShadow: "0 30px 80px -20px rgba(15,23,42,.25), 0 8px 24px rgba(15,23,42,.08)",
                border: "1px solid rgba(15,23,42,.06)",
              }}>
                <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
                  <Builder data={data} onBack={goBackToList} />
                </div>
              </div>
            </ScaleFrame>
            <div style={{ textAlign: "center", marginTop: 24, fontSize: 13, color: "#94a3b8" }}>
              Click any node to configure. Every step is interactive.
            </div>
          </div>
          <TriggersSection />
          <LibrarySection />
          <EmailSection />
          {typeof WhatsAppSection !== "undefined" && <WhatsAppSection />}
          {typeof AnalyticsSection !== "undefined" && <AnalyticsSection />}
        </div>
      );
    }

    // Wizard layout (steps 1-3)
    return (
      <div style={{ display: "flex", height: "100vh", background: "#fff", fontFamily: "inherit" }}>
        <Sidebar />
        <main style={{ flex: 1, overflow: "auto", display: "flex", flexDirection: "column" }}>
          <div style={{ height: 48, borderBottom: "1px solid #ececec", display: "flex", alignItems: "center", padding: "0 20px", background: "#fff" }}>
            <button onClick={goBackToList} style={{ background: "transparent", border: "none", padding: 4, cursor: "pointer", color: "#0f172a", display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, fontFamily: "inherit" }}>
              <Icon name="back" size={14}/> Back to Journeys
            </button>
            <div style={{ width: 1, height: 18, background: "#e2e8f0", margin: "0 12px" }} />
            <div style={{ fontSize: 14, fontWeight: 600, color: "#0f172a" }}>Create New Journey</div>
          </div>
          <WizardStepper active={step} onNavigate={setStep} />
          {step === 1 && <SetupStep onNext={setStep} />}
          {step === 2 && <TemplateStep onNext={setStep} />}
          {step === 3 && <TriggerStep onNext={setStep} />}
        </main>
      </div>
    );
  };

  /* expose */
  window.JourneysHero = App;
})();
