/* global React, I18N */
const { useState: useS, useEffect: useE, useRef: useR, useContext: useC, createContext: createCtx } = React;

// =========================================================
// PORTACOOLER · shared components (used on Hem + Allround)
// =========================================================

const LangCtx = createCtx({ lang: "sv", setLang: () => {}, t: I18N.sv });

function LangProvider({ children }) {
  const [lang, setLang] = useS(() => localStorage.getItem("pc-lang") || "sv");
  useE(() => { localStorage.setItem("pc-lang", lang); document.documentElement.lang = lang; }, [lang]);
  const t = I18N[lang];
  return React.createElement(LangCtx.Provider, { value: { lang, setLang, t } }, children);
}
const useLang = () => useC(LangCtx);

// ---------- Cart (lives in localStorage so it survives nav between pages) ----------
const CartCtx = createCtx(null);
function CartProvider({ children }) {
  const [items, setItems] = useS(() => {
    try { return JSON.parse(localStorage.getItem("pc-cart") || "[]"); } catch { return []; }
  });
  const [open, setOpen] = useS(false);
  const [toast, setToast] = useS(null);
  useE(() => { localStorage.setItem("pc-cart", JSON.stringify(items)); }, [items]);
  const add = (p) => {
    setItems(prev => {
      const i = prev.findIndex(x => x.id === p.id && x.color === p.color);
      if (i >= 0) {
        const copy = [...prev]; copy[i] = { ...copy[i], qty: copy[i].qty + (p.qty || 1) }; return copy;
      }
      return [...prev, { ...p, qty: p.qty || 1 }];
    });
    setToast({ name: p.name, ts: Date.now() });
    setTimeout(() => setToast(t => (t && t.ts === toast?.ts) ? null : t), 2400);
  };
  const remove = (i) => setItems(prev => prev.filter((_, j) => j !== i));
  const setQty = (i, q) => setItems(prev => prev.map((it, j) => j === i ? { ...it, qty: Math.max(1, q) } : it));
  const count = items.reduce((s, it) => s + it.qty, 0);
  return React.createElement(CartCtx.Provider, {
    value: { items, add, remove, setQty, count, open, setOpen, toast, setToast }
  }, children);
}
const useCart = () => useC(CartCtx);

// ---------- Reveal-on-scroll wrapper ----------
function Reveal({ children, delay = 0, y = 24, as = "div", style = {}, ...rest }) {
  const ref = useR(null);
  const [shown, setShown] = useS(false);
  useE(() => {
    const el = ref.current; if (!el) return;
    // Check if already in viewport on mount (covers first paint + screenshot envs).
    const r = el.getBoundingClientRect();
    const vh = window.innerHeight || document.documentElement.clientHeight;
    if (r.top < vh - 40 && r.bottom > 40) { setShown(true); return; }
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShown(true); io.disconnect(); }
    }, { threshold: 0.08, rootMargin: "0px 0px -60px 0px" });
    io.observe(el);
    // Safety net — if neither path fires within 800ms, just show it.
    const tm = setTimeout(() => setShown(true), 800);
    return () => { io.disconnect(); clearTimeout(tm); };
  }, []);
  return React.createElement(as, {
    ref, ...rest, style: {
      ...style,
      opacity: shown ? 1 : 0,
      transform: shown ? "translateY(0)" : `translateY(${y}px)`,
      transition: `opacity 720ms var(--ease-out-warm) ${delay}ms, transform 720ms var(--ease-out-warm) ${delay}ms`,
    }
  }, children);
}

// ---------- Buttons ----------
function PCButton({ children, variant = "primary", onClick, type = "button", icon, full = false, size = "md", href }) {
  const base = {
    fontFamily: "var(--font-body)", fontWeight: 600, border: "none", cursor: "pointer",
    transition: "all 200ms var(--ease-out-warm), transform 120ms var(--ease-out-warm)",
    display: "inline-flex", alignItems: "center", gap: 8,
    letterSpacing: "-0.005em", width: full ? "100%" : "auto", justifyContent: "center",
    fontSize: size === "sm" ? 14 : size === "lg" ? 16 : 15,
    padding: size === "sm" ? "9px 16px" : size === "lg" ? "16px 28px" : "12px 22px",
    borderRadius: "var(--r-3)", textDecoration: "none",
  };
  const variants = {
    primary: { background: "var(--sval-500)", color: "var(--fg-on-brand)", boxShadow: "var(--shadow-1), var(--shadow-inset-light)" },
    onDark: { background: "var(--linne)", color: "var(--skog)" },
    secondary: { background: "transparent", color: "var(--skog)", border: "1.5px solid var(--skog)" },
    secondaryDark: { background: "transparent", color: "var(--linne)", border: "1.5px solid rgba(246,241,230,0.4)" },
    tertiary: { background: "transparent", color: "var(--sval-500)", padding: "12px 6px" },
  };
  const props = {
    onClick,
    onMouseDown: e => { e.currentTarget.style.transform = "translateY(1px)"; },
    onMouseUp:   e => { e.currentTarget.style.transform = "translateY(0)"; },
    onMouseLeave:e => { e.currentTarget.style.transform = "translateY(0)"; },
    style: { ...base, ...variants[variant] },
  };
  if (href) return React.createElement("a", { href, ...props }, children, icon);
  return React.createElement("button", { type, ...props }, children, icon);
}

// ---------- Badge ----------
function PCBadge({ children, tone = "neutral" }) {
  const tones = {
    "in-stock": { bg: "#E2EADC", fg: "#4E6740", dot: "#7A9466" },
    "low":      { bg: "#F9E5C5", fg: "#B0701F", dot: "#E89A3C" },
    "out":      { bg: "#F3D7D3", fg: "#7A2F28", dot: "#B0463D" },
    "new":      { bg: "var(--skog)", fg: "var(--linne)", dot: null },
    "sale":     { bg: "var(--sol-500)", fg: "var(--skog)", dot: null },
    "best":     { bg: "var(--sval-900)", fg: "var(--linne)", dot: null },
    "b2b":      { bg: "var(--sval-100)", fg: "var(--sval-900)", dot: null },
    "neutral":  { bg: "var(--linne-djup)", fg: "var(--skog)", dot: null },
  };
  const tn = tones[tone] || tones.neutral;
  return (
    <span style={{
      fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12,
      padding: "5px 10px", borderRadius: 999,
      background: tn.bg, color: tn.fg,
      display: "inline-flex", alignItems: "center", gap: 6, letterSpacing: "0.02em",
    }}>
      {tn.dot && <span style={{ width: 6, height: 6, borderRadius: 999, background: tn.dot }} />}
      {children}
    </span>
  );
}

// ---------- Eyebrow ----------
function Eyebrow({ children, color = "var(--sval-700)" }) {
  return (
    <div style={{
      fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 600,
      letterSpacing: "0.14em", color, textTransform: "uppercase",
      marginBottom: 16, display: "inline-flex", alignItems: "center", gap: 10,
    }}>
      <span style={{ width: 18, height: 1, background: color, opacity: 0.6 }} />
      {children}
    </div>
  );
}

// ---------- Logo ----------
function Logo({ size = 30, tone = "dark" }) {
  return (
    <a href="index.html" style={{ display: "inline-flex", alignItems: "center", gap: 10, textDecoration: "none" }}>
      <img src="assets/logo-mark.svg" width={size} height={size} alt="Portacooler" />
      <span style={{
        fontFamily: "var(--font-display)", fontSize: size * 0.82,
        color: tone === "light" ? "var(--linne)" : "var(--skog)",
        letterSpacing: "-0.01em", lineHeight: 1, fontStyle: "italic",
      }}>
        Portacooler
      </span>
    </a>
  );
}

// ---------- Top Nav ----------
function TopNav({ current = "home" }) {
  const { lang, setLang, t } = useLang();
  const { count, setOpen } = useCart();
  const [scrolled, setScrolled] = useS(false);
  useE(() => {
    const onS = () => setScrolled(window.scrollY > 12);
    window.addEventListener("scroll", onS); onS();
    return () => window.removeEventListener("scroll", onS);
  }, []);
  const navItems = [
    { id: "products", label: t.nav.products, href: "index.html#products" },
    { id: "how", label: t.nav.how, href: "index.html#how" },
    { id: "pro", label: t.nav.pro, href: "index.html#pro" },
    { id: "ai", label: t.nav.ai, href: "index.html#ai" },
    { id: "support", label: t.nav.support, href: "index.html#faq" },
  ];

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: scrolled ? "rgba(246, 241, 230, 0.85)" : "rgba(246, 241, 230, 0.6)",
      backdropFilter: "blur(18px) saturate(140%)",
      WebkitBackdropFilter: "blur(18px) saturate(140%)",
      borderBottom: scrolled ? "1px solid rgba(168, 156, 132, 0.22)" : "1px solid transparent",
      transition: "all 220ms var(--ease-out-warm)",
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: scrolled ? "12px 32px" : "18px 32px", display: "flex", alignItems: "center", gap: 32, transition: "padding 220ms var(--ease-out-warm)" }}>
        <Logo size={scrolled ? 26 : 30} />
        <nav style={{ display: "flex", gap: 4, marginLeft: 12, flex: 1 }}>
          {navItems.map(item => (
            <a key={item.id} href={item.href} style={{
              fontSize: 14, fontWeight: 500, color: "var(--skog)", textDecoration: "none",
              padding: "8px 14px", borderRadius: "var(--r-2)",
              transition: "background 160ms var(--ease-out-warm)",
            }}
            onMouseEnter={e => e.currentTarget.style.background = "rgba(27,42,34,0.05)"}
            onMouseLeave={e => e.currentTarget.style.background = "transparent"}
            >{item.label}</a>
          ))}
        </nav>

        {/* Language switcher */}
        <div role="group" style={{
          display: "inline-flex", border: "1px solid rgba(27,42,34,0.16)", borderRadius: 999,
          padding: 2, background: "rgba(255,255,255,0.4)", fontFamily: "var(--font-body)",
        }}>
          {["sv", "en"].map(code => {
            const active = lang === code;
            return (
              <button key={code} onClick={() => setLang(code)} style={{
                fontSize: 12, fontWeight: 600, letterSpacing: "0.06em",
                padding: "6px 12px", borderRadius: 999,
                background: active ? "var(--skog)" : "transparent",
                color: active ? "var(--linne)" : "var(--skog-mjuk)",
                border: "none", cursor: "pointer", textTransform: "uppercase",
                transition: "all 160ms var(--ease-out-warm)",
              }}>{code}</button>
            );
          })}
        </div>

        <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
          <button aria-label={t.nav.search} style={iconBtn}>
            <i className="ph ph-magnifying-glass" style={{ fontSize: 20 }} />
          </button>
          <button onClick={() => setOpen(true)} aria-label={t.nav.cart} style={{ ...iconBtn, position: "relative" }}>
            <i className="ph ph-shopping-bag" style={{ fontSize: 20 }} />
            {count > 0 && (
              <span style={{
                position: "absolute", top: 2, right: 0,
                background: "var(--sval-500)", color: "#fff",
                fontSize: 10, fontWeight: 700,
                minWidth: 18, height: 18, padding: "0 5px", borderRadius: 999,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--font-body)",
              }}>{count}</span>
            )}
          </button>
        </div>
      </div>
    </header>
  );
}

const iconBtn = {
  background: "transparent", border: "none", cursor: "pointer",
  padding: 8, borderRadius: "var(--r-2)", color: "var(--skog)",
  display: "inline-flex",
};

// ---------- Footer ----------
function Footer() {
  const { t, lang, setLang } = useLang();
  return (
    <footer style={{ background: "var(--skog)", color: "var(--linne)", padding: "80px 32px 32px", position: "relative", overflow: "hidden" }}>
      <div style={{
        position: "absolute", inset: 0, opacity: 0.05, pointerEvents: "none",
        backgroundImage: "url(assets/wave.svg)", backgroundSize: "320px", backgroundRepeat: "repeat",
      }} />
      <div style={{ maxWidth: 1280, margin: "0 auto", position: "relative" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr repeat(4, 1fr)", gap: 48, marginBottom: 64 }}>
          <div>
            <div style={{ display: "inline-flex", alignItems: "center", gap: 12, marginBottom: 22 }}>
              <img src="assets/logo-mark.svg" width={40} height={40} alt="" />
              <span style={{ fontFamily: "var(--font-display)", fontSize: 30, color: "var(--linne)", letterSpacing: "-0.01em", fontStyle: "italic" }}>
                Portacooler
              </span>
            </div>
            <p style={{ fontFamily: "var(--font-display)", fontStyle: "italic", fontSize: 24, lineHeight: 1.3, color: "var(--sval-300)", marginBottom: 14 }}>
              {t.footer.tagline}
            </p>
            <p style={{ fontSize: 14, lineHeight: "22px", color: "rgba(246,241,230,0.7)", maxWidth: 300 }}>
              {t.footer.body}
            </p>
            <div style={{ display: "flex", gap: 10, marginTop: 24 }}>
              {["ph-instagram-logo", "ph-youtube-logo", "ph-linkedin-logo"].map(i => (
                <a key={i} href="#" aria-label={i} style={{
                  width: 38, height: 38, borderRadius: 999, background: "rgba(246,241,230,0.08)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center", color: "var(--linne)",
                  transition: "background 160ms var(--ease-out-warm)",
                }}
                onMouseEnter={e => e.currentTarget.style.background = "rgba(246,241,230,0.18)"}
                onMouseLeave={e => e.currentTarget.style.background = "rgba(246,241,230,0.08)"}
                ><i className={`ph ${i}`} style={{ fontSize: 18 }} /></a>
              ))}
            </div>
          </div>
          {t.footer.cols.map(col => (
            <div key={col.t}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "rgba(246,241,230,0.5)", marginBottom: 16 }}>
                {col.t}
              </div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 10 }}>
                {col.items.map(it => (
                  <li key={it}><a href="#" style={{ fontSize: 14, color: "var(--linne)", textDecoration: "none", opacity: 0.85 }}>{it}</a></li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          borderTop: "1px solid rgba(246,241,230,0.12)", paddingTop: 24,
          display: "flex", justifyContent: "space-between", alignItems: "center",
          fontSize: 13, color: "rgba(246,241,230,0.55)", flexWrap: "wrap", gap: 16,
        }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            <span style={{ display: "inline-block", width: 14, height: 9, borderRadius: 1, background: "linear-gradient(#006AA7 50%, #FECC00 50%)", position: "relative" }}>
              <span style={{ position: "absolute", left: 4, top: 0, bottom: 0, width: 2, background: "#FECC00" }} />
              <span style={{ position: "absolute", left: 0, right: 0, top: 4, height: 1, background: "#FECC00" }} />
            </span>
            {t.footer.address}
          </span>
          <div style={{ display: "flex", gap: 24, alignItems: "center" }}>
            {t.footer.legal.map(l => <a key={l} href="#" style={{ color: "inherit", textDecoration: "none" }}>{l}</a>)}
            <div role="group" style={{ display: "inline-flex", border: "1px solid rgba(246,241,230,0.18)", borderRadius: 999, padding: 2 }}>
              {["sv", "en"].map(c => (
                <button key={c} onClick={() => setLang(c)} style={{
                  fontSize: 11, fontWeight: 600, letterSpacing: "0.06em",
                  padding: "4px 10px", borderRadius: 999,
                  background: lang === c ? "var(--linne)" : "transparent",
                  color: lang === c ? "var(--skog)" : "rgba(246,241,230,0.7)",
                  border: "none", cursor: "pointer", textTransform: "uppercase",
                }}>{c}</button>
              ))}
            </div>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ---------- Cart drawer + toast ----------
function CartDrawer() {
  const { items, remove, setQty, open, setOpen } = useCart();
  const { t } = useLang();
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const shipping = subtotal > 1500 || items.length === 0 ? 0 : 79;

  // lock body scroll while open
  useE(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 100,
      pointerEvents: open ? "auto" : "none",
    }}>
      <div onClick={() => setOpen(false)} style={{
        position: "absolute", inset: 0, background: "rgba(27, 42, 34, 0.45)",
        opacity: open ? 1 : 0, transition: "opacity 220ms var(--ease-out-warm)",
      }} />
      <aside style={{
        position: "absolute", top: 0, right: 0, bottom: 0,
        width: "min(460px, 100vw)", background: "var(--linne)",
        boxShadow: "var(--shadow-3)",
        transform: open ? "translateX(0)" : "translateX(100%)",
        transition: "transform 320ms var(--ease-out-warm)",
        display: "flex", flexDirection: "column",
      }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "24px 28px", borderBottom: "1px solid var(--border-soft)" }}>
          <h2 style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "var(--skog)" }}>{t.cart.title}</h2>
          <button onClick={() => setOpen(false)} style={{ background: "transparent", border: "none", cursor: "pointer", color: "var(--skog)", padding: 8 }}>
            <i className="ph ph-x" style={{ fontSize: 20 }} />
          </button>
        </div>
        <div style={{ flex: 1, overflow: "auto", padding: "8px 28px" }}>
          {items.length === 0 ? (
            <div style={{ padding: "64px 16px", textAlign: "center", color: "var(--skog-mjuk)" }}>
              <i className="ph ph-shopping-bag" style={{ fontSize: 48, color: "var(--rök-mjuk)" }} />
              <p style={{ marginTop: 16, fontSize: 15 }}>{t.cart.empty}</p>
            </div>
          ) : items.map((it, i) => (
            <div key={i} style={{ display: "flex", gap: 14, padding: "20px 0", borderBottom: "1px solid var(--border-soft)" }}>
              <div style={{ width: 72, height: 72, background: "var(--linne-djup)", borderRadius: "var(--r-2)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, overflow: "hidden" }}>
                <img src={it.image || "assets/illu-product.svg"} alt="" style={{ width: "85%", height: "85%", objectFit: "contain" }} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
                  <div>
                    <div style={{ fontSize: 15, fontWeight: 600, color: "var(--skog)" }}>{it.name}</div>
                    <div style={{ fontSize: 12, color: "var(--skog-bleek)", marginTop: 2 }}>{it.color || "Blå"} · {it.volume} L</div>
                  </div>
                  <button onClick={() => remove(i)} style={{ background: "transparent", border: "none", cursor: "pointer", color: "var(--skog-bleek)" }}>
                    <i className="ph ph-trash" style={{ fontSize: 16 }} />
                  </button>
                </div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10 }}>
                  <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--border)", borderRadius: "var(--r-2)" }}>
                    <button onClick={() => setQty(i, it.qty - 1)} style={qtyBtn}><i className="ph ph-minus" style={{ fontSize: 11 }} /></button>
                    <span style={{ width: 24, textAlign: "center", fontSize: 13, fontWeight: 600 }}>{it.qty}</span>
                    <button onClick={() => setQty(i, it.qty + 1)} style={qtyBtn}><i className="ph ph-plus" style={{ fontSize: 11 }} /></button>
                  </div>
                  <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--skog)" }}>
                    {(it.price * it.qty).toLocaleString("sv-SE")} kr
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div style={{ padding: "24px 28px", borderTop: "1px solid var(--border-soft)", background: "var(--linne-djup)" }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "var(--skog-mjuk)", marginBottom: 8 }}>
              <span>{t.cart.sub}</span>
              <span style={{ fontFamily: "var(--font-mono)" }}>{subtotal.toLocaleString("sv-SE")} kr</span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, color: "var(--skog-mjuk)", marginBottom: 12 }}>
              <span>{t.cart.ship}</span>
              <span style={{ fontFamily: "var(--font-mono)", color: shipping === 0 ? "var(--mossa-700)" : "inherit" }}>
                {shipping === 0 ? t.cart.free : `${shipping} kr`}
              </span>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", fontSize: 16, color: "var(--skog)", fontWeight: 600, marginBottom: 20, paddingTop: 12, borderTop: "1px solid var(--border-soft)" }}>
              <span>{t.cart.total}</span>
              <span style={{ fontFamily: "var(--font-display)", fontSize: 28, fontWeight: 400 }}>{(subtotal + shipping).toLocaleString("sv-SE")} kr</span>
            </div>
            <PCButton full icon={<i className="ph ph-arrow-right" />}>{t.cart.checkout}</PCButton>
            <p style={{ fontSize: 12, color: "var(--skog-bleek)", textAlign: "center", marginTop: 12 }}>
              {t.cart.pay}
            </p>
          </div>
        )}
      </aside>
    </div>
  );
}

const qtyBtn = { background: "transparent", border: "none", width: 28, height: 28, cursor: "pointer", color: "var(--skog)" };

// ---------- Toast (cart add confirmation) ----------
function CartToast() {
  const { toast } = useCart();
  const { t } = useLang();
  return (
    <div style={{
      position: "fixed", bottom: 24, left: "50%", transform: `translateX(-50%) translateY(${toast ? 0 : 32}px)`,
      background: "var(--skog)", color: "var(--linne)", padding: "12px 18px",
      borderRadius: "var(--r-3)", boxShadow: "var(--shadow-3)",
      fontSize: 14, fontWeight: 500, zIndex: 200,
      opacity: toast ? 1 : 0, transition: "all 240ms var(--ease-out-warm)",
      pointerEvents: "none", display: "flex", alignItems: "center", gap: 10,
    }}>
      <i className="ph ph-check-circle" style={{ fontSize: 18, color: "var(--mossa-100)" }} />
      <span><strong style={{ fontWeight: 600 }}>{toast?.name}</strong> — {t.cart.added}</span>
    </div>
  );
}

Object.assign(window, {
  LangProvider, useLang,
  CartProvider, useCart,
  Reveal, PCButton, PCBadge, Eyebrow, Logo,
  TopNav, Footer, CartDrawer, CartToast,
});
