/* ============================================================
   FRUTA FRESCA — Shared components → window
   ============================================================ */
const { useState, useEffect, useRef, useContext, createContext } = React;
window.AppContext = window.AppContext || createContext(null);
const useApp = () => useContext(window.AppContext);
function useIsDesktop(bp = 860) {
  const [d, setD] = useState(typeof window !== "undefined" ? window.innerWidth >= bp : true);
  useEffect(() => {
    const f = () => setD(window.innerWidth >= bp);
    window.addEventListener("resize", f);
    return () => window.removeEventListener("resize", f);
  }, [bp]);
  return d;
}

/* ---------------- Icons ---------------- */
const P = {
  search: "M11 19a8 8 0 1 1 0-16 8 8 0 0 1 0 16Zm10 2-4.3-4.3",
  cart: "M6 6h15l-1.5 9h-12L5 3H2",
  user: "M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm-7 8a7 7 0 0 1 14 0",
  heart: "M12 21s-8-5.2-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 10c0 5.8-8 11-8 11Z",
  plus: "M12 5v14M5 12h14", minus: "M5 12h14",
  check: "M20 6 9 17l-5-5", chevronD: "M6 9l6 6 6-6", chevronR: "M9 6l6 6-6 6",
  chevronL: "M15 6l-6 6 6 6", arrowR: "M5 12h14M13 6l6 6-6 6",
  menu: "M4 7h16M4 12h16M4 17h16", close: "M6 6l12 12M18 6 6 18",
  mappin: "M12 22s7-5.5 7-12a7 7 0 1 0-14 0c0 6.5 7 12 7 12Z|M12 10a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",
  truck: "M3 6h11v9H3zM14 9h4l3 3v3h-7zM7 18.5A1.5 1.5 0 1 0 7 15a1.5 1.5 0 0 0 0 3.5ZM18 18.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z",
  shield: "M12 3l7 3v5c0 5-3.5 8-7 10-3.5-2-7-5-7-10V6l7-3Z|M9 12l2 2 4-4",
  leaf: "M5 21c0-9 5-14 14-15 0 9-5 14-14 15ZM5 21c2-5 5-8 9-10",
  snowflake: "M12 2v20M4 6l16 12M20 6 4 18M2 12h20",
  gift: "M20 12v9H4v-9M2 7h20v5H2zM12 7V3M12 7c-3 0-4-1.5-4-3s3-1 4 3Zm0 0c3 0 4-1.5 4-3s-3-1-4 3Z",
  calendar: "M3 5h18v16H3zM3 9h18M8 3v4M16 3v4",
  instagram: "M4 8a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4z|M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z|M17.5 6.5h.01",
  play: "M8 5v14l11-7z", pause: "M7 5v14M17 5v14",
  whatsapp: "M12 2a10 10 0 0 0-8.5 15.2L2 22l4.9-1.4A10 10 0 1 0 12 2Z",
  sparkle: "M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z",
  sprout: "M12 22V11M12 11c0-3 2-5 6-5 0 3-2 5-6 5Zm0 0C12 8 10 6 6 6c0 3 2 5 6 5Z",
  award: "M12 15a5 5 0 1 0 0-10 5 5 0 0 0 0 10Zm-3 .5L7 22l5-2 5 2-2-6.5",
  clock: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM12 7v5l3 2",
  phone: "M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L20 13l-1 4-2 1A16 16 0 0 1 4 6z",
  mail: "M3 6h18v12H3zM3 7l9 6 9-6",
  filter: "M3 5h18M6 12h12M10 19h4", star: "M12 3l2.6 5.6 6 .7-4.4 4.1 1.2 6L12 16.8 6.6 19.4l1.2-6L3.4 9.3l6-.7z",
  bag: "M6 7h12l-1 14H7zM9 7a3 3 0 0 1 6 0",
  mute: "M11 5 6 9H2v6h4l5 4V5z|M22 9l-6 6M16 9l6 6",
  sound: "M11 5 6 9H2v6h4l5 4V5z|M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13",
};
function Icon({ name, size = 20, stroke = 2, fill = "none", className = "", style = {} }) {
  const d = P[name] || "";
  const filled = name === "star";
  return (
    <svg className={className} width={size} height={size} viewBox="0 0 24 24"
      fill={filled ? "currentColor" : fill} stroke={filled ? "none" : "currentColor"}
      strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={style} aria-hidden="true">
      {d.split("|").map((seg, i) => <path key={i} d={seg} />)}
    </svg>
  );
}

/* ---------------- Logo ---------------- */
function Logo({ light = false, size = 18, stacked = false }) {
  // Header / light backgrounds: the official brand logo (green-on-white art).
  // mix-blend-mode: multiply drops the white so it sits cleanly on the off-white header.
  if (!light) {
    return (
      <img src="img/logo-header.png" alt="Fruta Fresca"
        style={{ height: 54, width: "auto", display: "block", mixBlendMode: "multiply" }} />
    );
  }
  // Footer / dark backgrounds: cream-recoloured official logo (transparent), so it sits on the green.
  return (
    <img src="img/logo-footer.png" alt="Fruta Fresca"
      style={{ height: 60, width: "auto", display: "block" }} />
  );
}

/* ---------------- Stars ---------------- */
function Stars({ value = 5, size = 15 }) {
  return (
    <span className="stars" role="img" aria-label={`${value} out of 5 stars`}>
      {[0, 1, 2, 3, 4].map((i) => (
        <Icon key={i} name="star" size={size}
          style={{ color: i < Math.round(value) ? "var(--citrus)" : "var(--border)" }} />
      ))}
    </span>
  );
}

/* ---------------- Season badge ---------------- */
function SeasonBadge({ season }) {
  const map = {
    "In season": "badge--season", "Limited": "badge--limited",
    "Pre-order": "badge--preorder", "Fresh stock": "badge--instock",
  };
  return <span className={`badge ${map[season] || "badge--instock"}`}>{season}</span>;
}

/* ---------------- Product card ---------------- */
function ProductCard({ p }) {
  const { go, addToCart, toggleWish, wish } = useApp();
  const [added, setAdded] = useState(false);
  const liked = wish.includes(p.id);
  const add = (e) => {
    e.stopPropagation();
    addToCart(p, 1);
    setAdded(true);
    setTimeout(() => setAdded(false), 1100);
  };
  return (
    <article className="product-card" onClick={() => go("pdp", { id: p.id })}
      tabIndex={0} role="button" aria-label={p.name}
      onKeyDown={(e) => e.key === "Enter" && go("pdp", { id: p.id })}>
      <div className="pc-media">
        <img src={FF.img(p.img, 500)} alt={p.name} loading="lazy" />
        <div className="pc-badges">
          <SeasonBadge season={p.season} />
          {p.organic && <span className="badge badge--organic">Organic</span>}
        </div>
        <span className="badge badge--origin pc-origin-badge">{p.origins[0]}</span>
        <button className="pc-fav" aria-label="Save" onClick={(e) => { e.stopPropagation(); toggleWish(p.id); }}>
          <Icon name="heart" size={17} fill={liked ? "var(--berry)" : "none"}
            style={{ color: liked ? "var(--berry)" : "var(--ink)" }} stroke={1.8} />
        </button>
      </div>
      <div className="pc-body">
        <div className="pc-origin">{p.grade}</div>
        <h3 className="pc-title">{p.name}</h3>
        <div className="pc-foot">
          <div>
            <span className="pc-price tabnum">{p.priceFrom ? "From " : ""}{FF.rupee(p.price)}</span>{" "}
            <span className="pc-unit">{p.unit}</span>
          </div>
          <button className={`pc-add${added ? " added" : ""}`} onClick={add}
            aria-label={`Add ${p.name} to cart`}>
            <Icon name={added ? "check" : "plus"} size={18} stroke={2.4} />
          </button>
        </div>
      </div>
    </article>
  );
}

/* ---------------- Pincode widget ---------------- */
function Pincode({ compact = false }) {
  const { pincode, setPincode } = useApp();
  const [val, setVal] = useState(pincode || "");
  const [state, setState] = useState(pincode ? "ok" : "idle");
  const check = (e) => {
    e && e.preventDefault();
    if (val.length === 6) { setState("ok"); setPincode(val); }
    else setState("err");
  };
  return (
    <form className="pincode" onSubmit={check} style={compact ? { width: "100%" } : {}}>
      <Icon name="mappin" size={16} style={{ color: "var(--green)", flex: "none" }} />
      <input inputMode="numeric" maxLength={6} placeholder="Delivery pincode"
        value={val} aria-label="Delivery pincode"
        onChange={(e) => { setVal(e.target.value.replace(/\D/g, "")); setState("idle"); }}
        style={compact ? { width: "100%" } : {}} />
      {state === "ok"
        ? <span className="badge badge--instock" style={{ marginRight: 2 }}>
            <span className="dot"></span>Delivers in 1 day</span>
        : <button type="submit" className="btn btn--ink btn--sm" style={{ padding: "7px 14px" }}>Check</button>}
    </form>
  );
}

/* ---------------- Header ---------------- */
function Header() {
  const { go, route, cartCount } = useApp();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const isDesktop = useIsDesktop(860);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const navTo = { Shop: "shop", Hampers: "hampers", Subscriptions: "subs",
    Gifting: "gifting", "Our Sourcing": "about", About: "about" };
  return (
    <>
      <div style={{ background: "var(--green)", color: "#fff", fontSize: 12.5, fontWeight: 500,
        letterSpacing: ".02em", textAlign: "center", padding: "7px 12px" }}>
        Class 1, export-grade · Cold-chain delivered across India · Free delivery over ₹999
      </div>
      <header className="app-header" style={{
        position: "sticky", top: 0, zIndex: 80, background: scrolled ? "rgba(251,249,244,.92)" : "var(--canvas)",
        backdropFilter: "blur(10px)", borderBottom: "1px solid var(--line)", transition: "background .2s" }}>
        <div className="container between" style={{ height: "var(--header-h)" }}>
          <div className="row" style={{ gap: 12 }}>
            {!isDesktop && (
              <button className="icon-btn" aria-label="Menu" onClick={() => setOpen(true)} style={iconBtn}>
                <Icon name="menu" size={22} /></button>
            )}
            <a href="#" onClick={(e) => { e.preventDefault(); go("home"); }} aria-label="Fruta Fresca home">
              <Logo />
            </a>
          </div>
          {isDesktop && (
            <nav className="row" style={{ gap: 22 }} aria-label="Primary">
              {FF.nav.map((n) => (
                <a key={n} href="#" onClick={(e) => { e.preventDefault(); go(navTo[n]); }}
                  className="nav-link nowrap" style={{ fontSize: 14.5, fontWeight: 500,
                    color: route === navTo[n] ? "var(--green)" : "var(--ink)" }}>{n}</a>
              ))}
            </nav>
          )}
          <div className="row" style={{ gap: 6 }}>
            {isDesktop && <Pincode />}
            <button style={iconBtn} aria-label="Search"><Icon name="search" size={20} /></button>
            {isDesktop && (
              <button style={iconBtn} aria-label="Account" onClick={() => go("account")}><Icon name="user" size={20} /></button>
            )}
            <button style={{ ...iconBtn, position: "relative" }} aria-label={`Cart, ${cartCount} items`}
              onClick={() => go("cart")}>
              <Icon name="bag" size={21} />
              {cartCount > 0 && <span style={cartDot}>{cartCount}</span>}
            </button>
          </div>
        </div>
      </header>

      {/* Mobile drawer */}
      {open && (
        <div className="drawer-overlay" onClick={() => setOpen(false)}
          style={{ position: "fixed", inset: 0, background: "rgba(28,42,33,.4)", zIndex: 200 }}>
          <div className="drawer" onClick={(e) => e.stopPropagation()} style={{
            position: "absolute", top: 0, left: 0, bottom: 0, width: "min(82vw, 340px)",
            background: "var(--canvas)", padding: 22, display: "flex", flexDirection: "column",
            gap: 4, animation: "slideIn .25s ease", overflowY: "auto" }}>
            <div className="between" style={{ marginBottom: 14 }}>
              <Logo />
              <button style={iconBtn} aria-label="Close" onClick={() => setOpen(false)}><Icon name="close" /></button>
            </div>
            <div style={{ marginBottom: 14 }}><Pincode compact /></div>
            {FF.nav.map((n) => (
              <a key={n} href="#" onClick={(e) => { e.preventDefault(); go(navTo[n]); setOpen(false); }}
                style={{ padding: "13px 4px", fontSize: 18, fontFamily: "var(--display)", fontWeight: 600,
                  borderBottom: "1px solid var(--line)" }}>{n}</a>
            ))}
            <button className="btn btn--ghost" style={{ marginTop: 16, justifyContent: "flex-start" }}
              onClick={() => { go("account"); setOpen(false); }}>
              <Icon name="user" size={18} /> My account</button>
          </div>
        </div>
      )}
    </>
  );
}
const iconBtn = { width: 40, height: 40, borderRadius: 10, border: "none", background: "transparent",
  display: "grid", placeItems: "center", color: "var(--ink)" };
const cartDot = { position: "absolute", top: 4, right: 3, minWidth: 17, height: 17, padding: "0 4px",
  borderRadius: 9, background: "var(--berry)", color: "#fff", fontSize: 10.5, fontWeight: 700,
  display: "grid", placeItems: "center", lineHeight: 1 };

/* ---------------- Qty stepper ---------------- */
function QtyStepper({ qty, onChange, size = "md" }) {
  const pad = size === "sm" ? "5px 6px" : "8px 8px";
  const bsz = size === "sm" ? 26 : 32;
  return (
    <div className="row" style={{ gap: 0, border: "1.5px solid var(--border)", borderRadius: 999,
      padding: pad, width: "fit-content", background: "var(--paper)" }}>
      <button onClick={() => onChange(Math.max(1, qty - 1))} aria-label="Decrease"
        style={{ width: bsz, height: bsz, borderRadius: "50%", border: "none", background: "var(--surface)",
          display: "grid", placeItems: "center" }}><Icon name="minus" size={15} /></button>
      <span className="tabnum" style={{ minWidth: 30, textAlign: "center", fontWeight: 600 }}>{qty}</span>
      <button onClick={() => onChange(qty + 1)} aria-label="Increase"
        style={{ width: bsz, height: bsz, borderRadius: "50%", border: "none", background: "var(--green)",
          color: "#fff", display: "grid", placeItems: "center" }}><Icon name="plus" size={15} /></button>
    </div>
  );
}

/* ---------------- Section head ---------------- */
function SectionHead({ eyebrow, title, action, onAction, center }) {
  return (
    <div className="section-head" style={center ? { justifyContent: "center", textAlign: "center", flexDirection: "column" } : {}}>
      <div>
        {eyebrow && <p className="eyebrow">{eyebrow}</p>}
        <h2 className="h2">{title}</h2>
      </div>
      {action && <button className="btn btn--ghost btn--sm" onClick={onAction}>{action}<Icon name="arrowR" size={16} /></button>}
    </div>
  );
}

/* ---------------- Reveal on scroll ---------------- */
function Reveal({ children, delay = 0, style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => { if (e.isIntersecting) { setTimeout(() => el.classList.add("in"), delay); io.unobserve(el); } });
    }, { threshold: 0.12 });
    if (el) io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return <div ref={ref} className="reveal" style={style}>{children}</div>;
}

/* ---------------- Background video (with poster fallback) ---------------- */
function BgVideo({ src, poster, alt = "", className = "fill", style = {} }) {
  const ref = useRef(null);
  useEffect(() => {
    const v = ref.current;
    if (!v) return;
    v.muted = true;
    // Pause when scrolled offscreen so background videos don't hog bandwidth
    const io = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting) { const p = v.play(); if (p && p.catch) p.catch(() => {}); }
        else { v.pause(); }
      });
    }, { threshold: 0.15 });
    io.observe(v);
    return () => io.disconnect();
  }, []);
  return (
    <video ref={ref} className={className} muted loop playsInline preload="metadata"
      poster={poster} aria-label={alt} style={{ objectFit: "cover", ...style }}>
      <source src={src} type="video/mp4" />
    </video>
  );
}

/* ---------------- WhatsApp FAB ---------------- */
function WhatsAppFab() {
  return (
    <a className="wa-fab" href="#" onClick={(e) => e.preventDefault()} aria-label="Chat on WhatsApp">
      <Icon name="whatsapp" size={26} style={{ color: "#fff" }} fill="#fff" stroke={0} />
    </a>
  );
}

/* ---------------- Footer ---------------- */
function Footer() {
  const { go } = useApp();
  return (
    <footer style={{ background: "var(--green)", color: "rgba(255,255,255,.82)", marginTop: 40 }}>
      <div className="container" style={{ paddingBlock: 56 }}>
        <div style={{ display: "grid", gap: 36, gridTemplateColumns: "1fr", marginBottom: 40 }} className="footer-grid">
          <div style={{ maxWidth: 320 }}>
            <Logo light />
            <p style={{ marginTop: 14, fontSize: 14.5, lineHeight: 1.6 }}>
              Class 1, export-grade fruit. Cold-chain delivered. 100% freshness guarantee or we replace it.
            </p>
            <div className="row" style={{ gap: 10, marginTop: 18 }}>
              {["instagram", "whatsapp", "mail"].map((i) => (
                <a key={i} href="#" onClick={(e) => e.preventDefault()} aria-label={i}
                  style={{ width: 38, height: 38, borderRadius: "50%", background: "rgba(255,255,255,.12)",
                    display: "grid", placeItems: "center", color: "#fff" }}><Icon name={i} size={18} /></a>
              ))}
            </div>
          </div>
          <div className="footer-links" style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 28 }}>
            {[
              { h: "Shop", items: [["Shop all", "shop"], ["Hampers & gifts", "hampers"], ["Subscriptions", "subs"], ["Occasions", "gifting"]] },
              { h: "Company", items: [["Our sourcing", "about"], ["About us", "about"], ["Contact", "contact"], ["Track order", "tracking"]] },
            ].map((col) => (
              <div key={col.h}>
                <h4 style={{ color: "#fff", fontSize: 13, letterSpacing: ".12em", textTransform: "uppercase",
                  margin: "0 0 14px", fontWeight: 600 }}>{col.h}</h4>
                <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "grid", gap: 11, fontSize: 14.5 }}>
                  {col.items.map(([t, r]) => (
                    <li key={t}><a href="#" onClick={(e) => { e.preventDefault(); go(r); }}>{t}</a></li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
          <div className="footer-news">
            <h4 style={{ color: "#fff", fontSize: 13, letterSpacing: ".12em", textTransform: "uppercase",
              margin: "0 0 14px", fontWeight: 600 }}>Fresh in your inbox</h4>
            <p style={{ fontSize: 14, marginBottom: 12 }}>Seasonal drops, sourcing stories and member offers.</p>
            <form className="row" style={{ gap: 8 }} onSubmit={(e) => e.preventDefault()}>
              <input className="input input--pill" placeholder="Email address"
                style={{ background: "rgba(255,255,255,.1)", border: "1.5px solid rgba(255,255,255,.22)", color: "#fff" }} />
              <button className="btn btn--primary" type="submit" style={{ flex: "none" }}>Join</button>
            </form>
          </div>
        </div>
        <div className="hr" style={{ background: "rgba(255,255,255,.16)" }}></div>
        <div className="between wrap" style={{ paddingTop: 22, fontSize: 13, gap: 12 }}>
          <span>© 2026 Fruta Fresca · Mumbai, India · <span className="serif" style={{ fontStyle: "italic" }}>Purveyors of fine fruits.</span></span>
          <div className="row wrap" style={{ gap: 18 }}>
            {["Privacy", "Terms", "Shipping & returns"].map((t) => (
              <a key={t} href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 13 }}>{t}</a>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------------- Trust band ---------------- */
function TrustBand() {
  const items = [
    { icon: "sprout", h: "Class 1, export-grade", s: "Hand-graded, never carbide-ripened" },
    { icon: "snowflake", h: "Unbroken cold-chain", s: "Farm to door, kept perfectly chilled" },
    { icon: "shield", h: "100% freshness guarantee", s: "Not perfect? We replace it, free" },
    { icon: "truck", h: "Pan-India delivery", s: "Next-day across major metros" },
  ];
  return (
    <div style={{ background: "var(--green-tint)" }}>
      <div className="container" style={{ paddingBlock: 28 }}>
        <div className="trust-grid" style={{ display: "grid", gap: 20, gridTemplateColumns: "repeat(2,1fr)" }}>
          {items.map((it) => (
            <div key={it.h} className="row" style={{ gap: 13, alignItems: "flex-start" }}>
              <span style={{ width: 42, height: 42, borderRadius: 12, background: "var(--paper)", flex: "none",
                display: "grid", placeItems: "center", color: "var(--green)" }}><Icon name={it.icon} size={22} /></span>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14.5, color: "var(--ink)" }}>{it.h}</div>
                <div className="small muted">{it.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Icon, Logo, Stars, SeasonBadge, ProductCard, Pincode, Header, QtyStepper,
  SectionHead, Reveal, WhatsAppFab, Footer, TrustBand, useApp, iconBtn, cartDot, BgVideo,
});
