// ---------- CATALOG TRANSFORM ----------
const CATEGORY_TONES = {
  diver:  { bg: "#E8E4DA", accent: "#212A3D", label: "Diver" },
  dress:  { bg: "#F2EDE0", accent: "#914F2C", label: "Dress" },
  gmt:    { bg: "#DAD6CD", accent: "#212A3D", label: "GMT · Travel" },
  chrono: { bg: "#E4E1D9", accent: "#5A4A38", label: "Chronograph" },
  sport:  { bg: "#E2DED4", accent: "#212A3D", label: "Sport" },
  other:  { bg: "#E8E4DA", accent: "#303747", label: "Timepiece" },
};

function transformCatalogItem(item) {
  const tone = CATEGORY_TONES[item.category] || CATEGORY_TONES.other;
  const modelLine = item.model || "Timepiece";
  return {
    id: item.id,
    brand: item.brand,
    model: modelLine,
    reference: item.reference || "",
    price: item.price_usd || 0,
    price_display: item.price_display,
    condition: item.condition,
    image: item.hero_image,
    hero_image: item.hero_image,
    images: item.images || [],
    tone: { ...tone, type: item.category },
    // Solo datos que el catálogo trae de verdad — nada de specs genéricas
    // inventadas (movimiento, cristal, resistencia al agua) iguales para los 599.
    specs: {
      reference: item.reference || "—",
      case: [item.case_size, item.material].filter(Boolean).join(" · ") || "—",
      dial: item.dial || "—",
      condition: item.condition,
    },
    summary: item.summary,
    tags: [item.material, item.dial && `${item.dial} dial`, item.condition]
      .filter(Boolean),
    category: item.category,
    category_label: item.category_label,
    title: item.title,
    published_at: item.published_at,
    updated_at: item.updated_at,
  };
}

// ---------- HASH ROUTING ----------
// Rutas: #/ (home), #/shop?category=&brand=&model=&q=&unworn=1, #/watch/<id>,
// #/article/<slug> y las páginas estáticas. El hash es la fuente de verdad:
// back/forward del navegador y links compartidos funcionan sin servidor.
const STATIC_PAGES = ["shop", "sell", "journal", "auth", "about", "accessories", "privacy", "terms"];

function parseHash() {
  const raw = (window.location.hash || "").replace(/^#\/?/, "");
  const [path, query] = raw.split("?");
  const segs = (path || "").split("/").filter(Boolean);
  const params = new URLSearchParams(query || "");
  if (segs[0] === "watch" && segs[1]) return { page: "product", watchId: decodeURIComponent(segs[1]) };
  if (segs[0] === "article" && segs[1]) return { page: "article", articleSlug: decodeURIComponent(segs[1]) };
  if (segs[0] === "shop") {
    const filters = {};
    ["category", "brand", "model", "q"].forEach(k => { const v = params.get(k); if (v) filters[k] = v; });
    if (params.get("unworn") === "1") filters.unworn = true;
    return { page: "shop", shopFilters: Object.keys(filters).length ? filters : null };
  }
  if (STATIC_PAGES.includes(segs[0])) return { page: segs[0] };
  return { page: "home" };
}

// Splash mientras llega el catálogo real: antes se veían 4 relojes de muestra
// de marcas inventadas hasta que respondía /api/catalog.
const LoadingScreen = () => (
  <div style={{ position: "fixed", inset: 0, background: "var(--bg)", display: "grid", placeItems: "center", zIndex: 100 }}>
    <div style={{ textAlign: "center" }}>
      <Monogram size={56} />
      <div className="serif" style={{ marginTop: 18, fontSize: 20, color: "var(--ink)", letterSpacing: "0.14em" }}>
        BRYTEZ
      </div>
      <div style={{
        marginTop: 12, fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase",
        color: "var(--muted)", animation: "gmrPulse 1.6s ease-in-out infinite",
      }}>
        Curating the collection
      </div>
      <style>{`@keyframes gmrPulse { 0%, 100% { opacity: 0.35 } 50% { opacity: 1 } }`}</style>
    </div>
  </div>
);

const App = () => {
  const initialRoute = React.useMemo(parseHash, []);
  const [page, setPage] = React.useState(initialRoute.page);
  const [watchId, setWatchId] = React.useState(initialRoute.watchId || null);
  const [articleSlug, setArticleSlug] = React.useState(initialRoute.articleSlug || null);
  const [inquiryWatch, setInquiryWatch] = React.useState(null);
  const [inquiryLead, setInquiryLead] = React.useState(null);
  const [inquiryOpen, setInquiryOpen] = React.useState(false);
  const [mobileMenu, setMobileMenu] = React.useState(false);
  const [catalogVersion, setCatalogVersion] = React.useState(0);
  const [catalogLoading, setCatalogLoading] = React.useState(true);
  const [shopFilters, setShopFilters] = React.useState(initialRoute.shopFilters || {});

  const applyRoute = (r) => {
    setPage(r.page);
    setWatchId(r.watchId || null);
    setArticleSlug(r.articleSlug || null);
    // Siempre objeto nuevo: un re-click en Shop (misma ruta) también debe
    // re-aplicar los filtros de la URL — o resetearlos si viene limpia.
    setShopFilters(r.shopFilters || {});
    // El modal no debe sobrevivir a un cambio de página: con el botón atrás se
    // quedaba abierto encima de otra sección.
    setInquiryOpen(false);
  };

  React.useEffect(() => {
    const onHash = () => applyRoute(parseHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Navega escribiendo el hash. Si el hash destino coincide con el actual
  // (p.ej. re-click en Shop estando ya ahí), aplica la ruta a mano porque no
  // habrá evento hashchange.
  const go = (hash) => {
    if (window.location.hash === hash) applyRoute(parseHash());
    else window.location.hash = hash;
  };

  React.useEffect(() => {
    let cancelled = false;
    fetch("/api/catalog", { cache: "no-store" })
      .then((r) => r.ok ? r.json() : Promise.reject(r.status))
      .then((data) => {
        if (cancelled) return;
        const items = (data.watches || []).map(transformCatalogItem);
        if (items.length > 0) {
          WATCHES.length = 0;
          WATCHES.push(...items);
          setCatalogVersion((v) => v + 1);
        }
        setCatalogLoading(false);
      })
      .catch((err) => {
        console.error("[GMR] Catalog load failed:", err);
        setCatalogLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  const openWatch = (id) => go(`#/watch/${encodeURIComponent(id)}`);
  const openArticle = (slug) => go(`#/article/${encodeURIComponent(slug)}`);
  // Abre el shop; con categoría (tarjetas del home), entra ya filtrado.
  const openShop = (category = null) =>
    go(typeof category === "string" && category ? `#/shop?category=${encodeURIComponent(category)}` : "#/shop");
  const goHome = (maybeOpenId) => {
    if (maybeOpenId && typeof maybeOpenId === "string") openWatch(maybeOpenId);
    else go("#/");
  };
  // Accepts a watch (from the shop/product pages) or a lead descriptor
  // ({ kind, details, prefill, ... }) from a page that collected its own data.
  const openInquiry = (arg) => {
    const isLead = arg && typeof arg === "object" && arg.kind;
    setInquiryWatch(isLead ? null : arg || null);
    setInquiryLead(isLead ? arg : null);
    setInquiryOpen(true);
  };
  const nav = (p) => {
    if (p === "shop") openShop();
    else if (STATIC_PAGES.includes(p)) go(`#/${p}`);
    else go("#/");
  };

  // Primer paint sin catálogo: splash de marca en vez de secciones vacías.
  // Si el fetch falla (catalogLoading false y 0 relojes), se muestra la web
  // normal — el contenido editorial funciona sin catálogo.
  if (catalogLoading && WATCHES.length === 0) {
    return <LoadingScreen />;
  }

  return (
    <>
      <Header
        page={page}
        onNav={nav}
        onMobileMenu={() => setMobileMenu(true)}
      />

      {page === "home" && (
        <LandingPage onOpenWatch={openWatch} onInquire={openInquiry} onViewAll={() => nav("shop")} onShopCategory={openShop} onSell={() => nav("sell")} onNav={nav} onOpenArticle={openArticle} />
      )}
      {page === "product" && (
        <ProductPage
          watchId={watchId}
          onHome={(maybeId) => goHome(maybeId)}
          onShop={() => openShop()}
          onInquire={openInquiry}
          catalogReady={!catalogLoading}
        />
      )}
      {page === "sell" && (
        <SellPage onHome={() => go("#/")} onInquire={openInquiry} />
      )}
      {page === "journal" && (
        <JournalPage
          onHome={() => go("#/")}
          onOpenPost={openArticle}
        />
      )}
      {page === "article" && (
        <ArticlePage
          slug={articleSlug}
          onHome={() => go("#/")}
          onJournal={() => go("#/journal")}
          onOpenPost={openArticle}
          onInquire={openInquiry}
        />
      )}
      {page === "auth" && (
        <AuthenticationPage onHome={() => go("#/")} onInquire={openInquiry} />
      )}
      {page === "about" && (
        <AboutPage onHome={() => go("#/")} onInquire={openInquiry} />
      )}
      {page === "shop" && (
        <ShopPage onHome={() => go("#/")} onOpenWatch={openWatch} onInquire={openInquiry} initialFilters={shopFilters} />
      )}
      {page === "accessories" && (
        <AccessoriesPage onHome={() => go("#/")} onInquire={openInquiry} />
      )}
      {page === "privacy" && (
        <PrivacyPage onHome={() => go("#/")} onNav={nav} />
      )}
      {page === "terms" && (
        <TermsPage onHome={() => go("#/")} onNav={nav} />
      )}

      <Footer onNav={nav} onInquire={openInquiry} />
      <WhatsAppFloat onClick={() => openInquiry(null)} />

      {inquiryOpen && (
        <InquiryModal watch={inquiryWatch} lead={inquiryLead} onClose={() => setInquiryOpen(false)} />
      )}

      {mobileMenu && (
        <MobileMenu
          onClose={() => setMobileMenu(false)}
          onNav={(p) => { setMobileMenu(false); nav(p); }}
          onInquire={() => { setMobileMenu(false); openInquiry(null); }}
        />
      )}
    </>
  );
};

const MobileMenu = ({ onClose, onNav, onInquire }) => (
  <div
    onClick={onClose}
    style={{
      position: "fixed", inset: 0, zIndex: 70,
      background: "rgba(15,15,14,0.45)",
    }}
  >
    <div
      onClick={(e) => e.stopPropagation()}
      style={{
        position: "absolute", right: 0, top: 0, bottom: 0,
        width: "min(340px, 86vw)",
        background: "#fff",
        padding: 28,
        display: "flex", flexDirection: "column", gap: 20,
        animation: "slideIn .28s ease",
      }}
    >
      <style>{`@keyframes slideIn { from { transform: translateX(20px); opacity: 0 } to { transform: translateX(0); opacity: 1 } }`}</style>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <Monogram size={36} />
        <button onClick={onClose}><IconClose size={22} /></button>
      </div>
      <nav style={{ display: "grid", gap: 4, marginTop: 14 }}>
        {[
          { l: "Shop", k: "shop" },
          { l: "Accessories", k: "accessories" },
          { l: "Sell", k: "sell" },
          { l: "Journal", k: "journal" },
          { l: "Authentication", k: "auth" },
          { l: "About", k: "about" },
        ].map((it) => (
          <button key={it.l} onClick={() => onNav(it.k)} style={{
            fontFamily: "var(--serif)", fontSize: 24, color: "var(--ink)",
            padding: "10px 0", borderBottom: "1px solid var(--rule)",
            textAlign: "left",
          }}>{it.l}</button>
        ))}
      </nav>
      <div style={{ marginTop: "auto", display: "grid", gap: 10 }}>
        <PrimaryButton full icon={<IconWhatsApp size={18} color="#fff" />} onClick={onInquire}>
          Inquire via WhatsApp
        </PrimaryButton>
        <div style={{ fontSize: 12, color: "var(--muted)", textAlign: "center" }}>
          Mon–Fri · 9am–7pm ET
        </div>
      </div>
    </div>
  </div>
);

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
