// shell.jsx — header, footer, translation helper, shared UI

const LANG_CTX = React.createContext("ja");

function useLang() {
  return React.useContext(LANG_CTX);
}

function T({ ja, en }) {
  const lang = useLang();
  return <>{lang === "ja" ? ja : en}</>;
}

// Simple hash router
const ROUTER_CTX = React.createContext({ route: "top", params: {}, go: () => {} });

function useRouter() {
  return React.useContext(ROUTER_CTX);
}

function RouterProvider({ children }) {
  const parseHash = () => {
    const raw = (window.location.hash || "#top").slice(1);
    const [route, ...rest] = raw.split("/");
    const params = {};
    if (rest.length) params.id = rest.join("/");
    return { route: route || "top", params };
  };
  const [state, setState] = React.useState(parseHash);

  React.useEffect(() => {
    const onHash = () => {
      setState(parseHash());
      window.scrollTo({ top: 0, behavior: "auto" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const go = React.useCallback((route, id = null) => {
    window.location.hash = id != null ? `${route}/${id}` : route;
  }, []);

  return (
    <ROUTER_CTX.Provider value={{ ...state, go }}>
      {children}
    </ROUTER_CTX.Provider>
  );
}

// Nav items
const NAV_ITEMS = [
  { id: "collection", ja: "Collection", en: "Collection" },
  { id: "bridal",     ja: "Bridal",     en: "Bridal" },
  { id: "bespoke",    ja: "Bespoke",    en: "Bespoke" },
  { id: "gem",        ja: "宝石図鑑",    en: "Encyclopedia" },
  { id: "artisans",   ja: "Artisans",   en: "Artisans" },
  { id: "heritage",   ja: "Heritage",   en: "Heritage" },
  { id: "journal",    ja: "Journal",    en: "Journal" },
  { id: "boutiques",  ja: "店舗",        en: "Boutiques" },
  { id: "warranty",   ja: "百年保証",    en: "Century Warranty" },
];

function Header({ lang, setLang, theme, setTheme }) {
  const { route, go } = useRouter();
  const [scrolled, setScrolled] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const bg = theme === "dark" ? "#0A0908" : "#F8F5F0";
  const fg = theme === "dark" ? "#F4EEE3" : "#0C0C0C";
  const border = theme === "dark" ? "rgba(244,238,227,0.08)" : "rgba(12,12,12,0.08)";

  return (
    <header style={{
      position: "sticky",
      top: 0,
      zIndex: 50,
      background: scrolled ? (theme === "dark" ? "rgba(10,9,8,0.92)" : "rgba(248,245,240,0.92)") : bg,
      backdropFilter: scrolled ? "blur(14px) saturate(1.1)" : "none",
      WebkitBackdropFilter: scrolled ? "blur(14px) saturate(1.1)" : "none",
      borderBottom: scrolled ? `1px solid ${border}` : "1px solid transparent",
      transition: "background 400ms ease, border-color 400ms ease",
      color: fg,
    }}>
      {/* Top utility bar */}
      <div style={{
        display: "flex",
        justifyContent: "space-between",
        padding: "10px 40px",
        fontFamily: "var(--sans)",
        fontSize: 10,
        letterSpacing: "0.32em",
        textTransform: "uppercase",
        color: theme === "dark" ? "#8A8378" : "#8A8378",
        borderBottom: `1px solid ${border}`,
      }}>
        <span>
          {lang === "ja" ? "東京・銀座本店" : "Ginza · Tokyo"} &nbsp;·&nbsp; {lang === "ja" ? "1925年創業" : "EST. 1925"}
        </span>
        <span style={{ display: "flex", gap: 24 }}>
          <a href="#vip" onClick={(e) => { e.preventDefault(); go("vip"); }} style={{ color: "inherit", letterSpacing: "0.32em" }}>
            {lang === "ja" ? "VIPサロン" : "VIP Salon"}
          </a>
          <button onClick={() => setLang(lang === "ja" ? "en" : "ja")} style={{ color: "inherit", letterSpacing: "0.32em", fontSize: 10, textTransform: "uppercase" }}>
            {lang === "ja" ? "EN" : "日本語"}
          </button>
        </span>
      </div>

      {/* Main nav */}
      <div style={{
        display: "grid",
        gridTemplateColumns: "1fr auto 1fr",
        alignItems: "center",
        padding: "22px 40px",
      }}>
        {/* Left: primary nav */}
        <nav style={{
          display: "flex",
          gap: 28,
          fontFamily: "var(--sans)",
          fontSize: 11,
          letterSpacing: "0.22em",
          textTransform: "uppercase",
          fontWeight: 400,
        }}>
          {NAV_ITEMS.slice(0, 5).map((item) => (
            <a
              key={item.id}
              href={`#${item.id}`}
              onClick={(e) => { e.preventDefault(); go(item.id); }}
              style={{
                position: "relative",
                paddingBottom: 3,
                opacity: route === item.id ? 1 : 0.68,
                borderBottom: route === item.id ? `1px solid ${fg}` : "1px solid transparent",
                transition: "opacity 200ms",
              }}
            >
              {lang === "ja" ? item.ja : item.en}
            </a>
          ))}
        </nav>

        {/* Centre: Wordmark */}
        <a
          href="#top"
          onClick={(e) => { e.preventDefault(); go("top"); }}
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            padding: "0 40px",
          }}
        >
          <div style={{
            fontFamily: "var(--serif-display)",
            fontSize: 30,
            letterSpacing: "0.36em",
            textIndent: "0.36em",
            fontWeight: 400,
            lineHeight: 1,
          }}>
            HOSHI
          </div>
          <div style={{
            fontFamily: "var(--serif-en-alt)",
            fontSize: 10,
            fontStyle: "italic",
            letterSpacing: "0.28em",
            marginTop: 6,
            color: theme === "dark" ? "#8A8378" : "#5E5851",
          }}>
            Jewellery · Ginza · est. 1925
          </div>
        </a>

        {/* Right: secondary nav */}
        <nav style={{
          display: "flex",
          gap: 24,
          justifyContent: "flex-end",
          fontFamily: "var(--sans)",
          fontSize: 11,
          letterSpacing: "0.22em",
          textTransform: "uppercase",
          fontWeight: 400,
          alignItems: "center",
        }}>
          {NAV_ITEMS.slice(5).map((item) => (
            <a
              key={item.id}
              href={`#${item.id}`}
              onClick={(e) => { e.preventDefault(); go(item.id); }}
              style={{
                opacity: route === item.id ? 1 : 0.68,
                borderBottom: route === item.id ? `1px solid ${fg}` : "1px solid transparent",
                paddingBottom: 3,
              }}
            >
              {lang === "ja" ? item.ja : item.en}
            </a>
          ))}
          {/* Cart icon */}
          <span aria-label="cart" style={{ width: 18, height: 18, display: "inline-flex", alignItems: "center", justifyContent: "center", opacity: 0.72 }}>
            <svg viewBox="0 0 18 18" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1">
              <path d="M5 6h8l-1 9H6L5 6z"/>
              <path d="M7 6a2 2 0 114 0"/>
            </svg>
          </span>
        </nav>
      </div>

      {/* Gold hairline */}
      <div className="hoshi-kinsugi" style={{ opacity: 0.3 }} />
    </header>
  );
}

function Footer({ lang, theme }) {
  const bg = theme === "dark" ? "#0A0908" : "#0C0C0C";
  const fg = "#F4EEE3";
  const dim = "#8A8378";

  return (
    <footer style={{
      background: bg,
      color: fg,
      padding: "80px 40px 40px",
      fontFamily: "var(--serif-jp)",
      fontWeight: 300,
    }}>
      <div style={{ maxWidth: 1400, margin: "0 auto" }}>
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr 1fr 1fr", gap: 60, paddingBottom: 60 }}>
          <div>
            <div style={{ fontFamily: "var(--serif-display)", fontSize: 28, letterSpacing: "0.28em", marginBottom: 6 }}>
              HOSHI
            </div>
            <div style={{ fontFamily: "var(--serif-en-alt)", fontStyle: "italic", fontSize: 12, color: dim, letterSpacing: "0.2em" }}>
              Jewellery · Ginza · est. 1925
            </div>
            <p style={{ marginTop: 32, fontSize: 13, lineHeight: 1.8, maxWidth: 360, color: "#D6CBB8" }}>
              <T
                ja="四代続く銀座の宝飾工房。伊勢志摩アコヤ真珠・南洋黒蝶／白蝶真珠・ダイヤモンドによるハイジュエリーを、完全自社工房にて製作しております。"
                en="A four-generation jewellery atelier in Ginza. High jewellery in Ise-Shima Akoya, Tahitian, South Sea pearls, and diamonds — all made in-house."
              />
            </p>
          </div>
          <FooterCol title={lang === "ja" ? "コレクション" : "Collection"} items={[
            { ja: "月 — Tsuki", en: "Tsuki — Moon" },
            { ja: "夜 — Yoru", en: "Yoru — Night" },
            { ja: "暁 — Akatsuki", en: "Akatsuki — Dawn" },
            { ja: "言霊 — Kotodama", en: "Kotodama" },
          ]} lang={lang} />
          <FooterCol title={lang === "ja" ? "サービス" : "Services"} items={[
            { ja: "ブライダル", en: "Bridal" },
            { ja: "ビスポーク", en: "Bespoke" },
            { ja: "百年保証", en: "Century Warranty" },
            { ja: "国際発送 (FedEx)", en: "Int'l Shipping (FedEx)" },
          ]} lang={lang} />
          <FooterCol title={lang === "ja" ? "店舗" : "Boutiques"} items={[
            { ja: "銀座本店", en: "Ginza Flagship" },
            { ja: "京都祇園", en: "Kyoto Gion" },
            { ja: "パリ店", en: "Paris" },
          ]} lang={lang} />
          <FooterCol title={lang === "ja" ? "メゾン" : "Maison"} items={[
            { ja: "四代の系譜", en: "Four Generations" },
            { ja: "工房案内", en: "The Atelier" },
            { ja: "プレス", en: "Press" },
            { ja: "採用", en: "Careers" },
          ]} lang={lang} />
        </div>
        <hr className="hoshi-hairline" style={{ background: "#D6CBB8", opacity: 0.15 }} />
        <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 40, color: dim, fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", fontFamily: "var(--sans)" }}>
          <span>© 1925–2026 HOSHI Jewellery K.K. All rights reserved.</span>
          <span style={{ display: "flex", gap: 28 }}>
            <a href="#">Privacy</a>
            <a href="#">Terms</a>
            <a href="#">特定商取引法</a>
            <a href="#">Accessibility</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ title, items, lang }) {
  return (
    <div>
      <h4 style={{
        fontFamily: "var(--sans)",
        fontSize: 10,
        letterSpacing: "0.3em",
        textTransform: "uppercase",
        color: "#8A8378",
        margin: 0,
        marginBottom: 22,
        fontWeight: 500,
      }}>{title}</h4>
      <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
        {items.map((it, i) => (
          <li key={i} style={{ fontSize: 13, lineHeight: 1.4 }}>
            <a href="#" style={{ color: "#F4EEE3", opacity: 0.85 }}>
              {lang === "ja" ? it.ja : it.en}
            </a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// Small reusable UI: section label + eyebrow + display title
function SectionHead({ eyebrowJa, eyebrowEn, titleJa, titleEn, align = "left", color = "inherit" }) {
  const lang = useLang();
  return (
    <div style={{ textAlign: align, color }}>
      <div className="hoshi-eyebrow" style={{ color: "inherit", opacity: 0.8 }}>
        {lang === "ja" ? eyebrowJa : eyebrowEn}
      </div>
      <h2 style={{
        fontFamily: "var(--serif-display)",
        fontWeight: 400,
        fontSize: "clamp(36px, 4.2vw, 72px)",
        lineHeight: 1.1,
        letterSpacing: "-0.01em",
        margin: "18px 0 0",
      }}>
        {lang === "ja"
          ? <span style={{ fontFamily: "var(--serif-jp)", fontWeight: 300 }}>{titleJa}</span>
          : titleEn}
      </h2>
    </div>
  );
}

// A "Price on Request" formatter
function formatPrice(product, lang) {
  if (product.priceLabel) return product.priceLabel;
  const yen = lang === "ja" ? "¥" : "¥";
  return yen + product.price.toLocaleString("en-US");
}

// Hairline link / button
function GhostLink({ children, onClick, style = {}, theme = "light" }) {
  const [hover, setHover] = React.useState(false);
  const fg = theme === "dark" ? "#F4EEE3" : "#0C0C0C";
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        fontFamily: "var(--sans)",
        fontSize: 11,
        letterSpacing: "0.3em",
        textTransform: "uppercase",
        color: fg,
        paddingBottom: 4,
        borderBottom: `1px solid ${hover ? fg : "rgba(0,0,0,0.15)"}`,
        transition: "border-color 300ms",
        ...style,
      }}
    >
      {children} <span style={{ display: "inline-block", marginLeft: 10, transition: "transform 300ms", transform: hover ? "translateX(4px)" : "translateX(0)" }}>→</span>
    </button>
  );
}

function SolidButton({ children, onClick, style = {}, theme = "light" }) {
  const [hover, setHover] = React.useState(false);
  const bg = theme === "dark" ? "#F4EEE3" : "#0C0C0C";
  const fg = theme === "dark" ? "#0C0C0C" : "#F8F5F0";
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        background: hover ? (theme === "dark" ? "#FBF8F2" : "#1A1714") : bg,
        color: fg,
        padding: "18px 32px",
        fontFamily: "var(--sans)",
        fontSize: 11,
        letterSpacing: "0.3em",
        textTransform: "uppercase",
        fontWeight: 400,
        transition: "background 300ms, transform 300ms",
        transform: hover ? "translateY(-1px)" : "none",
        ...style,
      }}
    >
      {children}
    </button>
  );
}

// Image-less product thumbnail — luxe placeholder
// Uses the product's heroColor + PearlCanvas to suggest its main pearl.
function ProductThumb({ product, size = 440, onClick }) {
  const lang = useLang();
  const dark = product.heroColor && hexDarkness(product.heroColor) > 0.5;
  const pearlDarkness = dark ? 0.92 : 0.04;
  // Pearl hue based on category
  const overtone = product.collection === "yoru" ? [0, 18, 10] : null;

  const [hover, setHover] = React.useState(false);

  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        position: "relative",
        width: "100%",
        aspectRatio: "4/5",
        background: product.heroColor,
        overflow: "hidden",
        textAlign: "left",
        display: "block",
        transition: "transform 500ms var(--ease)",
        transform: hover ? "scale(1.005)" : "none",
        cursor: "pointer",
      }}
    >
      {/* Soft gradient shading */}
      <div style={{
        position: "absolute", inset: 0,
        background: dark
          ? "radial-gradient(ellipse at 30% 20%, rgba(255,255,255,0.12), transparent 60%)"
          : "radial-gradient(ellipse at 30% 20%, rgba(255,255,255,0.8), transparent 60%)",
      }} />
      {/* Single pearl */}
      <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
        <PearlCanvas size={Math.round(size * 0.55)} darkness={pearlDarkness} hueShift={product.collection === "yoru" ? 0.3 : -0.2} overtone={overtone} />
      </div>
      {/* ID + name on hover overlay */}
      <div style={{
        position: "absolute",
        inset: 0,
        background: hover ? (dark ? "rgba(0,0,0,0.3)" : "rgba(255,255,255,0.25)") : "transparent",
        transition: "background 500ms",
        display: "flex",
        alignItems: "flex-end",
        padding: 20,
      }}>
        <span style={{
          fontFamily: "var(--sans)",
          fontSize: 10,
          letterSpacing: "0.28em",
          textTransform: "uppercase",
          color: dark ? "#F4EEE3" : "#0C0C0C",
          opacity: hover ? 1 : 0.5,
          transition: "opacity 300ms",
        }}>
          {product.id}
        </span>
      </div>
    </button>
  );
}

function hexDarkness(hex) {
  // simple luminance
  const h = hex.replace("#", "");
  const r = parseInt(h.substring(0, 2), 16);
  const g = parseInt(h.substring(2, 4), 16);
  const b = parseInt(h.substring(4, 6), 16);
  const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return 1 - lum;
}

Object.assign(window, {
  LANG_CTX, useLang, T,
  ROUTER_CTX, useRouter, RouterProvider,
  Header, Footer, SectionHead,
  formatPrice, GhostLink, SolidButton, ProductThumb, hexDarkness,
});
