// Shared components: Logo, Nav, Footer, ProductCard, FlowerImg
// Loaded as global components on every page.

const { useState, useEffect, useRef } = React;

// === Cart store (localStorage, syncs across tabs/pages) ===
const CART_KEY = "hbouquet.cart";

// Module-level cart store with subscriber pattern so multiple useCart
// consumers on the same page stay in sync without infinite loops.
const _cartStore = {
  items: (() => {
    try { return JSON.parse(localStorage.getItem(CART_KEY) || "[]"); }
    catch (e) { return []; }
  })(),
  subs: new Set(),
  set(items) {
    this.items = items;
    try { localStorage.setItem(CART_KEY, JSON.stringify(items)); } catch (e) {}
    this.subs.forEach((fn) => fn(items));
  },
  subscribe(fn) {
    this.subs.add(fn);
    return () => this.subs.delete(fn);
  },
};

window.useCart = function useCart() {
  const [items, setLocal] = useState(_cartStore.items);
  useEffect(() => {
    const unsub = _cartStore.subscribe((next) => setLocal(next));
    // Cross-tab sync via storage event
    const onStorage = (e) => {
      if (e.key !== CART_KEY) return;
      try { _cartStore.set(JSON.parse(e.newValue || "[]")); }
      catch (err) {}
    };
    window.addEventListener("storage", onStorage);
    return () => { unsub(); window.removeEventListener("storage", onStorage); };
  }, []);
  const setItems = (updater) => {
    const next = typeof updater === "function" ? updater(_cartStore.items) : updater;
    _cartStore.set(next);
  };
  const add = (item) => setItems((prev) => {
    const key = `${item.id}__${item.sizeLabel}`;
    const idx = prev.findIndex((p) => `${p.id}__${p.sizeLabel}` === key);
    if (idx >= 0) {
      const copy = [...prev];
      copy[idx] = { ...copy[idx], qty: copy[idx].qty + (item.qty || 1) };
      return copy;
    }
    return [...prev, { ...item, qty: item.qty || 1 }];
  });
  const remove = (key) => setItems((prev) => prev.filter((p) => `${p.id}__${p.sizeLabel}` !== key));
  const setQty = (key, qty) => setItems((prev) => prev.map((p) =>
    `${p.id}__${p.sizeLabel}` === key ? { ...p, qty: Math.max(1, qty) } : p
  ));
  const clear = () => setItems([]);
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  const count = items.reduce((s, i) => s + i.qty, 0);
  return { items, add, remove, setQty, clear, total, count };
};

// === Aesthetic mode (tweak persisted in localStorage) ===
window.useAesthetic = function useAesthetic() {
  const [aesthetic, setAesthetic] = useState(() => localStorage.getItem("hb.aesthetic") || "editorial");
  const [mode, setMode] = useState(() => localStorage.getItem("hb.mode") || "light");
  useEffect(() => {
    document.documentElement.setAttribute("data-aesthetic", aesthetic);
    document.documentElement.setAttribute("data-mode", mode);
    localStorage.setItem("hb.aesthetic", aesthetic);
    localStorage.setItem("hb.mode", mode);
  }, [aesthetic, mode]);
  return { aesthetic, setAesthetic, mode, setMode };
};

// === Theme toggle (light / dark) ===
window.ThemeToggle = function ThemeToggle({ size = 36 }) {
  const [mode, setMode] = useState(() => (window.HBTheme ? window.HBTheme.get() : 'light'));
  useEffect(() => {
    const onChange = (e) => setMode(e.detail.mode);
    window.addEventListener('hb:theme', onChange);
    return () => window.removeEventListener('hb:theme', onChange);
  }, []);
  const isDark = mode === 'dark';
  return (
    <button
      type="button"
      onClick={() => window.HBTheme && window.HBTheme.toggle()}
      aria-label={isDark ? 'Cambiar a modo claro' : 'Cambiar a modo oscuro'}
      title={isDark ? 'Modo claro' : 'Modo oscuro'}
      style={{
        width: size + 'px',
        height: size + 'px',
        borderRadius: '999px',
        border: '1px solid var(--rule)',
        background: 'transparent',
        color: 'var(--ink-soft)',
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        cursor: 'pointer',
        transition: 'all 0.2s ease',
      }}
    >
      {isDark ? (
        // Sun
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
          <circle cx="12" cy="12" r="4"/>
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
        </svg>
      ) : (
        // Moon
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
        </svg>
      )}
    </button>
  );
};

// === Logo ===
window.Logo = function Logo({ size = "md", clickable = true }) {
  const sizes = { sm: 36, md: 56, lg: 100, xl: 160 };
  const px = sizes[size] || sizes.md;
  const inner = (
    <span className="logo-mark" style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", lineHeight: 1 }}>
      <img src="/logo.png" alt="H Bouquet" style={{ height: px + "px", width: "auto", display: "block" }} />
      <span className="mark-tag" style={{ marginTop: "4px" }}>flor de vida</span>
    </span>
  );
  return clickable ? <a href="index.html" aria-label="H Bouquet — Inicio">{inner}</a> : inner;
};

// === Wordmark — top of nav ===
window.Wordmark = function Wordmark() {
  return (
    <a href="index.html" className="wordmark" aria-label="H Bouquet" style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", lineHeight: 1 }}>
      <div style={{ display: "inline-flex", alignItems: "center", gap: "10px" }}>
        <img src="/logo.png" alt="" style={{ height: "36px", width: "auto", display: "block" }} />
        <span style={{
          fontFamily: "var(--serif-display)",
          fontSize: "18px",
          letterSpacing: "0.34em",
          fontWeight: 400,
          color: "var(--ink)",
        }}>BOUQUET</span>
      </div>
      <span style={{
        display: "block",
        fontFamily: "var(--serif)",
        fontStyle: "italic",
        fontSize: "10px",
        color: "var(--accent)",
        letterSpacing: "0.06em",
        textAlign: "center",
        marginTop: "4px",
      }}>flor de vida</span>
    </a>
  );
};

// === Auth state hook (lightweight; checks /api/auth/me once per page) ===
window.useAuthUser = function useAuthUser() {
  const [user, setUser] = useState(null);
  const [loaded, setLoaded] = useState(false);
  useEffect(() => {
    fetch('/api/auth/me', { credentials: 'same-origin' })
      .then(r => r.ok ? r.json() : { user: null })
      .then(d => { setUser(d.user || null); setLoaded(true); })
      .catch(() => setLoaded(true));
  }, []);
  return { user, loaded };
};

// === Nav ===
window.Nav = function Nav({ active }) {
  const cart = useCart();
  const { user } = useAuthUser();
  const links = [
    { href: "catalogo.html", label: "Catálogo", id: "catalogo" },
    { href: "agendar.html", label: "Agendar", id: "agendar" },
    { href: "historia.html", label: "Nuestra Historia", id: "historia" },
    { href: "entrega.html", label: "Pago & Entrega", id: "entrega" },
    { href: "contacto.html", label: "Contacto", id: "contacto" },
  ];

  const accountHref = !user ? "/login" : (user.role === 'admin' ? "/admin" : "/profile");
  const accountLabel = !user ? "Iniciar sesión" : (user.role === 'admin' ? "Panel admin" : "Mi cuenta");

  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-links">
          {links.slice(0, 3).map((l) => (
            <a key={l.id} href={l.href} className={active === l.id ? "active" : ""}>{l.label}</a>
          ))}
        </div>
        <Wordmark />
        <div className="nav-right">
          <div className="nav-links" style={{ gap: "20px" }}>
            {links.slice(3).map((l) => (
              <a key={l.id} href={l.href} className={active === l.id ? "active" : ""}>{l.label}</a>
            ))}
          </div>
          <ThemeToggle />
          <a
            href={accountHref}
            className="nav-account-btn"
            style={{
              display: "inline-flex",
              alignItems: "center",
              gap: "8px",
              padding: "8px 18px",
              borderRadius: "999px",
              border: `1px solid ${user ? "var(--accent)" : "var(--ink)"}`,
              color: user ? "var(--accent)" : "var(--ink)",
              fontFamily: "var(--sans)",
              fontSize: "12px",
              fontWeight: 500,
              letterSpacing: "0.12em",
              textTransform: "uppercase",
              transition: "all 0.2s ease",
              whiteSpace: "nowrap",
            }}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
              <circle cx="12" cy="8" r="4"/>
              <path d="M4 21a8 8 0 0116 0"/>
            </svg>
            {accountLabel}
          </a>
          <a href="agendar.html" className="nav-cart" aria-label="Carrito de ramos">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
              <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/>
              <line x1="3" y1="6" x2="21" y2="6"/>
              <path d="M16 10a4 4 0 01-8 0"/>
            </svg>
            {cart.count > 0 && <span className="nav-cart-count">{cart.count}</span>}
          </a>
        </div>
      </div>
    </nav>
  );
};

// === Footer ===
window.Footer = function Footer() {
  return (
    <footer className="footer">
      <div className="container-wide">
        <div className="footer-grid">
          <div>
            <div style={{ marginBottom: "20px" }}><Logo size="md" clickable={false} /></div>
            <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: "16px", color: "var(--ink-soft)", maxWidth: "320px" }}>
              "El arte de expresar lo que sientes a través de la pureza y belleza de una flor."
            </p>
          </div>
          <div>
            <h4>Comprar</h4>
            <ul>
              <li><a href="catalogo.html">Catálogo completo</a></li>
              <li><a href="catalogo.html?flower=rosas">Rosas</a></li>
              <li><a href="catalogo.html?flower=gerberas">Gerberas</a></li>
              <li><a href="catalogo.html?flower=lisianthus">Lisianthus</a></li>
              <li><a href="agendar.html">Agendar ramo</a></li>
            </ul>
          </div>
          <div>
            <h4>Información</h4>
            <ul>
              <li><a href="historia.html">Nuestra historia</a></li>
              <li><a href="entrega.html">Pago & entrega</a></li>
              <li><a href="faq.html">Información importante</a></li>
              <li><a href="contacto.html">Contacto</a></li>
            </ul>
          </div>
          <div>
            <h4>Contacto</h4>
            <ul>
              <li>Av. México 68, No.8</li>
              <li>Infonavit 1ro de Mayo</li>
              <li><a href={`https://wa.me/52${BRAND.whatsapp}`} target="_blank">WhatsApp · {BRAND.whatsapp}</a></li>
              <li><a href={`https://instagram.com/${BRAND.instagram}`} target="_blank">@{BRAND.instagram}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 H Bouquet · Flor de vida</span>
          <span>Oaxaca, México</span>
        </div>
      </div>
    </footer>
  );
};

// === Flower image with placeholder fallback ===
window.FlowerImg = function FlowerImg({ src, label, ratio = "4 / 5", style }) {
  const [error, setError] = useState(false);
  return (
    <div className={"flower-img" + (src && !error ? " has-photo" : "")} style={{ aspectRatio: ratio, ...style }}>
      {src && !error ? (
        <img
          src={src}
          alt={label || ""}
          onError={() => setError(true)}
          style={{ width: "100%", height: "100%", objectFit: "cover" }}
        />
      ) : (
        <span className="flower-img-label">{label || "imagen del ramo"}</span>
      )}
    </div>
  );
};

// === Product card ===
window.ProductCard = function ProductCard({ product, index = 0 }) {
  const minPrice = Math.min(...product.sizes.map((s) => s.price));
  const maxPrice = Math.max(...product.sizes.map((s) => s.price));
  const priceLabel = minPrice === maxPrice
    ? `$${minPrice.toLocaleString("es-MX")}`
    : `$${minPrice.toLocaleString("es-MX")} – $${maxPrice.toLocaleString("es-MX")}`;
  return (
    <a href={`producto.html?id=${product.id}`} className="card product-card reveal" style={{ display: "block", transitionDelay: `${(index % 4) * 60}ms` }}>
      <FlowerImg src={product.img} label={product.name} ratio="4 / 5" />
      <div style={{ padding: "20px 22px 24px" }}>
        <div className="eyebrow" style={{ marginBottom: "8px" }}>{product.flowerLabel}</div>
        <h3 style={{ fontSize: "26px", marginBottom: "6px" }}>{product.name}</h3>
        <p className="italic-serif" style={{ color: "var(--ink-mute)", fontSize: "14px", marginBottom: "16px" }}>
          {product.tagline}
        </p>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", borderTop: "1px solid var(--rule)", paddingTop: "14px" }}>
          <span className="price">{priceLabel}</span>
          <span style={{ fontSize: "11px", letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
            Ver →
          </span>
        </div>
      </div>
    </a>
  );
};

// === Reveal-on-scroll observer ===
window.useReveal = function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.in)");
    if (!("IntersectionObserver" in window)) {
      els.forEach((e) => e.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  });
};

// === Aesthetic + Mode tweaks panel (loaded if TweaksPanel is available) ===
window.HBTweaks = function HBTweaks() {
  const aes = useAesthetic();
  if (typeof window.TweaksPanel === "undefined") return null;
  const { TweaksPanel, TweakSection, TweakRadio, TweakToggle } = window;
  return (
    <TweaksPanel title="Tweaks" defaultOpen={false}>
      <TweakSection title="Estética">
        <TweakRadio
          label="Dirección"
          value={aes.aesthetic}
          onChange={aes.setAesthetic}
          options={[
            { value: "editorial", label: "Editorial" },
            { value: "romantico", label: "Romántico" },
            { value: "artesanal", label: "Artesanal" },
          ]}
        />
        <TweakToggle
          label="Modo oscuro botánico"
          value={aes.mode === "dark"}
          onChange={(v) => aes.setMode(v ? "dark" : "light")}
        />
      </TweakSection>
    </TweaksPanel>
  );
};

// === Format MXN ===
window.fmtMXN = (n) => `$${Number(n).toLocaleString("es-MX")}`;
