const { useState, useRef, useEffect } = React;

/* ── session ID ── */
function makeSessionId() {
  return "s_" + Date.now().toString(36) + "_" + Math.random().toString(36).slice(2, 8);
}
const SESSION_ID = makeSessionId();

/* ── analytics helper ── */
function trackEvent(eventType, eventData, page) {
  fetch("/api/analytics/event", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ sessionId: SESSION_ID, eventType, eventData, page }),
  }).catch(() => {}); // fire-and-forget
}

/* ── palette ── */
const C = {
  gold: "#B8860B",
  goldBg: "rgba(184,134,11,0.06)",
  goldHover: "rgba(184,134,11,0.12)",
  brown: "#5C4033",
  text: "#2C2318",
  sec: "#6B5D4F",
  tri: "#9B8E7E",
  bdr: "rgba(107,93,79,0.15)",
  bdrH: "rgba(107,93,79,0.25)",
  surf: "#FAF8F5",
  w: "#FFFFFF",
};

/* ── designers ── */
const DESIGNERS = {
  claire: { name: "Claire", title: "Modern & editorial spaces", initials: "CM", color: "#3A2A1D" },
  rachel: { name: "Rachel", title: "Warm family-friendly rooms", initials: "RT", color: "#5C4033" },
  natalie: { name: "Natalie", title: "Smart style transformations", initials: "NW", color: "#8B6914" },
};

function pickDesigner(a) {
  if (a.priority === "showstopper" || a.style === "eclectic" || a.style === "modern") return DESIGNERS.claire;
  if (a.priority === "family" || a.priority === "complete" || a.style === "cozy") return DESIGNERS.rachel;
  if (a.priority === "value" || a.budget === "under150") return DESIGNERS.natalie;
  return DESIGNERS.rachel;
}

/* ── small components ── */
function Avatar({ d, size = 44 }) {
  return (
    <div style={{ width: size, height: size, borderRadius: "50%", background: d.color, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
      <span style={{ color: "#F5F0E8", fontSize: size * 0.35, fontWeight: 500 }}>{d.initials}</span>
    </div>
  );
}

function Stars({ rating = 4.7, count = "4,300+" }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 6, justifyContent: "center" }}>
      <div style={{ display: "flex", gap: 1 }}>
        {[1, 2, 3, 4, 5].map((n) => (
          <svg key={n} width="14" height="14" viewBox="0 0 24 24" fill={n <= Math.floor(rating) ? C.gold : "none"} stroke={C.gold} strokeWidth="1.5">
            <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>
        ))}
      </div>
      <span style={{ fontSize: 12, color: C.sec, fontWeight: 300 }}>{rating}/5 from {count} consultations</span>
    </div>
  );
}

function Hov({ children, base, hover, onClick, as: T = "div" }) {
  const [h, setH] = useState(false);
  return (
    <T style={h ? { ...base, ...hover } : base} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} onClick={onClick}>
      {children}
    </T>
  );
}

const bS = (on) => ({
  background: on ? C.gold : C.bdr,
  color: on ? "#fff" : C.tri,
  border: "none",
  borderRadius: 4,
  padding: "13px 36px",
  fontSize: 13,
  fontWeight: 500,
  letterSpacing: 0.5,
  cursor: on ? "pointer" : "default",
  transition: "all 0.2s",
});

/* ── quiz data ── */
const ROOMS = [
  { id: "living", l: "Living room", s: "Where everything comes together", e: "\u{1F6CB}\u{FE0F}" },
  { id: "bedroom", l: "Bedroom", s: "Your first step every morning", e: "\u{1F6CF}\u{FE0F}" },
  { id: "office", l: "Home office", s: "Work deserves warmth too", e: "\u{1F4BB}" },
  { id: "dining", l: "Dining room", s: "Set the scene for gathering", e: "\u{1F37D}\u{FE0F}" },
  { id: "entryway", l: "Entryway", s: "Where first impressions live", e: "\u{1F6AA}" },
  { id: "other", l: "Other space", s: "Den, nursery, covered patio", e: "\u2728" },
];

const ROOM_TIPS = {
  living: [
    "Angle the rug 10-15 degrees off-center from your sofa \u2014 the trick that makes a room look styled, not staged",
    "Front sofa legs on the rug, coffee table centered \u2014 this anchors the seating area",
    "Go X-Large if you\u2019re unsure \u2014 cowhides are natural shapes and the extra coverage makes all the difference",
  ],
  bedroom: [
    "Place it beside the bed \u2014 the first texture your feet touch every morning",
    "King beds pair best with X-Large. Queens look beautiful with a Large to X-Large at the foot",
    "Layer a sheepskin throw at the foot over the cowhide for magazine-level texture",
  ],
  office: [
    "Size it so your desk chair rolls entirely on the rug \u2014 protects floors and defines the workspace",
    "Go one size up from what you think \u2014 the natural shape means less coverage than the measurements suggest",
    "The rug creates a visual work zone that separates office from the rest of the room",
  ],
  dining: [
    "Designer technique: use two matching cowhide rugs side by side for full table coverage",
    "Two hides with similar patterns 1-2 inches apart read as one cohesive piece",
    "Wine, coffee, dinner spills wipe clean in seconds \u2014 cowhide is the most practical dining rug material",
  ],
  entryway: [
    "A Medium to Large cowhide makes a bold first impression \u2014 the piece guests see before anything else",
    "Center it so it sets the design tone for the home the moment someone walks in",
    "High traffic is no problem \u2014 cowhide is naturally durable and gets more characterful with age",
  ],
  other: [
    "Cowhides work in nurseries, covered patios, reading nooks \u2014 anywhere you want warmth and texture",
    "For dens and bonus rooms, a Large or X-Large anchors the seating area",
    "Pets, kids, and everyday use only make the material softer over time",
  ],
};

const MEASURE_TIPS = {
  living: { title: "Measuring for a natural-shape rug", text: "Cowhides aren\u2019t rectangular \u2014 they\u2019re organic shapes measured at the widest and tallest points. The actual coverage is smaller than those numbers. Measure the area from the front of your sofa to past the coffee table, then go one size up for a generous fit." },
  bedroom: { title: "Measuring for a natural-shape rug", text: "Dimensions are the widest and tallest points of the hide \u2014 actual coverage is smaller than a rectangle that size. Measure the length of bed you want covered and go one size up." },
  office: { title: "Measuring for a natural-shape rug", text: "Roll your chair to its furthest position in every direction. That\u2019s your minimum. Then go one size up \u2014 cowhides are irregular natural shapes and cover less area than the stated dimensions suggest." },
  dining: { title: "Measuring for a dining setup", text: "Measure your table length + 48 inches for chairs. Since cowhides are natural shapes (not rectangles), most dining tables work best with two matching hides side by side for full coverage." },
  entryway: { title: "Measuring for a natural-shape rug", text: "Measure your entry width. Cowhide dimensions are widest by tallest points \u2014 actual coverage is less than a rectangular rug. Go Medium to Large and center it for the boldest first impression." },
  other: { title: "Measuring for a natural-shape rug", text: "Measure the area, then go one size up. Cowhide dimensions are widest by tallest \u2014 the natural shape covers less than those numbers suggest. Bigger always looks more intentional." },
};

const STYLES = [
  { id: "modern", l: "Modern minimal", s: "Clean lines meet organic warmth", dots: ["#F5F0E8", "#2C2318", "#B8B0A4"], imgBrief: "Bright modern room" },
  { id: "warm", l: "Warm contemporary", s: "Leather, wood, layered comfort", dots: ["#C4A77D", "#5C4033", "#E8DFD0"], imgBrief: "Warm room \u2014 cognac leather" },
  { id: "eclectic", l: "Eclectic luxe", s: "Collected, curated, gallery energy", dots: ["#B8860B", "#3A2A1D", "#D4C5B0"], imgBrief: "Art-forward \u2014 gallery wall" },
  { id: "cozy", l: "Cozy transitional", s: "Soft textures, quiet warmth", dots: ["#D2C4B0", "#8B7355", "#F0EBE3"], imgBrief: "Comfortable \u2014 linen, knit" },
];

const PALETTES = [
  { id: "warm-neutral", l: "Warm neutrals", s: "Creams, tans, warm grays", sw: ["#F5F0E8", "#C4A77D", "#9B8E7E", "#6B5D4F"] },
  { id: "cool-neutral", l: "Cool neutrals", s: "Whites, grays, cool tones", sw: ["#F0F0EE", "#B8B8B4", "#808080", "#404040"] },
  { id: "earth", l: "Rich earth tones", s: "Deep browns, greens, terracotta", sw: ["#5C4033", "#8B6914", "#6B4226", "#3D5C3A"] },
  { id: "contrast", l: "High contrast", s: "Black, white, bold accents", sw: ["#FFFFFF", "#2C2318", "#B8860B", "#000000"] },
];

const BUDGETS = [
  { id: "under150", l: "Under $150", s: "Great style, smart price" },
  { id: "150to250", l: "$150 - $250", s: "The sweet spot" },
  { id: "250to400", l: "$250 - $400", s: "Premium quality" },
  { id: "best", l: "Show me the best", s: "Price isn\u2019t the priority" },
];

const HOUSEHOLD = [
  { id: "adults", l: "Just adults", e: "\u{1F46B}" },
  { id: "kids", l: "Kids under 10", e: "\u{1F476}" },
  { id: "dogs", l: "Dogs", e: "\u{1F415}" },
  { id: "cats", l: "Cats", e: "\u{1F408}" },
];

const PRIORITIES = [
  { id: "family", l: "Built for real life", s: "Kids, pets, spills \u2014 bring it on", i: "\u{1F43E}" },
  { id: "showstopper", l: "The room\u2019s centerpiece", s: "The piece guests notice immediately", i: "\u{1F3A8}" },
  { id: "value", l: "Maximum style, smart budget", s: "Look like you spent more than you did", i: "\u{1F48E}" },
  { id: "complete", l: "The missing piece", s: "The room needs something \u2014 this is it", i: "\u{1F9E9}" },
];

const SIZES = [
  { id: "small", l: "Small / cozy", s: "Under 10\u2019 x 10\u2019" },
  { id: "medium", l: "Medium", s: "10x12 to 12x14" },
  { id: "large", l: "Large / open", s: "14x16 or bigger" },
  { id: "unsure", l: "You decide", s: "That\u2019s what designers are for" },
];

const FLOOR_COLORS = [
  { id: "light", l: "Light floors", s: "Light oak, white tile, blonde" },
  { id: "medium-floor", l: "Medium floors", s: "Walnut, honey oak, tan tile" },
  { id: "dark", l: "Dark floors", s: "Espresso, dark walnut, stone" },
];

const PHASES = [
  "Reviewing your preferences...",
  "Selecting the best match...",
  "Mapping placement...",
  "Adding styling details...",
  "Finishing your report...",
];

const FLOOR_OPTS = [
  { id: "hardwood", l: "Hardwood", s: "The classic pairing" },
  { id: "tile", l: "Tile or stone", s: "Adds warmth underfoot" },
  { id: "carpet", l: "Over carpet", s: "Layering works beautifully" },
  { id: "other-floor", l: "Other", s: "Concrete, vinyl, etc." },
];

/* ── lookup helpers ── */
const g = (a, id) => a.find((x) => x.id === id);

function buildKlaviyoPayload(data) {
  return {
    profile: {
      email: data.email,
      first_name: data.name || "",
      properties: {
        quiz_completed: true,
        quiz_completed_at: new Date().toISOString(),
        quiz_room: g(ROOMS, data.room)?.l || "",
        quiz_style: g(STYLES, data.style)?.l || "",
        quiz_palette: g(PALETTES, data.palette)?.l || "",
        quiz_floor_color: g(FLOOR_COLORS, data.floorColor)?.l || "",
        quiz_budget: g(BUDGETS, data.budget)?.l || "",
        quiz_household: data.household?.map((h) => HOUSEHOLD.find((x) => x.id === h)?.l || h).join(", ") || "",
        quiz_priority: g(PRIORITIES, data.priority)?.l || "",
        quiz_room_size: g(SIZES, data.size)?.l || "",
        quiz_floor_type: data.floor || "",
        quiz_photo_uploaded: !!data.photoData,
        quiz_notes: data.photoNotes || "",
        quiz_designer: data.designer?.name || "",
      },
    },
    event: {
      name: "Design Consultation Completed",
      properties: {
        room: g(ROOMS, data.room)?.l || "",
        style: g(STYLES, data.style)?.l || "",
        budget: g(BUDGETS, data.budget)?.l || "",
        designer: data.designer?.name || "",
      },
    },
  };
}

/* =============================================
   LANDING
   ============================================= */
function Landing({ onStart }) {
  useEffect(() => {
    trackEvent("page_view", {}, "landing");
  }, []);

  return (
    <div style={{ padding: "44px 24px 40px" }}>
      <div style={{ textAlign: "center", marginBottom: 40 }}>
        <div style={{ fontSize: 10.5, letterSpacing: 2.5, textTransform: "uppercase", color: C.gold, fontWeight: 500, marginBottom: 16 }}>
          Free instant design consultation
        </div>
        <h1 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 30, fontWeight: 400, lineHeight: 1.2, maxWidth: 500, margin: "0 auto 12px" }}>
          The exact rug, size, and placement for your room &mdash; answered in 3 minutes
        </h1>
        <p style={{ fontSize: 15, color: C.sec, lineHeight: 1.65, maxWidth: 440, margin: "0 auto 20px", fontWeight: 300 }}>
          Our trained virtual designers analyze your space and style, then deliver a personalized consultation instantly. Free. No obligation.
        </p>
        <Hov
          as="button"
          base={{ background: C.gold, color: "#fff", border: "none", borderRadius: 4, padding: "15px 48px", fontSize: 14, fontWeight: 500, letterSpacing: 0.8, textTransform: "uppercase", cursor: "pointer", transition: "all 0.2s", marginBottom: 14 }}
          hover={{ background: "#A07A0A", transform: "translateY(-1px)" }}
          onClick={() => { trackEvent("cta_click", { button: "hero_start" }, "landing"); onStart(); }}
        >
          Start my free consultation
        </Hov>
        <div style={{ display: "flex", justifyContent: "center", gap: 16, fontSize: 12, color: C.tri, flexWrap: "wrap", marginBottom: 14 }}>
          <span>Results in ~15 seconds</span><span>&middot;</span><span>100% free</span><span>&middot;</span><span>No account needed</span>
        </div>
        <Stars />
      </div>

      <div style={{ background: C.surf, border: "1px dashed " + C.bdrH, borderRadius: 12, padding: "2rem 1.5rem", textAlign: "center", marginBottom: 32, minHeight: 200, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8 }}>
        <span style={{ fontSize: 10, letterSpacing: 1.5, textTransform: "uppercase", color: C.gold, fontWeight: 500 }}>Hero image</span>
        <span style={{ fontSize: 12.5, color: C.sec, maxWidth: 380, lineHeight: 1.55 }}>
          Designers collaborating over cowhide swatches and room photos. Warm light, Florida studio. 16:9.
        </span>
      </div>

      <div style={{ maxWidth: 500, margin: "0 auto 32px" }}>
        <div style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 20, fontWeight: 400, textAlign: "center", marginBottom: 16 }}>
          What a $200 design session looks like &mdash; free
        </div>
        {["Color guidance + top 3 collection picks", "Size range for natural-shape cowhide rugs", "Step-by-step placement with exact angles", "Styling ideas tailored to your decor", "Care essentials (spoiler: easier than your current rug)"].map((t, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
            <div style={{ width: 22, height: 22, borderRadius: "50%", background: C.goldBg, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, color: C.gold, fontWeight: 500, flexShrink: 0 }}>
              {i + 1}
            </div>
            <div style={{ fontSize: 13.5, color: C.sec, fontWeight: 300 }}>{t}</div>
          </div>
        ))}
      </div>

      <div style={{ background: C.surf, borderRadius: 12, padding: "22px 20px", textAlign: "center", maxWidth: 500, margin: "0 auto 32px" }}>
        <p style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 16, fontStyle: "italic", lineHeight: 1.6, color: C.text, marginBottom: 8 }}>
          "It told me exactly what size, what color, and how to angle it under my coffee table. When the rug arrived it looked like I hired a designer. My husband thought I did."
        </p>
        <cite style={{ fontSize: 12, color: C.tri, fontStyle: "normal" }}>&mdash; Amanda K., Raleigh, NC</cite>
      </div>

      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Hov
          as="button"
          base={{ background: C.gold, color: "#fff", border: "none", borderRadius: 4, padding: "15px 48px", fontSize: 14, fontWeight: 500, letterSpacing: 0.8, textTransform: "uppercase", cursor: "pointer", transition: "all 0.2s" }}
          hover={{ background: "#A07A0A", transform: "translateY(-1px)" }}
          onClick={() => { trackEvent("cta_click", { button: "bottom_start" }, "landing"); onStart(); }}
        >
          Get my free consultation
        </Hov>
      </div>

      <div style={{ display: "flex", justifyContent: "center", gap: 28, flexWrap: "wrap", paddingTop: 20, borderTop: "1px solid " + C.bdr }}>
        {[["25+", "years expertise"], ["100K+", "homes styled"], ["~15 sec", "instant results"], ["Free", "always"]].map(([v, l], i) => (
          <div key={i} style={{ textAlign: "center" }}>
            <span style={{ display: "block", fontSize: 15, fontWeight: 500, marginBottom: 1 }}>{v}</span>
            <span style={{ fontSize: 11, color: C.tri }}>{l}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* =============================================
   QUIZ
   ============================================= */
function QuizFlow({ onComplete }) {
  const [step, setStep] = useState(0);
  const [ans, setAns] = useState({
    room: null, style: null, palette: null, floorColor: null,
    budget: null, household: ["adults"], priority: null, size: null, floor: "hardwood",
  });
  const [photo, setPhoto] = useState(null);
  const [photoData, setPhotoData] = useState(null);
  const [photoNotes, setPhotoNotes] = useState("");
  const [email, setEmail] = useState("");
  const [fname, setFname] = useState("");
  const fileRef = useRef();
  const wrapRef = useRef();

  useEffect(() => {
    wrapRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  }, [step]);

  // Track quiz step views
  useEffect(() => {
    trackEvent("quiz_step_view", { step: step, stepKey: STEPS[step]?.key }, "quiz");
  }, [step]);

  const STEPS = [
    { key: "room", t: "Let\u2019s start with the room", s: "This shapes everything \u2014 size, pattern, and placement.", opts: ROOMS, hasE: true, hasTips3: true },
    { key: "style", t: "How would you describe your taste?", s: "Pick the room that feels most like home.", opts: STYLES, hasDots: true, hasImg: true },
    { key: "palette", t: "What colors already live in this room?", s: "Think walls and your biggest furniture piece.", opts: PALETTES, hasSw: true, hasFloorColor: true },
    { key: "budgetHousehold", isBH: true, t: "A couple details that shape the recommendation", s: "Your budget helps us point you to the right collection." },
    { key: "priority", t: "If this rug could do one thing perfectly \u2014 what?", s: "Our virtual designer optimizes for this first.", opts: PRIORITIES, hasI: true },
    { key: "size", t: "How big is the room?", s: "Ballpark is fine \u2014 we\u2019ll help you measure for the natural shape.", opts: SIZES, hasMeasure: true },
    { key: "photo", isPhoto: true, t: "Two more details for your virtual designer", s: "Flooring type helps dial in the recommendation. A room photo takes it further \u2014 completely optional." },
    { key: "email", isEmail: true },
  ];

  const cur = STEPS[step];
  const sel = ans[cur.key];
  const total = STEPS.length;
  const pct = ((step + 1) / total) * 100;
  const designer = step >= 5 ? pickDesigner(ans) : null;

  const handleFile = (f) => {
    if (!f?.type.startsWith("image/")) return;
    setPhoto(URL.createObjectURL(f));
    const r = new FileReader();
    r.onload = () => setPhotoData(r.result.split(",")[1]);
    r.readAsDataURL(f);
    trackEvent("photo_uploaded", {}, "quiz");
  };

  const toggleHH = (id) => {
    let h = [...ans.household];
    if (id === "adults") { h = ["adults"]; }
    else {
      h = h.filter((x) => x !== "adults");
      if (h.includes(id)) h = h.filter((x) => x !== id);
      else h.push(id);
      if (!h.length) h = ["adults"];
    }
    setAns({ ...ans, household: h });
  };

  const canNext = () => {
    if (cur.isPhoto || cur.isEmail) return true;
    if (cur.isBH) return !!ans.budget;
    if (cur.hasFloorColor) return !!sel && !!ans.floorColor;
    return !!sel;
  };

  const next = () => {
    if (step < total - 1) {
      trackEvent("quiz_step_complete", { step: step, stepKey: cur.key, answer: sel || ans.budget }, "quiz");
      setStep(step + 1);
    } else {
      if (!email.trim()) return;
      const d = pickDesigner(ans);
      trackEvent("quiz_completed", { designer: d.name, email: email.trim() }, "quiz");
      onComplete({ ...ans, photoData, photoNotes, email: email.trim(), name: fname.trim(), designer: d });
    }
  };

  const back = () => { if (step > 0) setStep(step - 1); };

  return (
    <div ref={wrapRef} style={{ padding: "36px 24px", scrollMarginTop: 0 }}>
      {/* Progress bar */}
      <div style={{ height: 3, background: C.bdr, borderRadius: 2, marginBottom: 24, overflow: "hidden" }}>
        <div style={{ height: "100%", width: pct + "%", background: C.gold, borderRadius: 2, transition: "width 0.4s ease" }} />
      </div>

      {/* Designer match badge */}
      {designer && !cur.isEmail && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18, padding: "9px 14px", background: C.goldBg, borderRadius: 8 }}>
          <Avatar d={designer} size={28} />
          <span style={{ fontSize: 12, fontWeight: 500 }}>Matched with {designer.name}</span>
          <span style={{ fontSize: 11, color: C.sec, fontWeight: 300 }}>{designer.title}</span>
        </div>
      )}

      {/* Step header (non-email) */}
      {!cur.isEmail && (
        <React.Fragment>
          <div style={{ fontSize: 10.5, letterSpacing: 2.5, textTransform: "uppercase", color: C.gold, fontWeight: 500, marginBottom: 8 }}>
            Step {step + 1} of {total}
          </div>
          <h2 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 24, fontWeight: 400, lineHeight: 1.2, marginBottom: 6 }}>{cur.t}</h2>
          <p style={{ fontSize: 14, color: C.sec, fontWeight: 300, lineHeight: 1.55, marginBottom: 24 }}>{cur.s}</p>
        </React.Fragment>
      )}

      {/* Email step header */}
      {cur.isEmail && (
        <React.Fragment>
          {designer && (
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20, padding: "14px 16px", background: C.surf, borderRadius: 12 }}>
              <Avatar d={designer} size={44} />
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{designer.name} has your consultation ready</div>
                <div style={{ fontSize: 12, color: C.sec, fontWeight: 300 }}>{designer.title}</div>
              </div>
            </div>
          )}
          <div style={{ fontSize: 10.5, letterSpacing: 2.5, textTransform: "uppercase", color: C.gold, fontWeight: 500, marginBottom: 8 }}>Final step</div>
          <h2 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 24, fontWeight: 400, lineHeight: 1.2, marginBottom: 6 }}>Your consultation is built and waiting</h2>
          <p style={{ fontSize: 14, color: C.sec, fontWeight: 300, lineHeight: 1.55, marginBottom: 24 }}>
            Enter your info &mdash; your personalized report appears on screen in about 15 seconds. We'll also email a copy.
          </p>
        </React.Fragment>
      )}

      {/* Image-style options (style step) */}
      {cur.hasImg && cur.opts && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {cur.opts.map((o) => {
            const isSelected = sel === o.id;
            return (
            <Hov
              key={o.id}
              base={{ border: "1.5px solid " + (isSelected ? C.gold : C.bdrH), borderRadius: 12, cursor: "pointer", transition: "all 0.2s", background: isSelected ? C.goldBg : C.w, overflow: "hidden" }}
              hover={isSelected ? {} : { background: C.goldBg, transform: "translateY(-2px)" }}
              onClick={() => setAns({ ...ans, [cur.key]: o.id })}
            >
              <div style={{ background: C.surf, minHeight: 90, display: "flex", alignItems: "center", justifyContent: "center", borderBottom: "1px solid " + C.bdr, padding: 12 }}>
                <span style={{ fontSize: 10, color: C.tri, textAlign: "center" }}>{o.imgBrief}</span>
              </div>
              <div style={{ padding: "14px 14px 16px", textAlign: "center" }}>
                <div style={{ display: "flex", gap: 5, justifyContent: "center", marginBottom: 8 }}>
                  {o.dots.map((c, j) => (
                    <div key={j} style={{ width: 14, height: 14, borderRadius: "50%", background: c, border: "1px solid " + C.bdr }} />
                  ))}
                </div>
                <div style={{ fontSize: 13.5, fontWeight: 500, marginBottom: 2 }}>{o.l}</div>
                <div style={{ fontSize: 11.5, color: C.sec, fontWeight: 300, lineHeight: 1.35 }}>{o.s}</div>
              </div>
            </Hov>
            );
          })}
        </div>
      )}

      {/* Standard grid options */}
      {!cur.hasImg && !cur.isBH && cur.opts && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {cur.opts.map((o) => {
            const isSelected = sel === o.id;
            return (
            <Hov
              key={o.id}
              base={{ border: "1.5px solid " + (isSelected ? C.gold : C.bdrH), borderRadius: 12, padding: "18px 14px", cursor: "pointer", transition: "all 0.2s", background: isSelected ? C.goldBg : C.w, textAlign: "center" }}
              hover={isSelected ? {} : { background: C.goldBg, transform: "translateY(-2px)" }}
              onClick={() => setAns({ ...ans, [cur.key]: o.id })}
            >
              {cur.hasE && <span style={{ fontSize: 26, display: "block", marginBottom: 6 }}>{o.e}</span>}
              {cur.hasI && <span style={{ fontSize: 26, display: "block", marginBottom: 6 }}>{o.i}</span>}
              {cur.hasSw && (
                <div style={{ display: "flex", gap: 4, justifyContent: "center", marginBottom: 8 }}>
                  {o.sw.map((c, j) => (
                    <div key={j} style={{ width: 18, height: 18, borderRadius: "50%", background: c, border: "1px solid " + C.bdr }} />
                  ))}
                </div>
              )}
              <div style={{ fontSize: 13.5, fontWeight: 500, marginBottom: 2 }}>{o.l}</div>
              <div style={{ fontSize: 11.5, color: C.sec, fontWeight: 300, lineHeight: 1.35 }}>{o.s}</div>
            </Hov>
            );
          })}
        </div>
      )}

      {/* Floor color follow-up */}
      {cur.hasFloorColor && sel && (
        <div style={{ marginTop: 20 }}>
          <label style={{ fontSize: 13, fontWeight: 500, color: C.text, display: "block", marginBottom: 8 }}>And your floors &mdash; light, medium, or dark?</label>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10 }}>
            {FLOOR_COLORS.map((f) => {
              const isSelected = ans.floorColor === f.id;
              return (
              <Hov
                key={f.id}
                base={{ border: "1.5px solid " + (isSelected ? C.gold : C.bdrH), borderRadius: 10, padding: "12px 8px", cursor: "pointer", transition: "all 0.2s", background: isSelected ? C.goldBg : C.w, textAlign: "center" }}
                hover={isSelected ? {} : { background: C.goldBg }}
                onClick={() => setAns({ ...ans, floorColor: f.id })}
              >
                <div style={{ fontSize: 12.5, fontWeight: 500, marginBottom: 1 }}>{f.l}</div>
                <div style={{ fontSize: 10.5, color: C.sec, fontWeight: 300 }}>{f.s}</div>
              </Hov>
              );
            })}
          </div>
        </div>
      )}

      {/* Budget + household step */}
      {cur.isBH && (
        <div>
          <label style={{ fontSize: 13, fontWeight: 500, color: C.text, display: "block", marginBottom: 8 }}>What's your budget range?</label>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 24 }}>
            {BUDGETS.map((b) => {
              const isSelected = ans.budget === b.id;
              return (
              <Hov
                key={b.id}
                base={{ border: "1.5px solid " + (isSelected ? C.gold : C.bdrH), borderRadius: 12, padding: "16px 14px", cursor: "pointer", transition: "all 0.2s", background: isSelected ? C.goldBg : C.w, textAlign: "center" }}
                hover={isSelected ? {} : { background: C.goldBg, transform: "translateY(-2px)" }}
                onClick={() => setAns({ ...ans, budget: b.id })}
              >
                <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 2 }}>{b.l}</div>
                <div style={{ fontSize: 11.5, color: C.sec, fontWeight: 300 }}>{b.s}</div>
              </Hov>
              );
            })}
          </div>
          <label style={{ fontSize: 13, fontWeight: 500, color: C.text, display: "block", marginBottom: 8 }}>
            Who shares this room? <span style={{ fontWeight: 300, color: C.tri }}>(select all)</span>
          </label>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {HOUSEHOLD.map((h) => {
              const isSelected = ans.household.includes(h.id);
              return (
              <Hov
                key={h.id}
                base={{ border: "1.5px solid " + (isSelected ? C.gold : C.bdrH), borderRadius: 10, padding: "10px 16px", cursor: "pointer", transition: "all 0.2s", background: isSelected ? C.goldBg : C.w, display: "flex", alignItems: "center", gap: 6 }}
                hover={isSelected ? {} : { background: C.goldBg }}
                onClick={() => toggleHH(h.id)}
              >
                <span style={{ fontSize: 18 }}>{h.e}</span>
                <span style={{ fontSize: 13, fontWeight: 500 }}>{h.l}</span>
              </Hov>
              );
            })}
          </div>
          {ans.budget === "under150" && (
            <div style={{ background: C.goldBg, borderRadius: 8, padding: "12px 14px", marginTop: 18 }}>
              <div style={{ fontSize: 10, letterSpacing: 1.5, textTransform: "uppercase", color: C.gold, fontWeight: 500, marginBottom: 3 }}>Great news</div>
              <div style={{ fontSize: 12.5, color: C.sec, lineHeight: 1.55, fontWeight: 300 }}>
                Our clearance collection starts at $99 &mdash; same premium thickness. The natural beauty marks are what make each one truly one-of-a-kind.
              </div>
            </div>
          )}
        </div>
      )}

      {/* Room tips */}
      {cur.hasTips3 && sel && ROOM_TIPS[sel] && (
        <div style={{ background: C.goldBg, borderRadius: 10, padding: 16, marginTop: 18 }}>
          <div style={{ fontSize: 10, letterSpacing: 1.5, textTransform: "uppercase", color: C.gold, fontWeight: 500, marginBottom: 10 }}>
            3 design tips for your {ROOMS.find((r) => r.id === sel)?.l.toLowerCase()}
          </div>
          {ROOM_TIPS[sel].map((tip, i) => (
            <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 10, marginBottom: i < 2 ? 10 : 0 }}>
              <div style={{ width: 20, height: 20, borderRadius: "50%", background: C.w, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, color: C.gold, fontWeight: 600, flexShrink: 0, marginTop: 1 }}>
                {i + 1}
              </div>
              <div style={{ fontSize: 12.5, color: C.sec, lineHeight: 1.5, fontWeight: 300 }}>{tip}</div>
            </div>
          ))}
        </div>
      )}

      {/* Measure tips */}
      {cur.hasMeasure && sel && ans.room && MEASURE_TIPS[ans.room] && (
        <div style={{ background: C.surf, border: "1px solid " + C.bdr, borderRadius: 10, padding: 16, marginTop: 18 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginBottom: 8 }}>
            <span style={{ fontSize: 16 }}>{"\u{1F4CF}"}</span>
            <div style={{ fontSize: 12, letterSpacing: 1, textTransform: "uppercase", color: C.gold, fontWeight: 500 }}>{MEASURE_TIPS[ans.room].title}</div>
          </div>
          <div style={{ fontSize: 13, color: C.sec, lineHeight: 1.6, fontWeight: 300 }}>{MEASURE_TIPS[ans.room].text}</div>
        </div>
      )}

      {/* Testimonial on step 4 */}
      {step === 4 && (
        <div style={{ background: C.surf, borderRadius: 10, padding: "14px 16px", marginTop: 16, textAlign: "center" }}>
          <p style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 14.5, fontStyle: "italic", lineHeight: 1.55, color: C.text, marginBottom: 6 }}>
            "I was going back and forth for weeks. This quiz told me exactly what to get and where to put it. Ordered that night."
          </p>
          <cite style={{ fontSize: 11, color: C.tri, fontStyle: "normal" }}>&mdash; Sarah M., Austin, TX</cite>
        </div>
      )}

      {/* Photo + floor step */}
      {cur.isPhoto && (
        <div>
          <div style={{ marginBottom: 24 }}>
            <label style={{ fontSize: 13, fontWeight: 500, color: C.text, display: "block", marginBottom: 8 }}>What type of flooring?</label>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              {FLOOR_OPTS.map((f) => {
                const isSelected = ans.floor === f.id;
                return (
                <Hov
                  key={f.id}
                  base={{ border: "1.5px solid " + (isSelected ? C.gold : C.bdrH), borderRadius: 10, padding: "14px 12px", cursor: "pointer", transition: "all 0.2s", background: isSelected ? C.goldBg : C.w, textAlign: "center" }}
                  hover={isSelected ? {} : { background: C.goldBg }}
                  onClick={() => setAns({ ...ans, floor: f.id })}
                >
                  <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 1 }}>{f.l}</div>
                  <div style={{ fontSize: 11, color: C.sec, fontWeight: 300 }}>{f.s}</div>
                </Hov>
                );
              })}
            </div>
          </div>
          <div style={{ marginBottom: 24 }}>
            <label style={{ fontSize: 13, fontWeight: 500, color: C.text, display: "block", marginBottom: 6 }}>
              Anything else? <span style={{ fontWeight: 300, color: C.tri }}>(optional)</span>
            </label>
            <textarea
              value={photoNotes}
              onChange={(e) => setPhotoNotes(e.target.value)}
              placeholder="E.g., budget is firm, sofa is new, might change curtains..."
              style={{ fontSize: 13, padding: "11px 14px", border: "1px solid " + C.bdr, borderRadius: 8, background: C.w, color: C.text, fontWeight: 300, resize: "vertical", minHeight: 60, width: "100%", boxSizing: "border-box" }}
            />
          </div>
          <div style={{ borderTop: "1px solid " + C.bdr, paddingTop: 20 }}>
            <div style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: C.text }}>
                Upload a room photo{" "}
                <span style={{ fontSize: 11, fontWeight: 400, color: C.tri, background: C.surf, padding: "2px 8px", borderRadius: 4, marginLeft: 6 }}>Optional</span>
              </div>
              <div style={{ fontSize: 12, color: C.sec, fontWeight: 300, marginTop: 2 }}>
                Your consultation works great without one &mdash; a photo lets our trained virtual designer see your actual space.
              </div>
            </div>
            {!photo ? (
              <Hov
                base={{ border: "1.5px dashed " + C.bdr, borderRadius: 10, padding: 16, textAlign: "center", cursor: "pointer", transition: "all 0.2s", background: C.surf }}
                hover={{ borderColor: C.gold, background: C.goldBg }}
                onClick={() => fileRef.current?.click()}
              >
                <span style={{ fontSize: 20, display: "inline-block", marginRight: 8, opacity: 0.4 }}>{"\u{1F4F7}"}</span>
                <span style={{ fontSize: 13, color: C.sec, fontWeight: 300 }}>Tap to upload</span>
                <input ref={fileRef} type="file" accept="image/*" style={{ display: "none" }} onChange={(e) => handleFile(e.target.files[0])} />
              </Hov>
            ) : (
              <div>
                <img src={photo} style={{ width: "100%", borderRadius: 10, display: "block", marginBottom: 8, maxHeight: 180, objectFit: "cover" }} alt="Room" />
                <button onClick={() => { setPhoto(null); setPhotoData(null); }} style={{ background: "none", border: "none", color: C.sec, fontSize: 12, cursor: "pointer" }}>
                  &larr; Remove
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Email step */}
      {cur.isEmail && (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <label style={{ fontSize: 12, fontWeight: 500, color: C.sec }}>First name</label>
            <input type="text" value={fname} onChange={(e) => setFname(e.target.value)} placeholder="Your first name" style={{ fontSize: 14, padding: "11px 14px", border: "1px solid " + C.bdr, borderRadius: 8, background: C.w, color: C.text, fontWeight: 300 }} />
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <label style={{ fontSize: 12, fontWeight: 500, color: C.sec }}>Email address</label>
            <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="your@email.com" style={{ fontSize: 14, padding: "11px 14px", border: "1px solid " + C.bdr, borderRadius: 8, background: C.w, color: C.text, fontWeight: 300 }} />
          </div>
          <p style={{ fontSize: 11, color: C.tri, fontWeight: 300, lineHeight: 1.4 }}>
            We'll send your consultation plus design tips and exclusive offers. Unsubscribe anytime.
          </p>
        </div>
      )}

      {/* Nav buttons */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 24 }}>
        <button onClick={back} style={{ background: "none", border: "none", color: C.sec, fontSize: 13, cursor: "pointer", visibility: step > 0 ? "visible" : "hidden" }}>
          &larr; Back
        </button>
        <button
          style={bS(cur.isEmail ? !!email.trim() : canNext())}
          onClick={(cur.isEmail ? !!email.trim() : canNext()) ? next : undefined}
        >
          {cur.isEmail ? "Show my consultation \u2192" : "Continue \u2192"}
        </button>
      </div>
    </div>
  );
}

/* =============================================
   RESULTS
   ============================================= */
function Results({ data, onRestart }) {
  const [loading, setLoading] = useState(true);
  const [result, setResult] = useState("");
  const [error, setError] = useState(null);
  const [phase, setPhase] = useState(0);
  const called = useRef(false);
  const designer = data.designer || DESIGNERS.rachel;

  useEffect(() => {
    if (called.current) return;
    called.current = true;
    const timer = setInterval(() => setPhase((p) => Math.min(p + 1, PHASES.length - 1)), 2500);

    const hhStr = data.household?.map((h) => HOUSEHOLD.find((x) => x.id === h)?.l || h).join(", ") || "Adults";

    // Call our backend instead of Anthropic directly
    fetch("/api/consult", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        sessionId: SESSION_ID,
        email: data.email,
        name: data.name,
        room: g(ROOMS, data.room)?.l || data.room,
        style: g(STYLES, data.style)?.l || data.style,
        palette: g(PALETTES, data.palette)?.l || data.palette,
        floorColor: g(FLOOR_COLORS, data.floorColor)?.l || "Not specified",
        floor: data.floor || "hardwood",
        budget: g(BUDGETS, data.budget)?.l || "Not specified",
        household: hhStr,
        priority: g(PRIORITIES, data.priority)?.l || data.priority,
        size: g(SIZES, data.size)?.l || data.size,
        photoData: data.photoData || null,
        photoNotes: data.photoNotes || "",
        designer: { name: designer.name, title: designer.title },
      }),
    })
      .then((r) => {
        if (!r.ok) throw new Error("Server error");
        return r.json();
      })
      .then((d) => {
        clearInterval(timer);
        if (!d.result) throw new Error("Empty");
        setResult(d.result);
        setLoading(false);
        trackEvent("consultation_received", { durationMs: d.durationMs, model: d.model }, "results");

        // Klaviyo payload (log for now, integrate later)
        const kd = buildKlaviyoPayload(data);
        console.log("KLAVIYO_PAYLOAD:", JSON.stringify(kd, null, 2));
      })
      .catch((e) => {
        clearInterval(timer);
        setError(e.message);
        setLoading(false);
        trackEvent("consultation_error", { error: e.message }, "results");
      });

    return () => clearInterval(timer);
  }, []);

  const render = (text) =>
    text.split("\n").map((ln, i) => {
      if (ln.startsWith("**") && ln.endsWith("**")) {
        const clean = ln.replace(/\*\*/g, "");
        const nm = clean.match(/^(\d+)\.\s*(.*)/);
        if (nm) {
          return (
            <div key={i} style={{ marginTop: i === 0 ? 0 : 28, marginBottom: 10, paddingTop: i === 0 ? 0 : 20, borderTop: i === 0 ? "none" : "1px solid " + C.bdr }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ width: 24, height: 24, borderRadius: "50%", background: C.goldBg, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, color: C.gold, fontWeight: 600, flexShrink: 0 }}>{nm[1]}</div>
                <h3 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 18, fontWeight: 500, color: C.text }}>{nm[2]}</h3>
              </div>
            </div>
          );
        }
        return <h3 key={i} style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 18, fontWeight: 500, color: C.text, margin: "24px 0 8px" }}>{clean}</h3>;
      }

      if (ln.trim().startsWith("\u2192") && /\[([^\]]+)\]\(([^)]+)\)/.test(ln)) {
        const m = ln.match(/\[([^\]]+)\]\(([^)]+)\)/);
        const after = ln.slice(ln.indexOf(")") + 1).replace(/^\s*[\u2014\u2013\-]\s*/, "");
        return (
          <a key={i} href={m[2]} target="_blank" rel="noopener noreferrer" style={{ display: "block", border: "1px solid " + C.bdr, borderRadius: 8, padding: "12px 14px", marginBottom: 6, textDecoration: "none", color: "inherit", transition: "border-color 0.2s" }}>
            <div style={{ fontSize: 13.5, fontWeight: 500, color: C.gold, marginBottom: after ? 2 : 0 }}>{m[1]} &rarr;</div>
            {after && <div style={{ fontSize: 12.5, color: C.sec, fontWeight: 300, lineHeight: 1.45 }}>{after}</div>}
          </a>
        );
      }

      if (/\[([^\]]+)\]\(([^)]+)\)/.test(ln)) {
        const p = [];
        let last = 0;
        ln.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (m, t, u, o) => {
          if (o > last) p.push(ln.slice(last, o));
          p.push(<a key={o} href={u} style={{ color: C.gold, fontWeight: 500, textDecoration: "none" }} target="_blank" rel="noopener noreferrer">{t}</a>);
          last = o + m.length;
        });
        if (last < ln.length) p.push(ln.slice(last));
        return <p key={i} style={{ fontSize: 14, color: C.sec, lineHeight: 1.7, fontWeight: 300, marginBottom: 5 }}>{p}</p>;
      }

      if (ln.includes("**")) {
        const p = ln.split(/\*\*/).map((s, j) => (j % 2 ? <strong key={j} style={{ color: C.text, fontWeight: 500 }}>{s}</strong> : s));
        return <p key={i} style={{ fontSize: 14, color: C.sec, lineHeight: 1.7, fontWeight: 300, marginBottom: 5 }}>{p}</p>;
      }

      if (/^\d+\.\s/.test(ln.trim()) && !ln.startsWith("**")) {
        const nm = ln.trim().match(/^(\d+)\.\s*(.*)/);
        return (
          <div key={i} style={{ display: "flex", alignItems: "flex-start", gap: 8, marginBottom: 6 }}>
            <div style={{ width: 20, height: 20, borderRadius: "50%", background: C.goldBg, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, color: C.gold, fontWeight: 600, flexShrink: 0, marginTop: 2 }}>{nm[1]}</div>
            <p style={{ fontSize: 14, color: C.sec, lineHeight: 1.65, fontWeight: 300 }}>{nm[2]}</p>
          </div>
        );
      }

      if (ln.trim() === "") return <div key={i} style={{ height: 6 }} />;

      if (ln.trim().startsWith("- ") || ln.trim().startsWith("\u2022 ")) {
        return <p key={i} style={{ fontSize: 14, color: C.sec, lineHeight: 1.7, fontWeight: 300, marginBottom: 4, paddingLeft: 12 }}>{"\u2022"} {ln.trim().slice(2)}</p>;
      }

      return <p key={i} style={{ fontSize: 14, color: C.sec, lineHeight: 1.7, fontWeight: 300, marginBottom: 5 }}>{ln}</p>;
    });

  if (loading) {
    return (
      <div style={{ padding: "60px 24px", textAlign: "center" }}>
        <div style={{ display: "flex", justifyContent: "center", marginBottom: 14 }}>
          <Avatar d={designer} size={52} />
        </div>
        <div style={{ width: 32, height: 32, border: "3px solid " + C.bdr, borderTopColor: C.gold, borderRadius: "50%", animation: "spin 0.8s linear infinite", margin: "0 auto 16px" }} />
        <div style={{ fontSize: 15, color: C.sec, fontWeight: 300 }}>{designer.name} is preparing your consultation...</div>
        <div style={{ fontSize: 12, color: C.tri, fontWeight: 300, marginTop: 6 }}>{PHASES[phase]}</div>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ padding: "48px 24px" }}>
        <h2 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 24, fontWeight: 400, marginBottom: 8 }}>Something went wrong</h2>
        <p style={{ fontSize: 14, color: C.sec, fontWeight: 300, lineHeight: 1.6, marginBottom: 16 }}>
          Call <a href="tel:8006512747" style={{ color: C.gold, fontWeight: 500, textDecoration: "none" }}>800-651-2747</a> or email{" "}
          <a href="mailto:Sales@CowhidesDirect.com" style={{ color: C.gold, fontWeight: 500, textDecoration: "none" }}>Sales@CowhidesDirect.com</a>.
        </p>
        <button onClick={onRestart} style={{ background: "none", border: "1px solid " + C.gold, color: C.gold, borderRadius: 4, padding: "11px 24px", fontSize: 13, fontWeight: 500, cursor: "pointer" }}>
          Try again
        </button>
      </div>
    );
  }

  return (
    <div style={{ padding: "36px 24px" }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 20 }}>
        <Avatar d={designer} size={40} />
        <div>
          <div style={{ fontSize: 10, letterSpacing: 2, textTransform: "uppercase", color: C.gold, fontWeight: 500 }}>Your design consultation</div>
          <div style={{ fontSize: 12, color: C.sec, fontWeight: 300 }}>By {designer.name} &middot; Cowhides Direct</div>
        </div>
      </div>
      <h2 style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 24, fontWeight: 400, lineHeight: 1.2, marginBottom: 20 }}>
        {data.name ? data.name + ", your design plan is ready" : "Your design plan is ready"}
      </h2>

      {/* Report */}
      <div style={{ border: "1px solid " + C.bdr, borderRadius: 12, padding: "20px 18px", marginBottom: 24 }}>
        {render(result)}
      </div>

      {/* Trust */}
      <div style={{ background: C.goldBg, borderRadius: 8, padding: "12px 14px", marginBottom: 24 }}>
        <div style={{ fontSize: 13, color: C.sec, lineHeight: 1.55, fontWeight: 300 }}>
          Every rug is individually photographed &mdash; the rug in the photo is the rug at your door. Free 5-year stain protection on orders $199+. 30-day easy returns.
        </div>
      </div>

      {/* CTA */}
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 28 }}>
        <a href="https://www.cowhidesdirect.com/pages/cowhide-rugs" target="_blank" rel="noopener noreferrer"
          style={{ background: C.gold, color: "#fff", borderRadius: 4, padding: "12px 32px", fontSize: 13, fontWeight: 500, textDecoration: "none" }}
          onClick={() => trackEvent("cta_click", { button: "browse_rugs" }, "results")}
        >
          Browse all cowhide rugs &rarr;
        </a>
        <button onClick={onRestart} style={{ background: "none", border: "1px solid " + C.bdr, color: C.sec, borderRadius: 4, padding: "11px 20px", fontSize: 13, fontWeight: 400, cursor: "pointer" }}>
          Start over
        </button>
      </div>

      <div style={{ textAlign: "center", marginBottom: 28 }}><Stars /></div>

      {/* Contact */}
      <div style={{ border: "1px solid " + C.bdr, borderRadius: 12, padding: "20px 18px" }}>
        <div style={{ fontFamily: "'Cormorant Garamond',serif", fontSize: 17, fontWeight: 500, marginBottom: 4 }}>Still have questions?</div>
        <p style={{ fontSize: 12.5, color: C.sec, fontWeight: 300, lineHeight: 1.5, marginBottom: 14 }}>Our team is here 7 days a week.</p>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <a href="tel:8006512747" style={{ display: "flex", alignItems: "center", gap: 10, textDecoration: "none", color: "inherit" }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.goldBg, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.gold} strokeWidth="1.5"><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.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z" /></svg>
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: C.gold }}>800-651-2747</div>
              <div style={{ fontSize: 11, color: C.tri, fontWeight: 300 }}>Mon-Sun 9am-6pm EST</div>
            </div>
          </a>
          <a href="mailto:Sales@CowhidesDirect.com" style={{ display: "flex", alignItems: "center", gap: 10, textDecoration: "none", color: "inherit" }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.goldBg, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.gold} strokeWidth="1.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" /><polyline points="22,6 12,13 2,6" /></svg>
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: C.gold }}>Sales@CowhidesDirect.com</div>
              <div style={{ fontSize: 11, color: C.tri, fontWeight: 300 }}>We respond within hours</div>
            </div>
          </a>
          <a href="https://www.cowhidesdirect.com/pages/contact-us" target="_blank" rel="noopener noreferrer" style={{ display: "flex", alignItems: "center", gap: 10, textDecoration: "none", color: "inherit" }}>
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: C.goldBg, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={C.gold} strokeWidth="1.5"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" /></svg>
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500, color: C.gold }}>Contact form</div>
              <div style={{ fontSize: 11, color: C.tri, fontWeight: 300 }}>Send us a message</div>
            </div>
          </a>
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "center", gap: 28, flexWrap: "wrap", paddingTop: 20, marginTop: 28, borderTop: "1px solid " + C.bdr }}>
        {[["25+", "years"], ["100K+", "homes"], ["Same-day", "shipping"], ["Free", "protection"]].map(([v, l], i) => (
          <div key={i} style={{ textAlign: "center" }}>
            <span style={{ display: "block", fontSize: 14, fontWeight: 500, marginBottom: 1 }}>{v}</span>
            <span style={{ fontSize: 10, color: C.tri }}>{l}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* =============================================
   APP ROOT
   ============================================= */
function App() {
  const [view, setView] = useState("landing");
  const [data, setData] = useState(null);

  return (
    <div style={{ maxWidth: 720, margin: "0 auto", color: C.text, minHeight: "100vh" }}>
      {view === "landing" && <Landing onStart={() => setView("quiz")} />}
      {view === "quiz" && <QuizFlow onComplete={(d) => { setData(d); setView("results"); }} />}
      {view === "results" && <Results data={data} onRestart={() => { setData(null); setView("landing"); }} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
