/* Yan's Cakes — immersive "step into the shop" hero.
   Drag the storefront to look around; tap a hotspot or category to browse. */
function ImmersiveHero({ onAdd, onScrollToShop, onNav }) {
  const { Button, Eyebrow, IconButton } = window.DorDesignSystem_396f3e;
  const { products, categories, hotspots, byId, fmt } = window.YANS;

  const [pan, setPan] = React.useState({ x: 0, y: 0 });
  const [parallax, setParallax] = React.useState({ x: 0, y: 0 });
  const [activeCat, setActiveCat] = React.useState("Swiss Rolls");
  const [popId, setPopId] = React.useState("sr-pandan");
  const drag = React.useRef(null);
  const RANGE_X = 90, RANGE_Y = 55;

  const clamp = (v, m) => Math.max(-m, Math.min(m, v));
  const onDown = (e) => { drag.current = { sx: e.clientX, sy: e.clientY, px: pan.x, py: pan.y }; };
  const onMove = (e) => {
    if (drag.current) {
      const d = drag.current;
      setPan({ x: clamp(d.px + (e.clientX - d.sx), RANGE_X), y: clamp(d.py + (e.clientY - d.sy), RANGE_Y) });
    } else {
      const r = e.currentTarget.getBoundingClientRect();
      const nx = (e.clientX - r.left) / r.width - 0.5;
      const ny = (e.clientY - r.top) / r.height - 0.5;
      setParallax({ x: -nx * 24, y: -ny * 16 });
    }
  };
  const endDrag = () => { drag.current = null; };
  const nudge = (dx, dy) => setPan((p) => ({ x: clamp(p.x + dx, RANGE_X), y: clamp(p.y + dy, RANGE_Y) }));

  const tx = pan.x + parallax.x, ty = pan.y + parallax.y;
  const railArrow = { flex: "none", width: 38, height: 38, borderRadius: "50%", border: "1px solid var(--border-default)", background: "var(--surface-raised)", color: "var(--accent)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 18 };
  const pop = byId(popId);
  const goCat = (cat) => onNav ? onNav({ s: "category", cat }) : onScrollToShop();
  const goProduct = (p) => onNav ? onNav({ s: "product", p }) : onScrollToShop();
  const popCatItems = pop ? products.filter((p) => p.cat === pop.cat) : [];
  const cyclePop = (dir) => { if (!pop) return; const i = popCatItems.findIndex((p) => p.id === pop.id); const n = (i + dir + popCatItems.length) % popCatItems.length; setPopId(popCatItems[n].id); };
  const popNav = (side) => ({ position: "absolute", [side]: 8, top: "50%", transform: "translateY(-50%)", width: 36, height: 36, borderRadius: "50%", border: 0, background: "rgba(252,250,246,0.92)", color: "var(--chocolate)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 17, boxShadow: "var(--shadow-md)" });
  // Fixed featured selection (no category filtering) — a few rolls, cheesecake & egg tart.
  const featured = ["sr-sugar", "sr-pandan", "sr-oreo", "c-cotton", "t-egg-box"].map(byId);
  const railRef = React.useRef(null);
  const scrollRail = (dir) => railRef.current && railRef.current.scrollBy({ left: dir * 280, behavior: "smooth" });

  const pickCat = (name) => {
    setActiveCat(name);
    const first = products.find((p) => p.cat === name);
    if (first) setPopId(first.id);
    if (railRef.current) railRef.current.scrollTo({ left: 0 });
  };

  return (
    <section style={{ position: "relative", height: "100vh", minHeight: 720, overflow: "hidden", background: "var(--chocolate)" }}>
      {/* ---- draggable scene (straight-on storefront, gentle overscan for look-around) ---- */}
      <div
        onPointerDown={onDown} onPointerMove={onMove} onPointerUp={endDrag} onPointerLeave={endDrag}
        style={{ position: "absolute", inset: 0, overflow: "hidden", cursor: drag.current ? "grabbing" : "grab", touchAction: "none" }}
      >
        <div style={{ position: "absolute", width: "118%", height: "118%", left: "-9%", top: "-9%", transformOrigin: "center",
          transform: `translate(${tx}px, ${ty}px)`, transition: drag.current ? "none" : "transform .35s var(--ease-standard)" }}>
          <img src="photos/storefront.jpg" alt="Yan's Cakes storefront" draggable="false"
            style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", filter: "saturate(1.06) contrast(1.03) brightness(1.02)", userSelect: "none" }} />
          {/* mini-photo hotspots — anchored to the photo; open category + jump to the store */}
          {hotspots.map((h) => (
            <button key={h.cat} onClick={() => goCat(h.cat)} onPointerDown={(e) => e.stopPropagation()} aria-label={"Shop " + h.cat} title={h.cat}
              onMouseEnter={(e) => { e.currentTarget.style.transform = "translate(-50%,-50%) scale(1.1)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = "translate(-50%,-50%) scale(1)"; }}
              style={{ position: "absolute", left: `${h.x}%`, top: `${h.y}%`, transform: "translate(-50%,-50%)",
                width: 64, height: 64, borderRadius: "50%", cursor: "pointer", padding: 0, border: "3px solid #fff", background: "#fff",
                boxShadow: "0 6px 18px rgba(33,28,24,.5)", animation: "yansPulse 2.6s var(--ease-standard) infinite", transition: "transform .2s var(--ease-standard)", touchAction: "manipulation" }}>
              <img src={h.img} alt="" draggable="false" style={{ width: "100%", height: "100%", objectFit: "cover", borderRadius: "50%", pointerEvents: "none" }} />
              <span style={{ position: "absolute", right: -4, bottom: -4, width: 24, height: 24, borderRadius: "50%", background: "var(--gold)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", border: "2px solid #fff", pointerEvents: "none" }}>
                <i className="ph-light ph-plus" style={{ fontSize: 14 }} />
              </span>
            </button>
          ))}
        </div>
        {/* legibility gradient stays fixed (not panned) */}
        <div style={{ position: "absolute", inset: 0, pointerEvents: "none",
          background: "linear-gradient(180deg, rgba(94,26,19,0.20) 0%, rgba(94,26,19,0) 28%, rgba(33,28,24,0) 60%, rgba(33,28,24,.5) 100%)" }} />
      </div>

      {/* ---- left category panel (capped so it never collides with the bottom dock) ---- */}
      <div style={{ position: "absolute", left: 36, top: 96, width: 234, zIndex: 50,
        maxHeight: "calc(100% - 200px)", overflow: "visible", scrollbarWidth: "none",
        background: "var(--surface-card)", backdropFilter: "blur(10px)", WebkitBackdropFilter: "blur(10px)",
        border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", padding: 20 }}>
        <div style={{ fontFamily: "var(--font-body)", fontSize: "var(--text-eyebrow)", fontWeight: 800, letterSpacing: "0.24em", textTransform: "uppercase", color: "#5c1a14", marginBottom: 14 }}>Explore our collection</div>
        <div style={{ height: 1, background: "var(--hairline-gold)", marginBottom: 14 }} />
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {categories.map((c) => {
            const on = c.name === activeCat;
            return (
              <button key={c.name} onClick={() => pickCat(c.name)}
                onMouseEnter={(e) => { if (!on) e.currentTarget.style.background = "var(--champagne)"; }}
                onMouseLeave={(e) => { if (!on) e.currentTarget.style.background = "transparent"; }}
                style={{ display: "flex", alignItems: "center", gap: 12, padding: "7px 10px", border: 0, borderRadius: "var(--radius-md)",
                  background: on ? "var(--accent-soft)" : "transparent", cursor: "pointer", textAlign: "left", transition: "background .15s" }}>
                <CatIcon type={c.svg} size={24} color={on ? "var(--accent)" : "var(--gold-deep)"} />
                <span style={{ fontFamily: "var(--font-display)", fontSize: 20, fontWeight: 500, color: on ? "var(--accent)" : "var(--text-primary)" }}>{c.name}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* ---- product popover (browse within category; Shop → category, Details → product) ---- */}
      {pop && (
        <div style={{ position: "absolute", right: 36, top: 96, width: 344, zIndex: 55, maxHeight: "calc(100% - 210px)", overflowY: "auto", scrollbarWidth: "none",
          background: "rgba(252,250,246,0.97)", backdropFilter: "blur(10px)", WebkitBackdropFilter: "blur(10px)",
          border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", padding: 18 }}>
          <button onClick={() => setPopId(null)} aria-label="Close" style={{ position: "absolute", top: 14, right: 14, width: 32, height: 32, borderRadius: "50%", border: 0, background: "rgba(33,28,24,.5)", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 3 }}>
            <i className="ph-light ph-x" style={{ fontSize: 16 }} />
          </button>
          <div style={{ position: "relative", height: 210, borderRadius: "var(--radius-md)", overflow: "hidden", marginBottom: 14 }}>
            <img src={pop.img} alt={pop.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
            <button onClick={() => cyclePop(-1)} aria-label="Previous item" style={popNav("left")}><i className="ph-light ph-caret-left" /></button>
            <button onClick={() => cyclePop(1)} aria-label="Next item" style={popNav("right")}><i className="ph-light ph-caret-right" /></button>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
            <h3 style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 26, color: "var(--text-primary)", lineHeight: 1.1 }}>{pop.name}</h3>
            <span style={{ fontFamily: "var(--font-display)", fontSize: 24, color: "var(--gold-deep)", whiteSpace: "nowrap" }}>{fmt(pop.price)}</span>
          </div>
          <p style={{ margin: "9px 0 16px", fontFamily: "var(--font-body)", fontSize: 14, lineHeight: 1.55, color: "var(--text-body)" }}>{pop.desc}</p>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={() => onAdd(pop)} title="Add to cart" aria-label="Add to cart" style={{ flex: 1, height: 48, border: 0, borderRadius: "var(--radius-md)", background: "var(--accent)", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", gap: 8, fontFamily: "var(--font-body)", fontSize: 14, fontWeight: 700 }}>
              <i className="ph-light ph-shopping-cart-simple" style={{ fontSize: 20 }} /> Add to cart
            </button>
            <button onClick={() => goProduct(pop)} title="View details" aria-label="View details" style={{ flex: "none", width: 48, height: 48, border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", background: "transparent", color: "var(--text-primary)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <i className="ph-light ph-arrow-up-right" style={{ fontSize: 20 }} />
            </button>
          </div>
        </div>
      )}

      {/* ---- bottom dock: nav pad · featured rail · visit card ---- */}
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 74, zIndex: 30, padding: "0 36px",
        display: "flex", alignItems: "flex-end", gap: 18 }}>
        {/* nav pad */}
        <div style={{ flex: "none", display: "flex", flexDirection: "column", alignItems: "center", gap: 5 }}>
          <div style={{ position: "relative", width: 74, height: 74, borderRadius: "50%", background: "rgba(252,250,246,0.9)", border: "1px solid var(--border-subtle)", boxShadow: "var(--shadow-md)" }}>
            <PadBtn pos={{ top: 4, left: "50%", transform: "translateX(-50%)" }} icon="ph-caret-up" onClick={() => nudge(0, 40)} />
            <PadBtn pos={{ bottom: 4, left: "50%", transform: "translateX(-50%)" }} icon="ph-caret-down" onClick={() => nudge(0, -40)} />
            <PadBtn pos={{ left: 4, top: "50%", transform: "translateY(-50%)" }} icon="ph-caret-left" onClick={() => nudge(60, 0)} />
            <PadBtn pos={{ right: 4, top: "50%", transform: "translateY(-50%)" }} icon="ph-caret-right" onClick={() => nudge(-60, 0)} />
            <button onClick={() => setPan({ x: 0, y: 0 })} aria-label="Recenter" style={{ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%,-50%)", width: 18, height: 18, borderRadius: "50%", border: "1.5px solid var(--gold)", background: "transparent", cursor: "pointer" }} />
          </div>
          <span style={{ fontFamily: "var(--font-body)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.04em", color: "var(--ivory)", textShadow: "0 1px 4px rgba(0,0,0,.5)", textAlign: "center", lineHeight: 1.25 }}>Drag to<br />look around</span>
        </div>

        {/* featured rail removed — browsing now lives in the product popover */}
        <div style={{ flex: 1 }} />

        {/* visit card */}
        <div style={{ flex: "none", width: 344, background: "var(--surface-card)", backdropFilter: "blur(10px)", WebkitBackdropFilter: "blur(10px)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-xl)", padding: 14, display: "flex", gap: 13 }}>
          <div style={{ width: 64, height: 64, borderRadius: "var(--radius-md)", overflow: "hidden", flex: "none" }}>
            <img src="photos/storefront.jpg" alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          </div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--gold-deep)" }}>Visit us</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 19, color: "var(--text-primary)", lineHeight: 1.12, margin: "2px 0 3px" }}>Yan&rsquo;s Cakes, #01-137</div>
            <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--text-secondary)", lineHeight: 1.35 }}>Open daily · 7am–7pm</div>
            <a href="#" onClick={(e) => e.preventDefault()} style={{ fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 600, color: "var(--text-link)", display: "inline-flex", alignItems: "center", gap: 4, marginTop: 5 }}>
              <i className="ph-light ph-map-pin" /> Directions
            </a>
          </div>
        </div>
      </div>

      {/* ---- value bar (signature red → maroon) ---- */}
      <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, zIndex: 40, background: "linear-gradient(0deg, #7d1f17, #a8312a)" }}>
        <div style={{ maxWidth: 1500, margin: "0 auto", padding: "12px 36px", display: "flex", alignItems: "center", justifyContent: "center", gap: 56 }}>
          <Val icon="ph-light ph-truck" head="Free Delivery" sub="On Orders Above $60" />
          <Val icon="ph-light ph-gift" head="For Every Occasion" sub="Birthdays, Gifting & Festive Seasons" />
          <Val icon="ph-light ph-seal-check" head="Freshly Handcrafted" sub="Baked Daily In Small Batches" />
        </div>
      </div>
    </section>
  );
}

/* Hand-drawn-style line icons for the category list (red/maroon to match the brand). */
function CatIcon({ type, size = 22, color = "currentColor" }) {
  const c = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: color, strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" };
  const paths = {
    cake: <g><path d="M4 20h16v-6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2z" /><path d="M4 15.5c1.3 1.4 2.7 1.4 4 0s2.7-1.4 4 0 2.7 1.4 4 0 2.7-1.4 4 0" /><path d="M12 12V7.5" /><circle cx="12" cy="5.6" r="1.1" /></g>,
    roll: <g><circle cx="12" cy="12" r="8.5" /><path d="M12 4.2A7.8 7.8 0 0 1 19.8 12A6 6 0 0 1 12 17.6A4.1 4.1 0 0 1 8 12A2.4 2.4 0 0 1 12 9.7" /></g>,
    cheesecake: <g><path d="M12 5.5 L20 18.5 L4 18.5 Z" /><path d="M4.7 16 H19.3" /><circle cx="12" cy="11" r="1" fill={color} stroke="none" /></g>,
    tart: <g><circle cx="12" cy="12" r="8.4" /><circle cx="12" cy="12" r="4.8" /><path d="M12 3.6v3M12 17.4v3M3.6 12h3M17.4 12h3M6 6l2.1 2.1M18 6l-2.1 2.1M6 18l2.1-2.1M18 18l-2.1-2.1" /></g>,
    bread: <g><path d="M4 14a8 4.5 0 0 1 16 0v2.5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1z" /><path d="M9 11l-1.2 4M12.3 10.4l-1.2 4.6M15.5 11l-1.2 4" /></g>,
    cookie: <g><circle cx="12" cy="12" r="8.2" /><circle cx="9.3" cy="10" r="0.9" fill={color} stroke="none" /><circle cx="14.2" cy="9.4" r="0.9" fill={color} stroke="none" /><circle cx="15.2" cy="13.8" r="0.9" fill={color} stroke="none" /><circle cx="10" cy="14.6" r="0.9" fill={color} stroke="none" /><circle cx="12.6" cy="12" r="0.7" fill={color} stroke="none" /></g>,
  };
  return <svg {...c}>{paths[type] || paths.cookie}</svg>;
}

function PadBtn({ pos, icon, onClick }) {
  return (
    <button onClick={onClick} style={{ position: "absolute", ...pos, width: 26, height: 26, border: 0, background: "transparent", color: "var(--taupe-deep)", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
      <i className={"ph-light " + icon} style={{ fontSize: 17 }} />
    </button>
  );
}

function Val({ icon, head, sub }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <i className={icon} style={{ fontSize: 26, color: "var(--gold-light)" }} />
      <div>
        <div style={{ fontFamily: "var(--font-body)", fontSize: 13, fontWeight: 700, color: "var(--ivory)", letterSpacing: "0.02em" }}>{head}</div>
        <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--text-on-dark-muted)" }}>{sub}</div>
      </div>
    </div>
  );
}

window.ImmersiveHero = ImmersiveHero;
