// EQUIPOS CATÁLOGO — alimentado por /admin/api/products.php
const { useState, useEffect, useMemo } = React;

const BRAND_LABELS = {
  apple: "Apple", samsung: "Samsung", motorola: "Motorola",
  xiaomi: "Xiaomi", huawei: "Huawei", google: "Google", otros: "Otros",
};

function badgeStyle(label) {
  const v = (label || "").toLowerCase();
  if (v.includes("oferta") || v.startsWith("-")) return { bg: "var(--brand)", fg: "#fff" };
  if (v.includes("nuevo")) return { bg: "var(--ink)", fg: "#fff" };
  if (v.includes("5g"))    return { bg: "var(--paper-2)", fg: "var(--ink-2)" };
  return { bg: "var(--paper-2)", fg: "var(--ink-2)" };
}

function ProductCard({ p }) {
  const href = window.balUrl(`equipo.html?slug=${encodeURIComponent(p.slug)}`);
  const primary = p.badges && p.badges.length ? p.badges[0] : null;
  const bs = primary ? badgeStyle(primary) : null;
  const [imgFailed, setImgFailed] = useState(false);
  const hasImg = !!p.image && !imgFailed;  // si la URL falla al cargar, caemos al mock
  const savings = p.price_old && p.price_old > p.price ? p.price_old - p.price : 0;

  return (
    <a href={href} className="card" style={{
      padding: 24, display: "flex", flexDirection: "column", gap: 16, color: "var(--ink)",
      minHeight: 460,
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-3)", letterSpacing: "0.05em", textTransform: "uppercase" }}>
          {BRAND_LABELS[p.brand] || p.brand}
        </span>
        {primary && bs && (
          <span className="tag" style={{ background: bs.bg, color: bs.fg, fontSize: 11, fontWeight: 600 }}>
            {primary}
          </span>
        )}
      </div>

      <div style={{
        height: 240, display: "flex", justifyContent: "center", alignItems: "center",
        padding: 12, background: "linear-gradient(180deg, var(--paper-2), transparent)", borderRadius: 16,
        overflow: "hidden",
      }}>
        {hasImg ? (
          <img src={p.image} alt={p.name} loading="lazy" referrerPolicy="no-referrer"
            onError={() => setImgFailed(true)}
            style={{ maxHeight: "100%", maxWidth: "100%", objectFit: "contain", display: "block" }} />
        ) : (
          <window.PhoneMock width={130} body="#1a1a1c" screen="linear-gradient(160deg,#2a2a2c,#0a0a0c)" />
        )}
      </div>

      <div>
        <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: "-0.012em" }}>{p.name}</div>
        {p.spec && <div className="caption" style={{ marginTop: 4 }}>{p.spec}</div>}
        {p.plan_tag && (
          <div style={{ marginTop: 6, fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--brand)" }}>
            {p.plan_tag}
          </div>
        )}
      </div>

      <div style={{ marginTop: "auto" }}>
        {p.price > 0 ? (
          <>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, flexWrap: "wrap" }}>
              <span style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.015em", color: "var(--brand)" }}>
                RD${Math.round(p.price).toLocaleString()}
              </span>
              {p.price_old && (
                <span style={{ fontSize: 13, color: "var(--ink-4)", textDecoration: "line-through" }}>
                  RD${Math.round(p.price_old).toLocaleString()}
                </span>
              )}
            </div>
            {savings > 0 && (
              <div style={{ fontSize: 12, color: "var(--brand)", fontWeight: 600, marginTop: 4 }}>
                Ahorra RD${Math.round(savings).toLocaleString()}
              </div>
            )}
          </>
        ) : (
          <div style={{ fontSize: 14, color: "var(--ink-3)", fontWeight: 500 }}>Precio a consultar</div>
        )}
      </div>
    </a>
  );
}

// Category enum → Spanish label (matches Claro "Tipo de equipo")
const CAT_LABELS = {
  telefono:   "Smartphones",
  modem:      "Routers",
  tablet:     "Tablets",
  smartwatch: "Smartwatches",
  accesorio:  "Accesorios",
};

function App() {
  const [items, setItems]   = useState([]);
  const [status, setStatus] = useState("loading"); // loading | ok | error | empty
  const [error, setError]   = useState(null);

  // ── Filtros (matchea la tienda Claro) ──────────────────────────────────
  const [sortBy, setSortBy]   = useState("reciente"); // reciente | vendido | precio-asc | precio-desc
  const [onlyOffer, setOffer] = useState(false);
  const [onlyFree, setFree]   = useState(false);
  const [selBrands, setBrands]= useState(() => new Set());
  const [selTypes, setTypes]  = useState(() => new Set());
  const [priceMin, setMin]    = useState("");
  const [priceMax, setMax]    = useState("");
  const [showFilters, setShowFilters] = useState(false); // mobile toggle

  useEffect(() => {
    const url = window.balUrl("admin/api/products.php?limit=100");
    fetch(url, { headers: { Accept: "application/json" } })
      .then((r) => { if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); })
      .then((d) => {
        if (!d.ok) throw new Error(d.error || "API error");
        setItems(d.items || []);
        setStatus(d.items && d.items.length ? "ok" : "empty");
      })
      .catch((e) => { setError(e.message); setStatus("error"); });
  }, []);

  // Marcas disponibles (auto-derivadas del catálogo real)
  const availBrands = useMemo(() => {
    const set = new Set(items.map((p) => p.brand).filter(Boolean));
    const ordered = ["apple","samsung","motorola","xiaomi","huawei","google","honor","lg","alcatel"].filter((b) => set.has(b));
    const rest = [...set].filter((b) => !ordered.includes(b)).sort();
    return [...ordered, ...rest];
  }, [items]);

  // Tipos de equipo disponibles
  const availTypes = useMemo(() => {
    const set = new Set(items.map((p) => p.category).filter(Boolean));
    return ["telefono","modem","tablet","smartwatch","accesorio"].filter((c) => set.has(c));
  }, [items]);

  const toggleSet = (setter) => (val) => setter((prev) => {
    const next = new Set(prev);
    next.has(val) ? next.delete(val) : next.add(val);
    return next;
  });
  const toggleBrand = toggleSet(setBrands);
  const toggleType  = toggleSet(setTypes);

  const hasActive = selBrands.size || selTypes.size || onlyOffer || onlyFree || priceMin || priceMax || sortBy !== "reciente";
  function resetFilters() {
    setBrands(new Set()); setTypes(new Set()); setOffer(false); setFree(false);
    setMin(""); setMax(""); setSortBy("reciente");
  }

  // Aplicar filtros + orden
  const filtered = useMemo(() => {
    let out = items.slice();
    if (selBrands.size) out = out.filter((p) => selBrands.has(p.brand));
    if (selTypes.size)  out = out.filter((p) => selTypes.has(p.category));
    if (onlyOffer)      out = out.filter((p) => p.price_old && p.price_old > p.price);
    if (onlyFree)       out = out.filter((p) => !p.price || p.price === 0);
    const min = parseFloat(priceMin), max = parseFloat(priceMax);
    if (!isNaN(min)) out = out.filter((p) => (p.price || 0) >= min);
    if (!isNaN(max)) out = out.filter((p) => (p.price || 0) <= max);
    switch (sortBy) {
      case "vendido":    out.sort((a, b) => (b.featured - a.featured) || (a.sort_order - b.sort_order)); break;
      case "precio-asc": out.sort((a, b) => (a.price || 0) - (b.price || 0)); break;
      case "precio-desc":out.sort((a, b) => (b.price || 0) - (a.price || 0)); break;
      default:           out.sort((a, b) => String(b.created_at || "").localeCompare(String(a.created_at || ""))); // reciente
    }
    return out;
  }, [items, selBrands, selTypes, onlyOffer, onlyFree, priceMin, priceMax, sortBy]);

  // ── Componentes de filtro ──────────────────────────────────────────────
  const FilterGroup = ({ title, children }) => (
    <div style={{ paddingBottom: 18, marginBottom: 18, borderBottom: "1px solid var(--line)" }}>
      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 12 }}>{title}</div>
      {children}
    </div>
  );
  const Check = ({ checked, onChange, label }) => (
    <label style={{ display: "flex", alignItems: "center", gap: 10, padding: "5px 0", cursor: "pointer", fontSize: 14, color: "var(--ink-2)" }}>
      <input type="checkbox" checked={checked} onChange={onChange}
        style={{ width: 17, height: 17, accentColor: "var(--brand)", cursor: "pointer", flexShrink: 0 }} />
      {label}
    </label>
  );

  const filtersUI = (
    <>
      <FilterGroup title="Ordenar por">
        {[["reciente","Más reciente"],["vendido","Más vendido"],["precio-asc","Precio: menor"],["precio-desc","Precio: mayor"]].map(([v,l]) => (
          <label key={v} style={{ display: "flex", alignItems: "center", gap: 10, padding: "5px 0", cursor: "pointer", fontSize: 14, color: "var(--ink-2)" }}>
            <input type="radio" name="eq-sort" checked={sortBy === v} onChange={() => setSortBy(v)}
              style={{ width: 16, height: 16, accentColor: "var(--brand)", cursor: "pointer" }} />
            {l}
          </label>
        ))}
        <div style={{ height: 8 }} />
        <Check checked={onlyOffer} onChange={() => setOffer(!onlyOffer)} label="En oferta" />
        <Check checked={onlyFree}  onChange={() => setFree(!onlyFree)}   label="Gratis" />
      </FilterGroup>

      {availBrands.length > 0 && (
        <FilterGroup title="Marca">
          <div style={{ maxHeight: 220, overflowY: "auto" }}>
            {availBrands.map((b) => (
              <Check key={b} checked={selBrands.has(b)} onChange={() => toggleBrand(b)} label={BRAND_LABELS[b] || (b.charAt(0).toUpperCase() + b.slice(1))} />
            ))}
          </div>
        </FilterGroup>
      )}

      {availTypes.length > 0 && (
        <FilterGroup title="Tipo de equipo">
          {availTypes.map((c) => (
            <Check key={c} checked={selTypes.has(c)} onChange={() => toggleType(c)} label={CAT_LABELS[c] || c} />
          ))}
        </FilterGroup>
      )}

      <FilterGroup title="Precio (RD$)">
        <div style={{ display: "flex", gap: 8 }}>
          <input type="number" inputMode="numeric" placeholder="Desde" value={priceMin} onChange={(e) => setMin(e.target.value)}
            style={{ width: "50%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 13, background: "#fff", color: "var(--ink)" }} />
          <input type="number" inputMode="numeric" placeholder="Hasta" value={priceMax} onChange={(e) => setMax(e.target.value)}
            style={{ width: "50%", padding: "9px 12px", borderRadius: 10, border: "1px solid var(--line)", fontFamily: "inherit", fontSize: 13, background: "#fff", color: "var(--ink)" }} />
        </div>
      </FilterGroup>

      {hasActive && (
        <button onClick={resetFilters} style={{ background: "transparent", border: 0, color: "var(--brand)", fontSize: 14, fontWeight: 600, cursor: "pointer", padding: "4px 0", fontFamily: "inherit" }}>
          Restablecer filtros
        </button>
      )}
    </>
  );

  return (
    <window.PageScaffold active="equipos">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Equipos</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            Tu próximo<br/><span className="italic-display" style={{ color: "var(--brand)" }}>teléfono.</span> Aquí.
          </h1>
          <p className="lead reveal" style={{ marginTop: 32, maxWidth: 600 }}>
            iPhone, Samsung, Google y más. Con plan, sin plan, en cuotas. Lo armamos contigo.
          </p>
        </div>
      </section>

      <section style={{ background: "var(--paper-2)", paddingTop: 48, paddingBottom: 80 }}>
        <div className="container">
          {/* Mobile filter toggle */}
          <button className="eq-filter-toggle" onClick={() => setShowFilters(!showFilters)}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="4" y1="6" x2="20" y2="6"/><line x1="7" y1="12" x2="17" y2="12"/><line x1="10" y1="18" x2="14" y2="18"/></svg>
            Filtros {hasActive ? "· activos" : ""}
          </button>

          <div className="eq-layout">
            {/* Sidebar */}
            <aside className={"eq-filters" + (showFilters ? " is-open" : "")}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
                <h2 style={{ fontSize: 17, fontWeight: 700, margin: 0 }}>Filtrar</h2>
                <span className="caption">{status === "ok" ? `${filtered.length} equipos` : ""}</span>
              </div>
              {filtersUI}
            </aside>

            {/* Results */}
            <div className="eq-results">
              {status === "loading" && (
                <div className="grid grid-3" style={{ gap: 16 }}>
                  {[...Array(6)].map((_, i) => (
                    <div key={i} className="card" style={{ padding: 24, minHeight: 460, background: "#fff", display: "flex", flexDirection: "column", gap: 16 }}>
                      <div style={{ height: 14, width: 60, background: "var(--paper-2)", borderRadius: 4 }} />
                      <div style={{ height: 240, background: "var(--paper-2)", borderRadius: 16 }} />
                      <div style={{ height: 18, background: "var(--paper-2)", borderRadius: 4 }} />
                      <div style={{ marginTop: "auto", height: 24, width: "50%", background: "var(--paper-2)", borderRadius: 4 }} />
                    </div>
                  ))}
                </div>
              )}
              {status === "error" && (
                <div className="card" style={{ padding: 48, textAlign: "center", background: "#fff" }}>
                  <div className="h3" style={{ margin: 0 }}>No pudimos cargar el catálogo.</div>
                  <p className="body" style={{ marginTop: 12 }}>{error}</p>
                </div>
              )}
              {status === "empty" && (
                <div className="card" style={{ padding: 48, textAlign: "center", background: "#fff" }}>
                  <div className="h3" style={{ margin: 0 }}>Catálogo vacío.</div>
                  <p className="body" style={{ marginTop: 12 }}>Sincroniza con Claro o crea equipos desde el admin.</p>
                </div>
              )}
              {status === "ok" && (
                filtered.length === 0 ? (
                  <div className="card" style={{ padding: 48, textAlign: "center", background: "#fff" }}>
                    <div className="h3" style={{ margin: 0 }}>Sin resultados</div>
                    <p className="body" style={{ marginTop: 12 }}>Ningún equipo coincide con tus filtros.</p>
                    <button onClick={resetFilters} className="btn btn-brand" style={{ marginTop: 16 }}>Restablecer filtros</button>
                  </div>
                ) : (
                  <div className="grid grid-3" style={{ gap: 16 }}>
                    {filtered.map((p) => <ProductCard key={p.id} p={p} />)}
                  </div>
                )
              )}
            </div>
          </div>
        </div>

        <style>{`
          .eq-layout { display: grid; grid-template-columns: 248px 1fr; gap: 32px; align-items: start; }
          .eq-filters {
            background: #fff; border: 1px solid var(--line); border-radius: 18px;
            padding: 22px; position: sticky; top: 90px;
          }
          .eq-filter-toggle { display: none; }
          @media (max-width: 900px) {
            .eq-layout { grid-template-columns: 1fr; }
            .eq-filter-toggle {
              display: inline-flex; align-items: center; gap: 8px;
              padding: 10px 18px; border-radius: 999px; margin-bottom: 20px;
              background: var(--ink); color: #fff; border: 0; cursor: pointer;
              font-family: inherit; font-size: 14px; font-weight: 600;
            }
            .eq-filters { display: none; position: static; margin-bottom: 24px; }
            .eq-filters.is-open { display: block; }
          }
        `}</style>
      </section>

      <section style={{ background: "var(--brand)", color: "#fff" }}>
        <div className="container" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64, alignItems: "center" }}>
          <div className="reveal">
            <div className="mini" style={{ marginBottom: 16, opacity: 0.85 }}>Cuotas</div>
            <h2 className="h1" style={{ margin: 0, color: "#fff" }}>Hasta 24 cuotas <span className="italic-display">sin interés.</span></h2>
            <p className="lead" style={{ color: "rgba(255,255,255,0.85)", marginTop: 24 }}>Con plan Smart Libre, lleva tu equipo y paga poquito a poquito.</p>
            <a href={window.balUrl("servicios.html")} className="btn" style={{ background: "#fff", color: "var(--brand)", marginTop: 32 }}>Cómo funciona <window.Icon.Arrow /></a>
          </div>
          <div className="reveal" style={{ fontSize: "clamp(120px, 20vw, 240px)", fontWeight: 700, letterSpacing: "-0.05em", lineHeight: 0.85, textAlign: "center", opacity: 0.95 }}>
            24x
          </div>
        </div>
      </section>
    </window.PageScaffold>
  );
}
window.PAGES = Object.assign({}, window.PAGES, { equipos: App });
if (!window.__BAL_ROOT) window.__BAL_ROOT = ReactDOM.createRoot(document.getElementById("root"));
window.__BAL_ROOT.render(React.createElement((window.PAGES && window.PAGES[window.PAGE]) || App));
