// src/shell.jsx — top chrome: logo, address switcher, search, account, cart button. Works on desktop and mobile (responsive via useMedia hook).

function useMedia(query) {
  const [m, setM] = React.useState(() => typeof window !== "undefined" && window.matchMedia(query).matches);
  React.useEffect(() => {
    const mq = window.matchMedia(query);
    const fn = () => setM(mq.matches);
    mq.addEventListener ? mq.addEventListener("change", fn) : mq.addListener(fn);
    return () => mq.removeEventListener ? mq.removeEventListener("change", fn) : mq.removeListener(fn);
  }, [query]);
  return m;
}

function TopBar({ nav, cart, onNav, onOpenCart, onOpenSearch, address, onOpenAddress, isDark, onToggleDark }) {
  const isMobile = useMedia("(max-width: 720px)");
  const cartCount = cart.items.reduce((s, x) => s + x.qty, 0);

  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 40,
      background: "oklch(from var(--bg) l c h / 0.82)",
      backdropFilter: "blur(18px) saturate(140%)",
      WebkitBackdropFilter: "blur(18px) saturate(140%)",
      borderBottom: "1px solid var(--line-soft)",
    }}>
      <div style={{
        maxWidth: 1280, margin: "0 auto",
        padding: isMobile ? "10px 16px" : "14px 28px",
        display: "flex", alignItems: "center", gap: isMobile ? 10 : 20,
      }}>
        {/* Logo */}
        <button className="btn-reset" onClick={() => onNav({ screen: "home" })}
          style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
          <OpaMark size={isMobile ? 22 : 26} />
        </button>

        {/* Address + time pill (desktop only) */}
        {!isMobile && (
          <button className="btn-reset" onClick={onOpenAddress}
            style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "7px 14px", borderRadius: 999,
              background: "var(--surface-2)", border: "1px solid var(--line)",
              fontSize: 13, color: "var(--ink-2)",
            }}>
            <Icons.Pin size={14} stroke={1.8} />
            <span style={{ color: "var(--ink)", fontWeight: 500 }}>{address?.label || "Set address"}</span>
            <span style={{ color: "var(--ink-4)" }}>·</span>
            <span>Deliver now</span>
            <Icons.ChevronDown size={13} stroke={1.8} />
          </button>
        )}

        {/* Search box */}
        <button className="btn-reset" onClick={onOpenSearch}
          style={{
            flex: 1, display: "flex", alignItems: "center", gap: 10,
            height: 44, padding: "0 16px",
            background: "var(--surface)", border: "1px solid var(--line)",
            borderRadius: 999, color: "var(--ink-4)", fontSize: 14,
            textAlign: "left",
          }}>
          <Icons.Search size={17} stroke={1.8} />
          <span>{isMobile ? "Search stores & items" : 'Search “Coke”, “sandwich”, or ask “what helps a hangover?”'}</span>
          {!isMobile && <span style={{
            marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 3,
            fontSize: 11, color: "var(--ink-4)",
          }}>
            <kbd style={{
              fontFamily: '"JetBrains Mono", monospace', fontSize: 10,
              padding: "2px 6px", borderRadius: 4,
              background: "var(--surface-2)", border: "1px solid var(--line)",
            }}>⌘K</kbd>
          </span>}
        </button>

        {/* Right side */}
        <button className="btn-reset" onClick={onToggleDark}
          aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}
          title={isDark ? "Switch to light mode" : "Switch to dark mode"}
          style={{ height: isMobile ? 38 : 44, width: isMobile ? 38 : 44, borderRadius: 999,
                   border: "1px solid var(--line)", background: "var(--surface)",
                   display: "inline-flex", alignItems: "center", justifyContent: "center",
                   color: "var(--ink-2)", flexShrink: 0 }}>
          {isDark
            ? <Icons.Sun size={isMobile ? 16 : 18} stroke={1.8} />
            : <Icons.Moon size={isMobile ? 16 : 18} stroke={1.8} />}
        </button>
        {!isMobile && (
          <button className="btn-reset" onClick={() => onNav({ screen: "orders" })}
            aria-label="Orders" title="Orders"
            style={{ height: 44, width: 44, borderRadius: 999, border: "1px solid var(--line)",
                     background: "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center",
                     color: "var(--ink-2)" }}>
            <Icons.Receipt size={18} stroke={1.8} />
          </button>
        )}
        {!isMobile && (
          <button className="btn-reset" onClick={() => onNav({ screen: "account" })}
            style={{ height: 44, width: 44, borderRadius: 999, border: "1px solid var(--line)",
                     background: "var(--surface)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <Icons.User size={18} stroke={1.8} />
          </button>
        )}
        <button className="btn-reset" onClick={onOpenCart}
          style={{
            height: 44, padding: "0 16px", borderRadius: 999,
            background: "var(--navy-fill)", color: "#fff",
            display: "inline-flex", alignItems: "center", gap: 8,
            fontSize: 14, fontWeight: 600,
          }}>
          <Icons.Bag size={17} stroke={1.8} />
          <span>{cartCount}</span>
          {!isMobile && <span style={{ opacity: 0.7, fontWeight: 400 }}>· <span className="num">{money(cart.subtotal)}</span></span>}
        </button>
      </div>
    </header>
  );
}

// Mobile bottom-nav (optional — matches mobile convention)
function MobileTabBar({ current, onNav }) {
  const isMobile = useMedia("(max-width: 720px)");
  if (!isMobile) return null;
  const tabs = [
    { id: "home", label: "Home", icon: "Home" },
    { id: "search", label: "Search", icon: "Search" },
    { id: "orders", label: "Orders", icon: "Receipt" },
    { id: "account", label: "Account", icon: "User" },
  ];
  return (
    <nav style={{
      position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 30,
      background: "oklch(from var(--bg) l c h / 0.92)",
      backdropFilter: "blur(18px)",
      borderTop: "1px solid var(--line-soft)",
      display: "grid", gridTemplateColumns: `repeat(${tabs.length}, 1fr)`,
      padding: "6px 0 calc(8px + env(safe-area-inset-bottom))",
    }}>
      {tabs.map(t => {
        const Icon = Icons[t.icon];
        const active = current === t.id;
        return (
          <button key={t.id} className="btn-reset" onClick={() => onNav({ screen: t.id })}
            style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2,
                     padding: "6px 0", color: active ? "var(--navy)" : "var(--ink-4)" }}>
            <Icon size={20} stroke={active ? 2.2 : 1.7} />
            <span style={{ fontSize: 10.5, fontWeight: active ? 600 : 500 }}>{t.label}</span>
          </button>
        );
      })}
    </nav>
  );
}

// Global site footer — shown below every screen. Mirrors the voice of
// opalink.com (neighborhood marketplace, shop independent, real humans).
function SiteFooter({ onNav }) {
  const isMobile = useMedia("(max-width: 720px)");
  const cols = [
    { title: "Marketplace", links: [
      { label: "How Opa works", to: { screen: "home" } },
      { label: "Stores near you", to: { screen: "home" } },
      { label: "Ask Opa", to: { screen: "home" } },
      { label: "Your orders", to: { screen: "orders" } },
    ]},
    { title: "For shops", links: [
      { label: "List your store" },
      { label: "Merchant support" },
      { label: "Opa for bodegas" },
      { label: "Local producers" },
    ]},
    { title: "Company", links: [
      { label: "About" },
      { label: "Press" },
      { label: "Careers" },
      { label: "Contact" },
    ]},
  ];
  return (
    <footer style={{
      borderTop: "1px solid var(--line-soft)",
      background: "var(--surface-2)",
      color: "var(--ink-2)",
      marginTop: 40,
      paddingBottom: isMobile ? 72 : 0, // clear mobile tab bar
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto",
                    padding: isMobile ? "28px 20px 24px" : "44px 28px 28px" }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: isMobile ? "1fr" : "1.4fr 1fr 1fr 1fr",
          gap: isMobile ? 24 : 32,
          marginBottom: 28,
        }}>
          <div>
            <button className="btn-reset" onClick={() => onNav({ screen: "home" })}
              style={{ display: "inline-flex", alignItems: "center", gap: 4, marginBottom: 12 }}>
              <OpaMark size={26} />
            </button>
            <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.55, color: "var(--ink-2)", maxWidth: 360 }}>
              The neighborhood marketplace — deli counters, bodegas, hardware stores, wine shops
              and the people who run them, all one tap away. Shop independent. Delivered fast.
            </p>
            <div style={{ display: "flex", gap: 8, marginTop: 16, flexWrap: "wrap" }}>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6,
                             padding: "6px 12px", borderRadius: 999,
                             background: "var(--surface)", border: "1px solid var(--line)",
                             fontSize: 12, color: "var(--ink-3)" }}>
                <Icons.Pin size={12} stroke={1.8} /> New York · LA · Chicago
              </span>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6,
                             padding: "6px 12px", borderRadius: 999,
                             background: "var(--surface)", border: "1px solid var(--line)",
                             fontSize: 12, color: "var(--ink-3)" }}>
                <Icons.ShieldCheck size={12} stroke={1.8} /> Real humans, real receipts
              </span>
            </div>
          </div>
          {cols.map(c => (
            <div key={c.title}>
              <div className="uppercase-mono" style={{ marginBottom: 10 }}>{c.title}</div>
              <ul style={{ listStyle: "none", margin: 0, padding: 0,
                           display: "flex", flexDirection: "column", gap: 8 }}>
                {c.links.map(l => (
                  <li key={l.label}>
                    <button className="btn-reset"
                      onClick={() => l.to && onNav(l.to)}
                      style={{ fontSize: 13, color: "var(--ink-2)", padding: 0,
                               textAlign: "left", cursor: l.to ? "pointer" : "default",
                               opacity: l.to ? 1 : 0.85 }}>
                      {l.label}
                    </button>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>

        <div style={{
          paddingTop: 18, borderTop: "1px solid var(--line)",
          display: "flex", alignItems: "center", justifyContent: "space-between",
          gap: 16, flexWrap: "wrap",
        }}>
          <span style={{ fontSize: 12, color: "var(--ink-4)" }}>
            © {new Date().getFullYear()} Opa! Marketplace. Built on real blocks.
          </span>
          <div style={{ display: "flex", gap: 18, flexWrap: "wrap" }}>
            {["Terms", "Privacy", "Accessibility", "Cookie settings"].map(t => (
              <span key={t} style={{ fontSize: 12, color: "var(--ink-4)" }}>{t}</span>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { TopBar, MobileTabBar, useMedia, SiteFooter });
