// INTERNET HOGAR — listing estilo catálogo (sidebar + grid), modal para solicitar.
// Alimentado por /admin/api/plans.php?family=internet_hogar
const { useState, useEffect, useMemo } = React;

function planFeatures(p) {
  const f = [];
  f.push("Fibra óptica");
  if (p.speed_up_mbps) f.push(`Subida ${p.speed_up_mbps} Mbps`);
  f.push(p.wifi_standard ? `Wi-Fi ${p.wifi_standard}` : "Wi-Fi 6 incluido");
  f.push(p.install_free === false ? "Instalación a coordinar" : "Instalación gratis");
  return f;
}

function solicitar(p, down, up) {
  window.openLeadForm({
    kind: "plan",
    id: p.id,
    name: p.name,
    slug: p.slug,
    price: p.price,
    extra: {
      "Plan": p.name,
      "Tipo": "Internet hogar",
      "Velocidad": `${down}/${up} Mbps`,
    },
    sourceTag: "internet-hogar-form",
  });
}

function InternetCard({ p }) {
  const down = Math.round(p.speed_down_mbps || 0);
  const up   = Math.round(p.speed_up_mbps || (down ? Math.round(down / 2) : 0));
  const isPop = p.is_popular;
  const feats = planFeatures(p);

  return (
    <article className="card" style={{
      padding: 26, display: "flex", flexDirection: "column", gap: 18,
      minHeight: 440, position: "relative", overflow: "hidden",
      background: isPop ? "linear-gradient(165deg,#1a1024 0%,#2a1538 55%,#1a1024 100%)" : "#fff",
      color: isPop ? "var(--paper)" : "var(--ink)",
      border: "1px solid " + (isPop ? "transparent" : "var(--line)"),
    }}>
      {isPop && (
        <span style={{
          position: "absolute", top: 16, right: 16, background: "var(--brand)", color: "#fff",
          padding: "5px 11px", borderRadius: 999, fontSize: 10, fontWeight: 700,
          letterSpacing: "0.12em", textTransform: "uppercase",
          boxShadow: "0 8px 20px -6px rgba(237,15,68,0.55)",
        }}>★ Destacado</span>
      )}

      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: isPop ? "rgba(255,255,255,0.6)" : "var(--ink-3)" }}>
        Internet hogar
      </div>

      {/* Velocidad protagonista */}
      <div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
          <span style={{ fontSize: 46, fontWeight: 800, letterSpacing: "-0.03em", lineHeight: 1 }}>{down}</span>
          <span style={{ fontSize: 18, fontWeight: 700, color: isPop ? "rgba(255,255,255,0.7)" : "var(--ink-3)" }}>Mbps</span>
        </div>
        <div style={{ fontSize: 13, color: isPop ? "rgba(255,255,255,0.6)" : "var(--ink-3)", marginTop: 4 }}>
          de bajada · {p.name}
        </div>
      </div>

      {/* Beneficios */}
      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "flex", flexDirection: "column", gap: 9 }}>
        {feats.map((t, i) => (
          <li key={i} style={{ display: "flex", gap: 9, alignItems: "center", fontSize: 14, color: isPop ? "rgba(255,255,255,0.9)" : "var(--ink-2)" }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--brand)" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><polyline points="20 6 9 17 4 12" /></svg>
            {t}
          </li>
        ))}
      </ul>

      {/* Precio + CTA */}
      <div style={{ marginTop: "auto" }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 6, marginBottom: 14 }}>
          <span style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em", color: isPop ? "#fff" : "var(--brand)" }}>
            RD${Math.round(p.price || 0).toLocaleString()}
          </span>
          <span style={{ fontSize: 13, color: isPop ? "rgba(255,255,255,0.6)" : "var(--ink-3)" }}>/ mes</span>
        </div>
        <button onClick={() => solicitar(p, down, up)} className="btn btn-brand" style={{
          width: "100%", justifyContent: "center", border: 0, cursor: "pointer", fontFamily: "inherit",
          background: isPop ? "#fff" : "var(--brand)", color: isPop ? "var(--brand)" : "#fff",
        }}>
          Solicitar plan
        </button>
      </div>
    </article>
  );
}

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

  const [sortBy, setSortBy]   = useState("recomendado"); // recomendado | precio-asc | precio-desc | velocidad
  const [selSpeed, setSpeed]  = useState(() => new Set()); // tiers de velocidad
  const [priceMin, setMin]    = useState("");
  const [priceMax, setMax]    = useState("");
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    fetch(window.balUrl("admin/api/plans.php?family=internet_hogar&limit=100"), { 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"); });
  }, []);

  // Tiers de velocidad
  const SPEED_TIERS = [
    { key: "low",  label: "Hasta 150 Mbps",  test: (s) => s <= 150 },
    { key: "mid",  label: "200 – 300 Mbps",  test: (s) => s > 150 && s <= 300 },
    { key: "high", label: "400 Mbps o más",  test: (s) => s > 300 },
  ];
  const toggleSpeed = (val) => setSpeed((prev) => {
    const next = new Set(prev); next.has(val) ? next.delete(val) : next.add(val); return next;
  });

  const hasActive = selSpeed.size || priceMin || priceMax || sortBy !== "recomendado";
  function resetFilters() { setSpeed(new Set()); setMin(""); setMax(""); setSortBy("recomendado"); }

  const filtered = useMemo(() => {
    let out = items.slice();
    if (selSpeed.size) {
      out = out.filter((p) => {
        const s = p.speed_down_mbps || 0;
        return SPEED_TIERS.some((t) => selSpeed.has(t.key) && t.test(s));
      });
    }
    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 "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;
      case "velocidad":   out.sort((a, b) => (b.speed_down_mbps || 0) - (a.speed_down_mbps || 0)); break;
      default:            out.sort((a, b) => (!!b.is_popular - !!a.is_popular) || (a.price || 0) - (b.price || 0)); // recomendado
    }
    return out;
  }, [items, selSpeed, priceMin, priceMax, sortBy]);

  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 filtersUI = (
    <>
      <FilterGroup title="Ordenar por">
        {[["recomendado","Recomendado"],["precio-asc","Precio: menor"],["precio-desc","Precio: mayor"],["velocidad","Más velocidad"]].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="in-sort" checked={sortBy === v} onChange={() => setSortBy(v)} style={{ width: 16, height: 16, accentColor: "var(--brand)", cursor: "pointer" }} />
            {l}
          </label>
        ))}
      </FilterGroup>

      <FilterGroup title="Velocidad">
        {SPEED_TIERS.map((t) => (
          <label key={t.key} style={{ display: "flex", alignItems: "center", gap: 10, padding: "5px 0", cursor: "pointer", fontSize: 14, color: "var(--ink-2)" }}>
            <input type="checkbox" checked={selSpeed.has(t.key)} onChange={() => toggleSpeed(t.key)} style={{ width: 17, height: 17, accentColor: "var(--brand)", cursor: "pointer", flexShrink: 0 }} />
            {t.label}
          </label>
        ))}
      </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="planes">
      <section style={{ padding: "112px 0 40px", position: "relative" }}>
        <window.DotGrid />
        <div className="container" style={{ position: "relative" }}>
          <div className="eyebrow reveal" style={{ marginBottom: 24 }}>Internet hogar</div>
          <h1 className="display reveal" style={{ margin: 0 }}>
            Fibra que <span className="italic-display" style={{ color: "var(--brand)" }}>vuela.</span> En tu casa.
          </h1>
          <p className="lead reveal" style={{ marginTop: 32, maxWidth: 600 }}>
            Fibra óptica con Wi-Fi 6 e instalación gratis. Elige tu velocidad y la activamos hoy.
          </p>
        </div>
      </section>

      <section style={{ background: "var(--paper-2)", paddingTop: 48, paddingBottom: 80 }}>
        <div className="container">
          <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">
            <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} planes` : ""}</span>
              </div>
              {filtersUI}
            </aside>

            <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: 26, minHeight: 440, background: "#fff", display: "flex", flexDirection: "column", gap: 16 }}>
                      <div style={{ height: 12, width: 90, background: "var(--paper-2)", borderRadius: 4 }} />
                      <div style={{ height: 46, width: 120, background: "var(--paper-2)", borderRadius: 6 }} />
                      <div style={{ height: 80, background: "var(--paper-2)", borderRadius: 6 }} />
                      <div style={{ marginTop: "auto", height: 44, background: "var(--paper-2)", borderRadius: 999 }} />
                    </div>
                  ))}
                </div>
              )}
              {status === "error" && (
                <div className="card" style={{ padding: 48, textAlign: "center", background: "#fff" }}>
                  <div className="h3" style={{ margin: 0 }}>No pudimos cargar los planes.</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 }}>Sin planes de internet hogar.</div>
                  <p className="body" style={{ marginTop: 12 }}>Crea planes 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 plan 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) => <InternetCard 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>
    </window.PageScaffold>
  );
}
window.PAGES = Object.assign({}, window.PAGES, { internet: 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));
