/* global React, UmIcon, PMDS_SERVICES, PMDS_AI_IMPLEMENTATION, PMDS_AI_PACK */
const { useState: useOf, useEffect: useEffOf, useMemo: useMemoOf, useRef: useRefOf } = React;

/* ============================================================
   ORDER FLOW — Higgsfield-style sales funnel
   Hero → Questionnaire → Dynamic Offer (+ AI Pack/Impl) → Payment → Success
   ============================================================ */

/* ---------- Persistence ---------- */
const STORAGE_KEY = "um_order_state_v2";
function loadState() {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}"); }
  catch (e) { return {}; }
}
function saveState(s) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch (e) {}
}

/* ---------- URL helpers ---------- */
function getUrlParam(name) {
  if (typeof window === "undefined") return null;
  const p = new URLSearchParams(window.location.search);
  return p.get(name);
}

/* ---------- Question bank ---------- */
// Returns array of step objects: { id, kind, title, sub?, options?, optional? }
function buildQuestions(prefilledService) {
  return [
    /* ============ SMART SALES DIAGNOSIS LAYER ============ */
    {
      id: "diag_intro",
      kind: "intro",
      title: "Let's diagnose first, then design the solution.",
      sub: "Most studios show you services. I'd rather understand the friction in your business first — then recommend what actually moves the needle.",
      icon: "◇",
    },
    {
      id: "business_type",
      kind: "single",
      title: "What best describes your business?",
      sub: "I'll calibrate the questions and the recommendation to your industry.",
      layout: "grid",
      options: [
        { v: "real-estate",     ico: "◉", title: "Real estate" },
        { v: "manufacturing",   ico: "◉", title: "Manufacturing" },
        { v: "logistics",       ico: "◉", title: "Logistics" },
        { v: "healthcare",      ico: "◉", title: "Healthcare" },
        { v: "ecommerce",       ico: "◉", title: "E-commerce" },
        { v: "construction",    ico: "◉", title: "Construction" },
        { v: "restaurant",      ico: "◉", title: "Restaurant / Hospitality" },
        { v: "professional",    ico: "◉", title: "Professional services" },
        { v: "other",           ico: "◉", title: "Other" },
      ],
    },
    {
      id: "goal",
      kind: "single",
      title: "What outcome are you chasing?",
      sub: "I'll tailor the package to match — content velocity, brand depth, or product surfaces.",
      layout: "2x2 big",
      options: [
        { v: "leads",     ico: "📈", title: "Generate leads + sales",     sub: "Marketing creatives, landing pages, ad campaigns." },
        { v: "brand",     ico: "✦",  title: "Build a complete brand",       sub: "Logo, identity, guidelines, application kit." },
        { v: "content",   ico: "▶",  title: "Ship content consistently",    sub: "Recurring static, motion, and video at scale." },
        { v: "product",   ico: "□",  title: "Design a product or website",  sub: "UI/UX, web, or app from wireframe to live." },
      ],
    },
    {
      id: "pain",
      kind: "multi",
      title: "What's slowing your business down right now?",
      sub: "Pick everything that costs you sleep. I'll map them to the right fix.",
      layout: "chips",
      options: [
        { v: "losing-leads",       title: "Losing leads",                sub: "Coming in, never closing." },
        { v: "poor-online",        title: "Weak online presence",        sub: "Site or socials feel outdated." },
        { v: "manual-workflows",   title: "Manual workflows",            sub: "Repetitive work eating hours." },
        { v: "slow-support",       title: "Slow customer support",       sub: "Response time hurts retention." },
        { v: "inconsistent-brand", title: "Inconsistent branding",       sub: "Looks different everywhere." },
        { v: "no-automation",      title: "No automation",               sub: "Everything is hands-on." },
        { v: "poor-followup",      title: "Poor lead follow-up",         sub: "Leads slip through the cracks." },
        { v: "low-conversion",     title: "Low sales conversion",        sub: "Traffic, no sales." },
        { v: "staff-comms",        title: "Staff communication",         sub: "Info siloed across tools." },
        { v: "social-inconsist",   title: "Social media inconsistency",  sub: "Posting irregularly." },
      ],
    },
    {
      id: "impact",
      kind: "single",
      title: "How much do you think this is costing you monthly?",
      sub: "Time, lost revenue, productivity — anything quantifiable.",
      layout: "rows",
      options: [
        { v: "<1k",    ico: "○",  title: "Under $1,000 / month",          sub: "Annoying, but tolerable." },
        { v: "1-5k",   ico: "◔",  title: "$1k – $5k / month",              sub: "Meaningful — would notice if fixed." },
        { v: "5-20k",  ico: "◑",  title: "$5k – $20k / month",             sub: "Hurts. Active priority." },
        { v: "20k+",   ico: "●",  title: "$20k+ / month",                  sub: "Bleeding. Fix yesterday." },
        { v: "unsure", ico: "?",  title: "Honestly, I'm not sure",         sub: "I'll help you size it on the call." },
      ],
    },
    {
      id: "ai_readiness",
      kind: "single",
      title: "Have you used AI or automation tools before?",
      sub: "No wrong answer — this just shapes how we onboard.",
      layout: "rows",
      options: [
        { v: "beginner",     ico: "①", title: "Beginner",     sub: "Heard of ChatGPT, haven't really used it." },
        { v: "intermediate", ico: "②", title: "Intermediate", sub: "Use AI casually for writing or research." },
        { v: "advanced",     ico: "③", title: "Advanced",     sub: "Already built workflows, looking to scale." },
      ],
    },
    /* ============ EXISTING QUESTIONS ============ */
    {
      id: "services",
      kind: "multi",
      title: "Which services do you need?",
      sub: "Pick all that apply — I'll bundle them into one offer. Or skip and let the diagnosis recommend.",
      layout: "chips",
      options: [
        ...PMDS_SERVICES.map(s => ({ v: s.id, title: s.title, sub: s.short })),
        { v: "ai-pack", title: "AI Automation Pack", sub: "Self-serve automation stack — Claude Code, Telegram bot, Google Sheets integration." }
      ],
    },
    {
      id: "tier",
      kind: "single-dynamic-tier",
      title: "Which plan fits the scope?",
      sub: "Each service has 2–3 plans. Pick a tier for every selected service.",
    },
    {
      id: "timeline",
      kind: "single",
      title: "When do you need to start?",
      sub: "This shapes the pricing — rush vs scheduled.",
      layout: "rows",
      options: [
        { v: "asap",     ico: "⚡", title: "ASAP — within this week",       sub: "Rush queue. Priority TAT applies." },
        { v: "2weeks",   ico: "◑", title: "Within 2 weeks",                sub: "Standard onboarding window." },
        { v: "month",    ico: "◯", title: "Within a month",                sub: "Best window for premium scopes." },
        { v: "flexible", ico: "∞", title: "Flexible — not in a rush",      sub: "I'll find the right slot." },
      ],
    },
    {
      id: "size",
      kind: "single",
      title: "What stage is your business at?",
      layout: "2x2",
      options: [
        { v: "solo",      ico: "①", title: "Solo / Side project",     sub: "1 person, getting started." },
        { v: "startup",   ico: "②", title: "Early-stage startup",     sub: "Pre-seed to Series A." },
        { v: "smb",       ico: "③", title: "Established SMB",         sub: "10+ team, generating revenue." },
        { v: "enterprise",ico: "④", title: "Enterprise",              sub: "100+ team, brand standards in place." },
      ],
    },
    {
      id: "discovery",
      kind: "single",
      title: "How did you hear about us?",
      sub: "Helps me understand what's resonating.",
      layout: "grid",
      options: [
        { v: "instagram",  ico: "◌", title: "Instagram" },
        { v: "linkedin",   ico: "◌", title: "LinkedIn" },
        { v: "google",     ico: "◌", title: "Google Search" },
        { v: "referral",   ico: "◌", title: "Referral / Word of mouth" },
        { v: "youtube",    ico: "◌", title: "YouTube" },
        { v: "outreach",   ico: "◌", title: "Direct outreach from Uche" },
        { v: "other",      ico: "◌", title: "Other" },
      ],
    },
    {
      id: "contact",
      kind: "contact",
      title: "Last step — who's this for?",
      sub: "I'll send a confirmation and walk you through the next step.",
    },
  ];
}

/* ---------- COUNTDOWN ---------- */
function useCountdown(deadline) {
  const [now, setNow] = useOf(() => Date.now());
  useEffOf(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const ms = Math.max(0, deadline - now);
  const total = Math.floor(ms / 1000);
  return {
    hours:   String(Math.floor(total / 3600)).padStart(2, "0"),
    minutes: String(Math.floor((total % 3600) / 60)).padStart(2, "0"),
    seconds: String(total % 60).padStart(2, "0"),
    expired: ms === 0,
  };
}

/* ---------- HERO ---------- */
function OrderHero({ onStart }) {
  const R2 = (typeof window !== "undefined" && window.UM_ROOT) || "../../";
  return (
    <section className="of-hero">
      <div className="of-hero-copy">
        <span className="of-hero-eyebrow">
          <span className="dot"></span> Personalized offer · 5 min flow
        </span>
        <h1 className="of-hero-title">
          Build your<br/>
          <span className="grad">creative</span><br/>
          <span className="accent">package.</span>
        </h1>
        <p className="of-hero-sub">
          Answer a few questions and I'll tailor a creative bundle, dial in your discount,
          and confirm next steps. No spam, no sales calls — just a clean offer.
        </p>
        <div className="of-hero-ctas">
          <button className="um-btn-primary" onClick={onStart}>
            Start the flow <UmIcon name="ico-arrow-right" size={14}/>
          </button>
          <a className="um-btn-ghost" href={`${R2}pages/book-appointment.html`}>
            Book a call instead
          </a>
        </div>
        <div className="of-hero-meta">
          <div>
            <div className="num">5+</div>
            <div className="lbl">Years experience</div>
          </div>
          <div>
            <div className="num">300+</div>
            <div className="lbl">Projects shipped</div>
          </div>
          <div>
            <div className="num">30+</div>
            <div className="lbl">Brands worldwide</div>
          </div>
        </div>
      </div>

      <div className="of-hero-visual">
        <div className="of-hero-orbit">
          <div className="of-hero-ring"></div>
          <div className="of-hero-ring"></div>
          <div className="of-hero-ring"></div>
          <div className="of-hero-core">
            <img src={`${R2}assets/logos/transparent/iconmark-whiteblue.png`} alt="UM"/>
          </div>
        </div>
        <div className="of-hero-pill p1"><span className="dot"></span>Static Graphics</div>
        <div className="of-hero-pill p2"><span className="dot"></span>Motion Reel</div>
        <div className="of-hero-pill p3"><span className="dot"></span>Brand Identity</div>
        <div className="of-hero-pill p4"><span className="dot"></span>UI / UX</div>
        <div className="of-hero-pill p5"><span className="dot"></span>AI Automation</div>
      </div>
    </section>
  );
}

/* ---------- OPTION CARD ---------- */
function Opt({ option, selected, multi, onPick, big }) {
  return (
    <button
      className={"of-opt " + (big ? "of-opt-big " : "") + (selected ? "selected" : "")}
      onClick={() => onPick(option.v)}
      type="button"
    >
      {option.ico && <span className="of-opt-ico">{option.ico}</span>}
      <span className="of-opt-title">{option.title}</span>
      {option.sub && <span className="of-opt-sub">{option.sub}</span>}
      <span className="of-opt-radio" style={multi ? { borderRadius: 6 } : null}></span>
    </button>
  );
}

/* ---------- QUESTION STEP ---------- */
function QuestionStep({ q, stepIdx, totalSteps, answers, onAnswer, onNext, onBack }) {
  const current = answers[q.id];

  // build options layout class
  const layoutCls = ({
    "2x2":     "of-options-grid-2x2",
    "2x2 big": "of-options-grid-2x2",
    "rows":    "of-options-rows-1",
    "grid":    "of-options-3",
  })[q.layout] || "of-options-rows-2";
  const useBig = q.layout === "2x2 big";

  const canContinue = useMemoOf(() => {
    if (q.kind === "intro")   return true;
    if (q.kind === "single")  return !!current;
    if (q.kind === "multi")   return Array.isArray(current) && current.length > 0;
    if (q.kind === "contact") return current && current.name && current.email;
    if (q.kind === "single-dynamic-tier") {
      const services = answers.services || [];
      const tiers = current || {};
      return services.every(sid => tiers[sid]);
    }
    return true;
  }, [q, current, answers]);

  // INTRO step — just a hero with a CTA
  if (q.kind === "intro") {
    return (
      <section className="of-question of-intro-step">
        <div className="of-question-inner of-intro-inner">
          <div className="of-intro-glyph">{q.icon}</div>
          <div className="of-q-counter">Smart Diagnosis · 5 quick questions</div>
          <h2 className="of-q-title of-intro-title">{q.title}</h2>
          <p className="of-q-sub of-intro-sub">{q.sub}</p>
          <div className="of-cta-bar" style={{justifyContent: "center"}}>
            <button className="of-back" onClick={onBack}>← Back</button>
            <button className="um-btn-primary" onClick={onNext}>
              Begin diagnosis <UmIcon name="ico-arrow-right" size={14}/>
            </button>
          </div>
        </div>
      </section>
    );
  }

  // Dynamic-tier picker: one tier selector per selected service
  if (q.kind === "single-dynamic-tier") {
    const services = (answers.services || []).map(sid => PMDS_SERVICES.find(s => s.id === sid)).filter(Boolean);
    const tierSelections = current || {};
    return (
      <section className="of-question">
        <div className="of-question-inner">
          <div className="of-q-head">
            <div className="of-q-counter">Step <span className="accent">{stepIdx + 1}</span> / {totalSteps}</div>
            <h2 className="of-q-title">{q.title}</h2>
            <p className="of-q-sub">{q.sub}</p>
          </div>

          {services.length === 0 && (
            <div style={{color:"var(--muted-grey)"}}>Please go back and select at least one service.</div>
          )}

          {services.map(s => (
            <div key={s.id} style={{marginTop: 8}}>
              <div style={{fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase",
                           color: "var(--muted-grey)", fontWeight: 700, marginBottom: 14}}>
                {s.title}
              </div>
              <div className="of-options of-options-3" style={{gridTemplateColumns:
                `repeat(${Math.min(3, s.tiers?.length || 1)}, 1fr)`}}>
                {(s.tiers || []).map(t => {
                  const sel = tierSelections[s.id] === t.id;
                  return (
                    <button
                      key={t.id}
                      type="button"
                      className={"of-opt of-opt-big " + (sel ? "selected" : "")}
                      onClick={() => onAnswer(q.id, { ...tierSelections, [s.id]: t.id })}
                    >
                      <span className="of-opt-title">
                        {t.nm}{" "}
                        {t.featured && (
                          <span style={{fontSize:9, marginLeft:6, color:"var(--accent)", letterSpacing:"0.18em"}}>POPULAR</span>
                        )}
                      </span>
                      <span className="of-opt-sub">{t.unitNote || `${t.list[0]}`}</span>
                      <span style={{
                        fontFamily:"var(--font-display)", fontWeight:700, fontSize:32,
                        color: sel ? "var(--accent)" : "var(--fg)", letterSpacing:"-0.02em",
                        marginTop:8,
                      }}>
                        ${t.price.toLocaleString()}<span style={{fontSize:12, color:"var(--muted-grey)", marginLeft:6}}>{t.suffix}</span>
                      </span>
                      <span className="of-opt-radio"></span>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}

          <div className="of-cta-bar">
            <button className="of-back" onClick={onBack}>← Back</button>
            <button
              className="um-btn-primary"
              disabled={!canContinue}
              style={{opacity: canContinue ? 1 : 0.4, cursor: canContinue ? "pointer" : "not-allowed"}}
              onClick={onNext}
            >
              Continue <UmIcon name="ico-arrow-right" size={14}/>
            </button>
            <span className="hint">Press Enter ↵ to continue</span>
          </div>
        </div>
      </section>
    );
  }

  // Contact step
  if (q.kind === "contact") {
    const c = current || {};
    const update = (k, v) => onAnswer(q.id, { ...c, [k]: v });
    return (
      <section className="of-question">
        <div className="of-question-inner">
          <div className="of-q-head">
            <div className="of-q-counter">Step <span className="accent">{stepIdx + 1}</span> / {totalSteps}</div>
            <h2 className="of-q-title">{q.title}</h2>
            <p className="of-q-sub">{q.sub}</p>
          </div>
          <div style={{maxWidth: 720, display:"grid", gap: 16}}>
            <div className="of-field">
              <label>Full name</label>
              <input value={c.name || ""} onChange={e => update("name", e.target.value)} placeholder="Your name"/>
            </div>
            <div className="of-field">
              <label>Email</label>
              <input type="email" value={c.email || ""} onChange={e => update("email", e.target.value)} placeholder="you@brand.com"/>
            </div>
            <div className="of-field">
              <label>Company (optional)</label>
              <input value={c.company || ""} onChange={e => update("company", e.target.value)} placeholder="Brand or studio"/>
            </div>
            <div className="of-field">
              <label>Anything else I should know?</label>
              <textarea value={c.notes || ""} onChange={e => update("notes", e.target.value)} placeholder="Project details, deadlines, brand links..."/>
            </div>
          </div>
          <div className="of-cta-bar">
            <button className="of-back" onClick={onBack}>← Back</button>
            <button
              className="um-btn-primary"
              disabled={!canContinue}
              style={{opacity: canContinue ? 1 : 0.4, cursor: canContinue ? "pointer" : "not-allowed"}}
              onClick={onNext}
            >
              See my offer <UmIcon name="ico-arrow-right" size={14}/>
            </button>
          </div>
        </div>
      </section>
    );
  }

  // Standard single / multi
  const pick = (v) => {
    if (q.kind === "multi") {
      const cur = Array.isArray(current) ? current : [];
      onAnswer(q.id, cur.includes(v) ? cur.filter(x => x !== v) : [...cur, v]);
    } else {
      onAnswer(q.id, v);
    }
  };

  const isChipsLayout = q.layout === "chips";
  return (
    <section className="of-question">
      <div className="of-question-inner">
        <div className="of-q-head">
          <div className="of-q-counter">Step <span className="accent">{stepIdx + 1}</span> / {totalSteps}</div>
          <h2 className="of-q-title">{q.title}</h2>
          {q.sub && <p className="of-q-sub">{q.sub}</p>}
        </div>

        {isChipsLayout ? (
          <div className="of-chip-grid">
            {q.options.map(o => {
              const sel = Array.isArray(current) ? current.includes(o.v) : current === o.v;
              return (
                <button key={o.v} type="button"
                        className={"of-chip " + (sel ? "selected" : "")}
                        onClick={() => pick(o.v)}>
                  <span className="of-chip-check"></span>
                  <span className="nm">{o.title}</span>
                  {o.sub && <span className="sub">{o.sub}</span>}
                </button>
              );
            })}
          </div>
        ) : (
          <div className={"of-options " + layoutCls}>
            {q.options.map(o => (
              <Opt key={o.v}
                   option={o}
                   selected={Array.isArray(current) ? current.includes(o.v) : current === o.v}
                   multi={q.kind === "multi"}
                   big={useBig}
                   onPick={pick}/>
            ))}
          </div>
        )}

        <div className="of-cta-bar">
          <button className="of-back" onClick={onBack}>← Back</button>
          <button
            className="um-btn-primary"
            disabled={!canContinue}
            style={{opacity: canContinue ? 1 : 0.4, cursor: canContinue ? "pointer" : "not-allowed"}}
            onClick={onNext}
          >
            Continue <UmIcon name="ico-arrow-right" size={14}/>
          </button>
          <span className="hint">{q.kind === "multi" ? "Select all that apply" : "Pick one to continue"}</span>
        </div>
      </div>
    </section>
  );
}

/* ---------- DIAGNOSIS / RECOMMENDATION ENGINE ---------- */
function computeDiagnosis(answers) {
  const pain = answers.pain || [];
  const ai = answers.ai_readiness;
  const goal = answers.goal;
  const business = answers.business_type;
  const impact = answers.impact;
  const services = answers.services || [];

  const recs = [];

  // Pain → service mapping
  if (pain.includes("losing-leads") || pain.includes("poor-followup") || pain.includes("low-conversion")) {
    recs.push({
      k: "leads-system",
      t: "Automated lead capture + follow-up",
      d: "Stop losing leads in inboxes. Set up a Telegram bot + Sheets pipeline that captures, alerts, and follows up automatically.",
      maps: ["ai-pack", "ai-implementation", "digital-marketing"],
    });
  }
  if (pain.includes("poor-online") || pain.includes("low-conversion")) {
    recs.push({
      k: "web-rebuild",
      t: "Conversion-focused web rebuild",
      d: "Your site is the first sales tool. A focused redesign with clear conversion paths usually pays for itself in 60 days.",
      maps: ["web-design", "ui-ux"],
    });
  }
  if (pain.includes("manual-workflows") || pain.includes("no-automation") || pain.includes("staff-comms")) {
    recs.push({
      k: "automation-stack",
      t: "Automation stack — done-for-you",
      d: "Repetitive work eats compounding hours. The AI Pack + implementation handles lead capture, follow-up, internal alerts, and reporting.",
      maps: ["ai-pack", "ai-implementation"],
    });
  }
  if (pain.includes("inconsistent-brand") || goal === "brand") {
    recs.push({
      k: "brand-system",
      t: "Full-stack brand identity",
      d: "Consistency compounds trust. Build a strict identity system (logo, guidelines, applications) once — apply it everywhere.",
      maps: ["logo-creation", "static-graphics"],
    });
  }
  if (pain.includes("social-inconsist") || goal === "content") {
    recs.push({
      k: "content-engine",
      t: "Recurring content engine",
      d: "Switch from sporadic posts to a calibrated monthly engine — static, motion, and video shipped on a calendar.",
      maps: ["static-graphics", "motion-graphics", "video-production"],
    });
  }
  if (pain.includes("slow-support")) {
    recs.push({
      k: "support-bot",
      t: "AI support assistant",
      d: "Common questions get answered instantly via a trained AI assistant. Hand off the rest to humans.",
      maps: ["ai-pack", "ai-implementation"],
    });
  }

  // If nothing matched, default to a discovery call
  if (recs.length === 0) {
    recs.push({
      k: "consultation",
      t: "Free diagnostic call",
      d: "Let's get on a 15-minute call and map your bottlenecks together. From there I'll send you a scoped offer.",
      maps: [],
    });
  }

  // Engagement tier suggestion
  let engagement;
  if (impact === "20k+" || impact === "5-20k") {
    engagement = { tier: "Retainer", note: "Pain is significant — a monthly retainer brings velocity + accountability." };
  } else if (services.length >= 2 || pain.length >= 3) {
    engagement = { tier: "Project bundle", note: "Multiple pain points — bundling services into one project compounds impact." };
  } else if (ai === "beginner" && (pain.includes("manual-workflows") || pain.includes("no-automation"))) {
    engagement = { tier: "AI Pack + Implementation", note: "Best entry point — get the automation stack installed in 1–2 days." };
  } else if (ai === "advanced") {
    engagement = { tier: "AI Pack (self-serve)", note: "You can run the install yourself. Save the implementation fee." };
  } else {
    engagement = { tier: "Project-based", note: "One-off scope with clear deliverables." };
  }

  return { recs: recs.slice(0, 3), engagement, pain, impact, business };
}

function DiagnosisCard({ answers }) {
  const dx = useMemoOf(() => computeDiagnosis(answers), [answers]);

  return (
    <div className="of-diagnosis">
      <div className="of-dx-head">
        <span className="of-dx-eyebrow">
          <span className="dot"></span> Diagnosis complete
        </span>
        <h2 className="of-dx-title">
          Based on your answers, here's what I'd <span className="accent">recommend.</span>
        </h2>
      </div>

      {/* Engagement tier */}
      <div className="of-dx-engagement">
        <div className="of-dx-eng-lbl">Recommended engagement</div>
        <div className="of-dx-eng-tier">{dx.engagement.tier}</div>
        <div className="of-dx-eng-note">{dx.engagement.note}</div>
      </div>

      {/* Pain summary */}
      {dx.pain && dx.pain.length > 0 && (
        <div className="of-dx-pain">
          <div className="of-dx-eng-lbl">Bottlenecks you identified</div>
          <div className="of-dx-pain-row">
            {dx.pain.map((p, i) => <span key={i} className="of-dx-pain-chip">{p.replace(/-/g, " ")}</span>)}
          </div>
          {dx.impact && dx.impact !== "unsure" && (
            <div className="of-dx-pain-cost">
              Estimated monthly cost: <strong>
                {({
                  "<1k": "Under $1,000",
                  "1-5k": "$1k – $5k",
                  "5-20k": "$5k – $20k",
                  "20k+": "$20k+",
                })[dx.impact]}
              </strong>
            </div>
          )}
        </div>
      )}

      {/* Solutions */}
      <div className="of-dx-recs">
        {dx.recs.map((r, i) => (
          <div key={r.k} className="of-dx-rec">
            <div className="of-dx-rec-n">0{i+1}</div>
            <div>
              <div className="of-dx-rec-t">{r.t}</div>
              <div className="of-dx-rec-d">{r.d}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- OFFER PAGE ---------- */
function OfferPage({ answers, addons, setAddons, deadline, onProceed, onBack }) {
  const cd = useCountdown(deadline);

  // Build selected services + tiers
  const selected = useMemoOf(() => {
    const services = answers.services || [];
    const tiers = answers.tier || {};
    return services.map(sid => {
      const s = PMDS_SERVICES.find(x => x.id === sid);
      const t = s?.tiers?.find(tt => tt.id === tiers[sid]);
      return s && t ? { service: s, tier: t } : null;
    }).filter(Boolean);
  }, [answers]);

  // Compute discount based on timeline + cart size
  const discount = useMemoOf(() => {
    const t = answers.timeline;
    let pct = 0;
    if (selected.length >= 3) pct += 15;
    else if (selected.length >= 2) pct += 10;
    if (t === "month") pct += 5;
    if (t === "flexible") pct += 8;
    return Math.min(25, pct); // cap 25%
  }, [selected, answers.timeline]);

  const subtotal = selected.reduce((sum, x) => sum + x.tier.price, 0);
  const addonsTotal =
    (addons.aiPack         ? PMDS_AI_PACK.tiers[0].price       : 0) +
    (addons.aiImpl         ? PMDS_AI_IMPLEMENTATION.tiers[0].price : 0);
  const beforeDiscount = subtotal + addonsTotal;
  const discountAmt = Math.round(beforeDiscount * (discount / 100));
  const total = beforeDiscount - discountAmt;

  return (
    <section className="of-offer">
      <div className="of-offer-head">
        <span className="of-offer-pill">⚡ Limited personal offer</span>
        <h1 className="of-offer-title">
          Your <span className="accent">tailored</span><br/>
          package — <span className="off-pink">up to {discount || 5}% off</span>
        </h1>
        <p className="of-offer-sub">
          Based on what you told me, this is the cleanest fit. Add or remove items below.
          Lock in the discount before the timer ends.
        </p>
      </div>

      {/* DIAGNOSIS CARD */}
      <DiagnosisCard answers={answers}/>

      {/* Countdown banner */}
      <div className="of-countdown">
        <div className="promo">
          <span style={{color:"var(--signal-green)"}}>✓</span>{" "}
          <span className="code">umad_{(answers.contact?.name || "personal").toString().slice(0, 8).toUpperCase()}_PROMO</span>{" "}
          promocode is applied
        </div>
        <div className="col">
          <div className="big pink">{discount || 5}% OFF</div>
          <div className="lbl">With limited-offer promo</div>
        </div>
        <div className="col">
          <div className="big" style={{display:"flex", alignItems:"baseline", gap:6}}>
            <span>{cd.hours}</span>
            <span style={{color:"var(--dim-grey)"}}>:</span>
            <span>{cd.minutes}</span>
            <span style={{color:"var(--dim-grey)"}}>:</span>
            <span style={{color:"var(--accent)"}}>{cd.seconds}</span>
          </div>
          <div className="lbl">Hours · Minutes · Seconds</div>
        </div>
      </div>

      <div className="of-offer-grid">
        <div>
          {/* Selected services */}
          <div style={{display:"flex", flexDirection:"column", gap: 14}}>
            {selected.map(({service, tier}) => (
              <div key={service.id} className="of-pay-card" style={{padding: 22}}>
                <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:16}}>
                  <div>
                    <div style={{fontSize:10, letterSpacing:"0.22em", color:"var(--muted-grey)",
                                 textTransform:"uppercase", fontWeight:700, marginBottom: 6}}>
                      {service.kicker}
                    </div>
                    <h3 style={{fontWeight:800, fontSize: 22, margin: 0, letterSpacing:"-0.01em"}}>
                      {service.title}
                    </h3>
                    <div style={{fontSize:13, color:"var(--muted-grey)", marginTop: 4}}>
                      {tier.nm}{tier.unitNote ? ` · ${tier.unitNote}` : ""}
                    </div>
                  </div>
                  <div style={{textAlign:"right", whiteSpace:"nowrap"}}>
                    <div style={{fontFamily:"var(--font-display)", fontWeight:700, fontSize: 28, color:"var(--accent)", letterSpacing:"-0.02em"}}>
                      ${tier.price.toLocaleString()}
                    </div>
                    <div style={{fontSize:11, color:"var(--muted-grey)"}}>{tier.suffix}</div>
                  </div>
                </div>
              </div>
            ))}
            {selected.length === 0 && (
              <div className="of-pay-card" style={{textAlign:"center"}}>
                No services selected. <button className="of-back" style={{marginTop:14}} onClick={onBack}>← Go back</button>
              </div>
            )}
          </div>

          {/* AI add-ons */}
          <div style={{marginTop: 36}}>
            <div style={{fontSize:11, letterSpacing:"0.22em", color:"var(--muted-grey)",
                         textTransform:"uppercase", fontWeight:700, marginBottom: 14}}>
              ⚡ Power-up add-ons
            </div>
            <div className="of-addons">
              <button type="button"
                className={"of-addon " + (addons.aiPack ? "selected" : "")}
                onClick={() => setAddons({...addons, aiPack: !addons.aiPack})}>
                <span className="of-addon-check"></span>
                <div className="ad-nm">AI Automation Pack</div>
                <div className="ad-sub">6-step automation stack — Claude Code, VS Code, Telegram, Sheets. <a href="ai-setup.html" style={{color:"var(--accent)"}}>What's inside →</a></div>
                <div className="ad-price">${PMDS_AI_PACK.tiers[0].price}</div>
              </button>
              <button type="button"
                className={"of-addon " + (addons.aiImpl ? "selected" : "")}
                onClick={() => setAddons({...addons, aiImpl: !addons.aiImpl})}>
                <span className="of-addon-check"></span>
                <div className="ad-nm">AI Pack — Implementation</div>
                <div className="ad-sub">We install everything for you in 1–2 days. <a href="ai-implementation.html" style={{color:"var(--accent)"}}>Read more →</a></div>
                <div className="ad-price">${PMDS_AI_IMPLEMENTATION.tiers[0].price}</div>
              </button>
            </div>
          </div>

          <div className="of-cta-bar">
            <button className="of-back" onClick={onBack}>← Back</button>
          </div>
        </div>

        {/* Right: sticky order summary */}
        <aside className="of-summary">
          <h3>Your Order</h3>
          {selected.map(({service, tier}) => (
            <div key={service.id} className="line">
              <div>
                <div className="nm">{service.title}</div>
                <div className="meta">{tier.nm}</div>
              </div>
              <div className="price">${tier.price.toLocaleString()}</div>
            </div>
          ))}
          {addons.aiPack && (
            <div className="line">
              <div>
                <div className="nm">AI Automation Pack</div>
                <div className="meta">Self-serve install</div>
              </div>
              <div className="price">${PMDS_AI_PACK.tiers[0].price}</div>
            </div>
          )}
          {addons.aiImpl && (
            <div className="line">
              <div>
                <div className="nm">AI Implementation</div>
                <div className="meta">Done-for-you setup</div>
              </div>
              <div className="price">${PMDS_AI_IMPLEMENTATION.tiers[0].price}</div>
            </div>
          )}

          {discount > 0 && beforeDiscount > 0 && (
            <div className="line" style={{color:"var(--signal-green)"}}>
              <div>
                <div className="nm" style={{color:"var(--signal-green)"}}>Discount ({discount}%)</div>
                <div className="meta">Limited offer</div>
              </div>
              <div className="price" style={{color:"var(--signal-green)"}}>−${discountAmt.toLocaleString()}</div>
            </div>
          )}

          <div className="total-row">
            <div className="total-lbl">Total</div>
            <div className="total-price">${total.toLocaleString()}</div>
          </div>

          <button className="um-btn-primary"
                  style={{justifyContent:"center", width:"100%", marginTop: 6}}
                  onClick={onProceed}
                  disabled={beforeDiscount === 0}>
            Proceed to payment <UmIcon name="ico-arrow-right" size={14}/>
          </button>
          <div style={{fontSize:11, color:"var(--dim-grey)", textAlign:"center", letterSpacing:"0.12em"}}>
            Transfer · Cheque · Secure
          </div>
        </aside>
      </div>
    </section>
  );
}

/* ---------- PAYMENT PAGE ---------- */
function PaymentPage({ answers, total, addons, selected, onSubmit, onBack }) {
  const [method, setMethod] = useOf("transfer");
  const c = answers.contact || {};
  return (
    <section className="of-pay">
      <h1 style={{fontFamily:"var(--font-display)", fontSize:"clamp(36px, 4.5vw, 56px)",
                  textTransform:"uppercase", letterSpacing:"-0.01em", marginBottom: 32}}>
        Confirm & <span style={{color:"var(--accent)"}}>place order</span>
      </h1>

      <div className="of-pay-grid">
        <div>
          <div className="of-pay-card">
            <h2>Contact details</h2>
            <div className="of-field-row">
              <div className="of-field">
                <label>Name</label>
                <input defaultValue={c.name} placeholder="Full name"/>
              </div>
              <div className="of-field">
                <label>Email</label>
                <input defaultValue={c.email} placeholder="you@brand.com"/>
              </div>
            </div>
            <div className="of-field-row">
              <div className="of-field">
                <label>Company</label>
                <input defaultValue={c.company} placeholder="Brand or studio"/>
              </div>
              <div className="of-field">
                <label>Phone (optional)</label>
                <input placeholder="+1 (000) 000-0000"/>
              </div>
            </div>
          </div>

          <div className="of-pay-card" style={{marginTop: 18}}>
            <h2>Payment method</h2>
            <div className="of-pay-methods">
              <button type="button"
                      className={"of-pay-method " + (method === "transfer" ? "selected" : "")}
                      onClick={() => setMethod("transfer")}>
                <div className="ic">⇄</div>
                <div className="ttl">Bank transfer</div>
                <div className="sub">Wire / e-transfer. Most common. Cleared same-day.</div>
              </button>
              <button type="button"
                      className={"of-pay-method " + (method === "cheque" ? "selected" : "")}
                      onClick={() => setMethod("cheque")}>
                <div className="ic">✎</div>
                <div className="ttl">Bank cheque</div>
                <div className="sub">Mailed to studio address. Cleared on receipt.</div>
              </button>
            </div>

            {method === "transfer" && (
              <div className="of-bank-info">
                <div><span className="k">Beneficiary:</span> <span className="v">Uche Madumere / PMDS</span></div>
                <div><span className="k">Bank:</span>        <span className="v">RBC Royal Bank</span></div>
                <div><span className="k">Transit:</span>     <span className="v">00012</span></div>
                <div><span className="k">Account:</span>     <span className="v">000 000 000</span></div>
                <div><span className="k">SWIFT:</span>       <span className="v">ROYCCAT2</span></div>
                <div><span className="k">Reference:</span>   <span className="v">UM-ORDER / {c.name || "your name"}</span></div>
              </div>
            )}
            {method === "cheque" && (
              <div className="of-bank-info">
                <div><span className="k">Payable to:</span> <span className="v">Uche Madumere</span></div>
                <div><span className="k">Mail to:</span>    <span className="v">PMDS Studio · Mississauga, ON, Canada</span></div>
                <div><span className="k">Address:</span>    <span className="v">Provided by email after confirmation</span></div>
                <div><span className="k">Reference:</span>  <span className="v">UM-ORDER / {c.name || "your name"}</span></div>
              </div>
            )}
          </div>
        </div>

        {/* Sticky summary */}
        <aside className="of-summary">
          <h3>Order summary</h3>
          {selected.map(({ service, tier }) => (
            <div key={service.id} className="line">
              <div>
                <div className="nm">{service.title}</div>
                <div className="meta">{tier.nm}</div>
              </div>
              <div className="price">${tier.price.toLocaleString()}</div>
            </div>
          ))}
          {addons.aiPack && (
            <div className="line">
              <div><div className="nm">AI Automation Pack</div><div className="meta">Self-serve</div></div>
              <div className="price">${PMDS_AI_PACK.tiers[0].price}</div>
            </div>
          )}
          {addons.aiImpl && (
            <div className="line">
              <div><div className="nm">AI Implementation</div><div className="meta">Done-for-you</div></div>
              <div className="price">${PMDS_AI_IMPLEMENTATION.tiers[0].price}</div>
            </div>
          )}
          <div className="total-row">
            <div className="total-lbl">Total due</div>
            <div className="total-price">${total.toLocaleString()}</div>
          </div>
          <button className="um-btn-primary" style={{justifyContent:"center", width:"100%"}} onClick={() => onSubmit(method)}>
            Place order <UmIcon name="ico-arrow-right" size={14}/>
          </button>
          <button className="of-back" onClick={onBack}>← Edit offer</button>
        </aside>
      </div>
    </section>
  );
}

/* ---------- SUCCESS ---------- */
function SuccessPage({ method, contact }) {
  const R2 = (typeof window !== "undefined" && window.UM_ROOT) || "../../";
  return (
    <div className="of-success">
      <div className="check">✓</div>
      <h2>Order received</h2>
      <p>
        Thanks {contact.name?.split(" ")[0] || "there"}. We've sent a confirmation to{" "}
        <strong>{contact.email}</strong> with payment instructions for {method === "cheque" ? "bank cheque" : "bank transfer"}.
        Once payment clears, you'll receive an onboarding link.
      </p>
      <div style={{display:"flex", gap:14, justifyContent:"center", flexWrap:"wrap"}}>
        <a className="um-btn-primary" href={`${R2}index.html`}>Back to home</a>
        <a className="um-btn-ghost" href={`${R2}pages/book-appointment.html`}>Book a kickoff call</a>
      </div>
    </div>
  );
}

/* ---------- TOP BAR ---------- */
function OrderTopBar({ stepIdx, totalSteps, onBack, showBack }) {
  const R2 = (typeof window !== "undefined" && window.UM_ROOT) || "../../";
  const pct = totalSteps > 0 ? Math.round((stepIdx / totalSteps) * 100) : 0;
  return (
    <div className="of-top">
      <div className="of-top-inner">
        <a className="of-top-mark" href={`${R2}index.html`}>
          <img src={`${R2}assets/logos/transparent/iconmark-whiteblue.png`} alt="UM"/>
          <span className="nm">UCHE MADUMERE</span>
        </a>
        <div className="of-step">
          {totalSteps > 0
            ? <>Step <span className="accent">{Math.min(stepIdx + 1, totalSteps)}</span> of {totalSteps}</>
            : "Build your offer"}
        </div>
        {showBack
          ? <button className="of-back" onClick={onBack}>← Back</button>
          : <a className="of-back" href={`${R2}index.html`}>Exit ×</a>}
      </div>
      {totalSteps > 0 && (
        <div className="of-progress-rail">
          <div className="of-progress-fill" style={{width: `${pct}%`}}></div>
        </div>
      )}
    </div>
  );
}

/* ---------- MAIN ---------- */
function OrderFlow() {
  // Phase: 'hero' | 'q' | 'offer' | 'pay' | 'success'
  const initial = loadState();
  const prefilledService = getUrlParam("service");
  const prefilledTier    = getUrlParam("tier");

  const initialAnswers = useMemoOf(() => {
    const base = initial.answers || {};
    if (prefilledService) {
      base.services = Array.from(new Set([...(base.services || []), prefilledService]));
      if (prefilledTier && PMDS_SERVICES.find(s => s.id === prefilledService)?.tiers?.find(t => t.id === prefilledTier)) {
        base.tier = { ...(base.tier || {}), [prefilledService]: prefilledTier };
      }
    }
    return base;
  }, []);

  const [phase, setPhase]       = useOf(initial.phase || "hero");
  const [stepIdx, setStepIdx]   = useOf(initial.stepIdx || 0);
  const [answers, setAnswers]   = useOf(initialAnswers);
  const [addons, setAddons]     = useOf(initial.addons || { aiPack: false, aiImpl: false });
  const [method, setMethod]     = useOf("transfer");
  const questions = useMemoOf(() => buildQuestions(prefilledService), []);

  // Persist
  useEffOf(() => {
    saveState({ phase, stepIdx, answers, addons });
  }, [phase, stepIdx, answers, addons]);

  // Countdown deadline — start a fresh 24h timer the first time the user sees the offer
  const deadlineRef = useRefOf(null);
  if (deadlineRef.current === null) {
    const stored = Number(localStorage.getItem("um_order_deadline_v1"));
    if (stored && stored > Date.now()) {
      deadlineRef.current = stored;
    } else {
      const d = Date.now() + 1000 * 60 * 60 * 24; // 24 hours
      localStorage.setItem("um_order_deadline_v1", String(d));
      deadlineRef.current = d;
    }
  }

  const answer = (id, v) => setAnswers(prev => ({ ...prev, [id]: v }));

  const next = () => {
    if (stepIdx < questions.length - 1) setStepIdx(stepIdx + 1);
    else setPhase("offer");
  };
  const back = () => {
    if (phase === "offer") { setPhase("q"); setStepIdx(questions.length - 1); return; }
    if (phase === "pay")   { setPhase("offer"); return; }
    if (phase === "q" && stepIdx > 0) setStepIdx(stepIdx - 1);
    else setPhase("hero");
  };

  // For payment page
  const selected = useMemoOf(() => {
    const services = answers.services || [];
    const tiers = answers.tier || {};
    return services.map(sid => {
      const s = PMDS_SERVICES.find(x => x.id === sid);
      const t = s?.tiers?.find(tt => tt.id === tiers[sid]);
      return s && t ? { service: s, tier: t } : null;
    }).filter(Boolean);
  }, [answers]);

  const discountPct = useMemoOf(() => {
    let pct = 0;
    if (selected.length >= 3) pct += 15;
    else if (selected.length >= 2) pct += 10;
    if (answers.timeline === "month") pct += 5;
    if (answers.timeline === "flexible") pct += 8;
    return Math.min(25, pct);
  }, [selected, answers.timeline]);

  const total = useMemoOf(() => {
    const sub = selected.reduce((s, x) => s + x.tier.price, 0)
              + (addons.aiPack ? PMDS_AI_PACK.tiers[0].price : 0)
              + (addons.aiImpl ? PMDS_AI_IMPLEMENTATION.tiers[0].price : 0);
    return sub - Math.round(sub * (discountPct / 100));
  }, [selected, addons, discountPct]);

  return (
    <div className="of-shell">
      <div className="of-aurora"></div>
      <OrderTopBar
        stepIdx={phase === "q" ? stepIdx : 0}
        totalSteps={phase === "q" ? questions.length : 0}
        showBack={phase !== "hero"}
        onBack={back}
      />

      {phase === "hero" && <OrderHero onStart={() => { setPhase("q"); setStepIdx(0); }}/>}

      {phase === "q" && (
        <QuestionStep
          q={questions[stepIdx]}
          stepIdx={stepIdx}
          totalSteps={questions.length}
          answers={answers}
          onAnswer={answer}
          onNext={next}
          onBack={back}
        />
      )}

      {phase === "offer" && (
        <OfferPage
          answers={answers}
          addons={addons}
          setAddons={setAddons}
          deadline={deadlineRef.current}
          onProceed={() => setPhase("pay")}
          onBack={back}
        />
      )}

      {phase === "pay" && (
        <PaymentPage
          answers={answers}
          total={total}
          addons={addons}
          selected={selected}
          onSubmit={(m) => { setMethod(m); setPhase("success"); }}
          onBack={back}
        />
      )}

      {phase === "success" && (
        <SuccessPage method={method} contact={answers.contact || {}}/>
      )}
    </div>
  );
}

window.OrderFlow = OrderFlow;
