/* ============================================================
   chrome.jsx — Nav + Footer shared across all pages.
   Depends on lib.jsx + i18n.jsx globals.
   ============================================================ */

function currentPage() {
  const p = location.pathname.split("/").pop();
  return !p || p === "" ? "index.html" : p;
}

/* ---------- small inline icons (Lucide-style, thin) ---------- */
function IconSun() {
  return (
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4" /><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4" />
    </svg>
  );
}
function IconMoon() {
  return (
    <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
    </svg>
  );
}
function SocialIcon({ label, size = 17 }) {
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round" };
  const k = String(label).toLowerCase();
  if (k.includes("insta")) return (<svg {...common}><rect x="2" y="2" width="20" height="20" rx="5.5" /><circle cx="12" cy="12" r="4" /><circle cx="17.4" cy="6.6" r="0.9" fill="currentColor" stroke="none" /></svg>);
  if (k.includes("you")) return (<svg {...common}><rect x="2" y="5" width="20" height="14" rx="4.5" /><path d="M10 9.2 15 12l-5 2.8z" fill="currentColor" stroke="none" /></svg>);
  if (k.includes("linked")) return (<svg {...common}><rect x="2.5" y="2.5" width="19" height="19" rx="3" /><path d="M7 10v7M7 7.2v.01M11 17v-4a2 2 0 0 1 4 0v4M11 11v6" /></svg>);
  if (k.includes("tik")) return (<svg {...common}><path d="M15 4c.4 2.3 1.9 3.8 4 4v2.6c-1.5 0-2.9-.5-4-1.3V15a5 5 0 1 1-5-5c.3 0 .7 0 1 .1v2.7a2.3 2.3 0 1 0 1.6 2.2V4z" /></svg>);
  if (k.includes("face")) return (<svg {...common}><path d="M14 9h2.5l.5-3H14V4.5C14 3.7 14.3 3 15.5 3H17V.2C16.6.1 15.5 0 14.5 0 12.2 0 11 1.4 11 3.9V6H8.5v3H11v9h3V9z" /></svg>);
  if (k.includes("x") || k.includes("twit")) return (<svg {...common}><path d="M4 4l16 16M20 4 4 20" /></svg>);
  return (<svg {...common}><circle cx="12" cy="12" r="9" /></svg>);
}

function LangToggle({ onDark = false }) {
  const lang = useLang();
  const ink = onDark ? "#F4F1EA" : "var(--foreground)";
  const soft = onDark ? "rgba(244,241,234,0.55)" : "var(--muted-foreground)";
  return (
    <div className="inline-flex items-center rounded-full overflow-hidden" style={{ border: `1px solid ${onDark ? "rgba(244,241,234,0.3)" : "var(--border)"}`, fontFamily: "var(--font-mono)", fontSize: "0.7rem", letterSpacing: "0.08em" }}>
      {["pl", "en"].map((l) => (
        <button key={l} onClick={() => setLang(l)}
          style={{ padding: "0.32rem 0.66rem", border: "none", cursor: "pointer", textTransform: "uppercase", fontWeight: 600,
            background: lang === l ? "var(--primary)" : "transparent",
            color: lang === l ? "var(--primary-foreground)" : soft, transition: "all .15s var(--ease)" }}>
          {l}
        </button>
      ))}
    </div>
  );
}

function ThemeToggle({ onDark = false }) {
  const [theme, set] = useTheme();
  const ink = onDark ? "#F4F1EA" : "var(--foreground)";
  return (
    <button aria-label="Toggle theme" onClick={() => set(theme === "dark" ? "light" : "dark")}
      className="inline-flex items-center justify-center rounded-full transition-all duration-200"
      style={{ width: 34, height: 34, border: `1px solid ${onDark ? "rgba(244,241,234,0.3)" : "var(--border)"}`, background: "transparent", color: ink, cursor: "pointer" }}
      onMouseEnter={(e) => (e.currentTarget.style.color = "var(--primary)")}
      onMouseLeave={(e) => (e.currentTarget.style.color = ink)}>
      {theme === "dark" ? <IconSun /> : <IconMoon />}
    </button>
  );
}

/* ---------- Navbar ---------- */
function Nav() {
  const tx = useTx();
  const [theme] = useTheme();
  const [open, setOpen] = useState(false);
  const here = currentPage();
  const logo = theme === "dark" ? "assets/logo-lockup-reversed.png" : "assets/logo-lockup.png";

  return (
    <header style={{ position: "sticky", top: 0, zIndex: 50,
      background: theme === "dark" ? "rgba(19,26,40,0.82)" : "rgba(255,255,255,0.82)",
      backdropFilter: "saturate(160%) blur(14px)", WebkitBackdropFilter: "saturate(160%) blur(14px)",
      borderBottom: "1px solid var(--border)" }}>
      <div className="mx-auto flex items-center justify-between" style={{ maxWidth: 1240, padding: "0.9rem 1.5rem" }}>
        <a href="index.html" className="flex items-center" style={{ flex: "0 0 auto" }}>
          <img src={logo} alt="Mateusz Bielecki Studios" style={{ height: 30, width: "auto" }} />
        </a>

        <nav className="hidden lg:flex items-center" style={{ gap: "2rem", fontFamily: "var(--font-sans)", fontSize: "0.82rem", fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.04em" }}>
          {NAV_ITEMS.map((it) => {
            const active = here === it.href;
            return (
              <a key={it.href} href={it.href}
                style={{ color: active ? "var(--primary)" : "var(--foreground)", textDecoration: "none", transition: "color .15s var(--ease)", paddingBottom: 2, borderBottom: active ? "1.5px solid var(--primary)" : "1.5px solid transparent" }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.color = "var(--primary)"; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.color = "var(--foreground)"; }}>
                {tx(it.label)}
              </a>
            );
          })}
        </nav>

        <div className="flex items-center" style={{ gap: "0.6rem" }}>
          <div className="hidden sm:flex items-center" style={{ gap: "0.6rem" }}>
            <LangToggle />
            <ThemeToggle />
          </div>
          <a href="kontakt.html" className="hidden sm:inline-flex items-center rounded-full font-medium transition-all duration-200"
            style={{ background: "var(--foreground)", color: "var(--background)", textDecoration: "none", padding: "0.5rem 1.15rem", fontSize: "0.8rem", fontFamily: "var(--font-sans)" }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--primary)"; e.currentTarget.style.color = "var(--primary-foreground)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "var(--foreground)"; e.currentTarget.style.color = "var(--background)"; }}>
            {tx(CTA)}
          </a>
          <button aria-label="Menu" className="lg:hidden inline-flex items-center justify-center" onClick={() => setOpen(!open)}
            style={{ width: 38, height: 38, border: "1px solid var(--border)", borderRadius: 999, background: "transparent", color: "var(--foreground)", cursor: "pointer" }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
              {open ? <path d="M6 6l12 12M18 6L6 18" /> : <path d="M3 6h18M3 12h18M3 18h18" />}
            </svg>
          </button>
        </div>
      </div>

      {/* mobile drawer */}
      {open && (
        <div className="lg:hidden" style={{ borderTop: "1px solid var(--border)", background: "var(--background)", padding: "1rem 1.5rem 1.6rem" }}>
          <nav className="flex flex-col" style={{ gap: "0.2rem" }}>
            {NAV_ITEMS.map((it) => {
              const active = here === it.href;
              return (
                <a key={it.href} href={it.href}
                  style={{ color: active ? "var(--primary)" : "var(--foreground)", textDecoration: "none", fontFamily: "var(--font-serif)", fontSize: "1.6rem", fontWeight: 500, padding: "0.5rem 0", letterSpacing: "-0.01em" }}>
                  {tx(it.label)}
                </a>
              );
            })}
          </nav>
          <div className="flex items-center justify-between" style={{ marginTop: "1.2rem" }}>
            <LangToggle />
            <div className="flex items-center" style={{ gap: "0.6rem" }}>
              <ThemeToggle />
              <a href="kontakt.html" className="inline-flex items-center rounded-full font-medium"
                style={{ background: "var(--foreground)", color: "var(--background)", textDecoration: "none", padding: "0.5rem 1.15rem", fontSize: "0.8rem" }}>
                {tx(CTA)}
              </a>
            </div>
          </div>
        </div>
      )}
    </header>
  );
}

/* ---------- Footer ---------- */
function SiteFooter() {
  const tx = useTx();
  const [sent, setSent] = useState(false);
  const moreLinks = [
    { label: FOOTER.panelLink, href: BRAND.panel, arrow: true },
    { label: FOOTER.privacy, href: "polityka-prywatnosci.html" },
    // { label: FOOTER.terms, href: "regulamin.html" }, // ukryte tymczasowo
  ];
  return (
    <footer style={{ background: "var(--brand-navy)", color: "#F4F1EA" }}>
      <div className="mx-auto" style={{ maxWidth: 1240, padding: "5rem 1.5rem 2.5rem" }}>
        <div className="grid" style={{ gridTemplateColumns: "1fr", gap: "3rem" }}>
          <div className="mb-foot-grid">
            {/* newsletter */}
            <div style={{ maxWidth: 420 }}>
              <Display as="h2" gradient={false} style={{ color: "#F4F1EA", fontSize: "clamp(2rem,4vw,2.8rem)" }}>{tx(FOOTER.heading)}</Display>
              <p style={{ color: "rgba(244,241,234,0.66)", marginTop: "1rem", lineHeight: 1.6, fontSize: "0.98rem" }}>{tx(FOOTER.blurb)}</p>
              <form onSubmit={(e) => { e.preventDefault(); const el = e.currentTarget.querySelector('input[type=email]'); window.mbSubscribe && window.mbSubscribe({ email: el ? el.value : "", form: "newsletter", fields: { source: "footer" } }); setSent(true); }} className="flex" style={{ marginTop: "1.6rem", gap: "0.5rem", maxWidth: 380 }}>
                <input type="email" required placeholder={tx(FOOTER.emailPlaceholder)}
                  style={{ flex: 1, background: "rgba(244,241,234,0.06)", border: "1px solid rgba(244,241,234,0.2)", borderRadius: 999, padding: "0.7rem 1.1rem", color: "#F4F1EA", fontFamily: "var(--font-sans)", fontSize: "0.9rem", outline: "none" }} />
                <button type="submit" className="rounded-full font-medium uppercase tracking-wide" style={{ background: "var(--primary)", color: "var(--primary-foreground)", border: "none", padding: "0.7rem 1.3rem", cursor: "pointer", fontSize: "0.78rem", fontFamily: "var(--font-sans)", whiteSpace: "nowrap" }}>
                  {tx(FOOTER.subscribe)}
                </button>
              </form>
              {sent && <p style={{ color: "var(--primary)", marginTop: "0.7rem", fontSize: "0.85rem", fontFamily: "var(--font-mono)" }}>{tx(FOOTER.subscribed)}</p>}
            </div>

            {/* nav */}
            <div>
              <div className="mb-foot-eyebrow">{tx(FOOTER.navTitle)}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: "0.7rem" }}>
                {NAV_ITEMS.map((it) => (
                  <li key={it.href}><a href={it.href} className="mb-foot-link">{tx(it.label)}</a></li>
                ))}
              </ul>
            </div>

            {/* more + socials */}
            <div>
              <div className="mb-foot-eyebrow">{tx(FOOTER.moreTitle)}</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: "0.7rem" }}>
                {moreLinks.map((it, i) => (
                  <li key={i}><a href={it.href} className="mb-foot-link">{tx(it.label)}{it.arrow ? " →" : ""}</a></li>
                ))}
              </ul>
              <div className="mb-foot-eyebrow" style={{ marginTop: "1.8rem" }}>Social</div>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: "0.7rem" }}>
                {SOCIALS.map((s) => (
                  <li key={s.label}><a href={s.href} target="_blank" rel="noopener noreferrer" className="mb-foot-link" style={{ display: "inline-flex", alignItems: "center", gap: "0.6rem" }}><SocialIcon label={s.label} /> {s.label}</a></li>
                ))}
              </ul>
            </div>
          </div>
        </div>

        <div className="flex flex-wrap items-center justify-between" style={{ marginTop: "4rem", paddingTop: "1.6rem", borderTop: "1px solid rgba(244,241,234,0.16)", gap: "1rem" }}>
          <span style={{ color: "rgba(244,241,234,0.5)", fontFamily: "var(--font-mono)", fontSize: "0.74rem", letterSpacing: "0.04em" }}>
            © 2026 {BRAND.name} · {tx(FOOTER.rights)}
          </span>
          <div className="flex items-center" style={{ gap: "1rem" }}>
            <span style={{ color: "rgba(244,241,234,0.5)", fontFamily: "var(--font-mono)", fontSize: "0.74rem", letterSpacing: "0.04em" }}>{tx(FOOTER.madeIn)}</span>
            <LangToggle onDark />
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Cookie banner + floating preferences button ---------- */
function CookieBanner() {
  const tx = useTx();
  const [choice, setChoice] = useState(() => { try { return localStorage.getItem("mb_cookie"); } catch (e) { return null; } });
  const [open, setOpen] = useState(false);
  useEffect(() => {
    if (!choice) { const t = setTimeout(() => setOpen(true), 600); return () => clearTimeout(t); }
  }, []);
  const choose = (v) => { try { localStorage.setItem("mb_cookie", v); } catch (e) {} setChoice(v); setOpen(false); };

  if (!open) {
    if (!choice) return null;
    return (
      <button aria-label={tx({ pl: "Ustawienia cookies", en: "Cookie settings" })} onClick={() => setOpen(true)}
        style={{ position: "fixed", left: 16, bottom: 16, zIndex: 85, width: 46, height: 46, borderRadius: 999, cursor: "pointer",
          background: "var(--card)", color: "var(--foreground)", border: "1px solid var(--border)", boxShadow: "var(--shadow-lg)",
          display: "flex", alignItems: "center", justifyContent: "center", transition: "transform .15s var(--ease), box-shadow .15s var(--ease)" }}
        onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.color = "var(--primary)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.color = "var(--foreground)"; }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5" />
          <circle cx="8.5" cy="10.5" r=".6" fill="currentColor" /><circle cx="12" cy="15" r=".6" fill="currentColor" /><circle cx="15.5" cy="12" r=".6" fill="currentColor" /><circle cx="9" cy="14.5" r=".6" fill="currentColor" />
        </svg>
      </button>
    );
  }

  return (
    <div style={{ position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 90, padding: "0 1rem 1rem", pointerEvents: "none" }}>
      <div className="mb-cookie-card" style={{ pointerEvents: "auto", margin: "0 auto", maxWidth: 1000, background: "var(--brand-navy)", color: "#F4F1EA", border: "1px solid rgba(244,241,234,0.16)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)", padding: "1.1rem 1.3rem", display: "flex", alignItems: "center", gap: "1.4rem", flexWrap: "wrap", position: "relative" }}>
        {choice && (
          <button aria-label={tx({ pl: "Zamknij", en: "Close" })} onClick={() => setOpen(false)}
            style={{ position: "absolute", top: 10, right: 10, width: 30, height: 30, borderRadius: 999, border: "none", background: "rgba(244,241,234,0.1)", color: "#F4F1EA", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
          </button>
        )}
        <div style={{ flex: "1 1 320px", minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: "1.05rem", marginBottom: "0.25rem" }}>{tx({ pl: "Ciasteczka", en: "Cookies" })}</div>
          <p style={{ color: "rgba(244,241,234,0.7)", fontSize: "0.88rem", lineHeight: 1.55, margin: 0, paddingRight: choice ? "1.6rem" : 0 }}>
            {tx({ pl: "Używam plików cookie, aby strona działała i żebym mógł ją ulepszać. Szczegóły w ", en: "I use cookies to run the site and to improve it. Details in the " })}
            <a href="polityka-prywatnosci.html" style={{ color: "var(--primary)", textDecoration: "underline" }}>{tx({ pl: "polityce prywatności", en: "privacy policy" })}</a>.
          </p>
        </div>
        <div className="flex items-center" style={{ gap: "0.6rem", flex: "0 0 auto" }}>
          <button onClick={() => choose("necessary")} style={{ background: choice === "necessary" ? "rgba(244,241,234,0.14)" : "transparent", border: "1px solid rgba(244,241,234,0.32)", color: "#F4F1EA", borderRadius: 999, padding: "0.6rem 1.2rem", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "0.8rem", fontWeight: 500, whiteSpace: "nowrap" }}>
            {tx({ pl: "Tylko niezbędne", en: "Only necessary" })}
          </button>
          <button onClick={() => choose("all")} style={{ background: "var(--primary)", border: "none", color: "var(--primary-foreground)", borderRadius: 999, padding: "0.6rem 1.4rem", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: "0.8rem", fontWeight: 600, whiteSpace: "nowrap" }}>
            {tx(choice ? { pl: "Akceptuję wszystkie", en: "Accept all" } : { pl: "Akceptuję", en: "Accept" })}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Nav, SiteFooter, LangToggle, ThemeToggle, CookieBanner });

/* Auto-mount the cookie banner once per page, independent of each page's App. */
(function mountCookieBanner() {
  if (document.getElementById("mb-cookie-root")) return;
  const el = document.createElement("div");
  el.id = "mb-cookie-root";
  document.body.appendChild(el);
  ReactDOM.createRoot(el).render(<CookieBanner />);
})();
