// home.jsx — Coolcaséate: hero + model picker with brand filters
// exposes: HomeView

function ModelCard({ model, onPick, index }) {
  const [hover, setHover] = React.useState(false);
  const accent = ["#ff3df0", "#8b5cff", "#2de2ff", "#3dffa8"][index % 4];
  const shortName = model.name.replace(new RegExp("^" + model.brand + "\\s+", "i"), "").replace(/^MI\s/i, "Mi ") || model.name;
  return (
    <button
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onPick(model)}
      className="glass rise"
      style={{
        position: "relative", border: "1px solid var(--glass-border)", cursor: "pointer",
        borderRadius: 28, padding: "26px 22px 22px", textAlign: "left",
        display: "flex", flexDirection: "column", alignItems: "center", gap: 16,
        transition: "transform 0.3s cubic-bezier(0.2,0.8,0.2,1), box-shadow 0.3s ease, border-color 0.3s ease",
        transform: hover ? "translateY(-8px)" : "none",
        borderColor: hover ? "var(--glass-border-strong)" : "var(--glass-border)",
        boxShadow: hover ? `0 30px 60px -22px ${accent}66, inset 0 1px 0 rgba(255,255,255,0.12)` : "var(--shadow-glass)",
        animationDelay: index * 0.05 + "s",
        overflow: "hidden",
      }}
    >
      <div style={{ position: "absolute", inset: 0, background: `radial-gradient(70% 50% at 50% 0%, ${accent}22, transparent 70%)`, opacity: hover ? 1 : 0.5, transition: "opacity 0.3s ease", pointerEvents: "none" }}/>
      <div style={{ position: "relative", height: 230, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ transition: "transform 0.4s ease", transform: hover ? "translateY(-4px) rotate(-2deg)" : "none" }}>
          <PhoneCase model={model} design={{ base: "#1b1740", pattern: "none" }} scale={0.4} />
        </div>
      </div>
      <div className="col" style={{ alignItems: "center", gap: 5, zIndex: 1, width: "100%" }}>
        <span className="eyebrow" style={{ fontSize: 10, letterSpacing: "0.28em" }}>{model.brand}</span>
        <span style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16.5, lineHeight: 1.18, textAlign: "center",
          display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden",
          minHeight: "2.36em", alignItems: "center", justifyContent: "center" }}>{shortName}</span>
        <span style={{ fontSize: 13, color: "var(--ink-50)" }}>desde {fmt(model.price)}</span>
      </div>
      <div className="row center" style={{
        gap: 7, zIndex: 1, padding: "10px 18px", borderRadius: 999,
        background: hover ? "var(--grad-neon)" : "var(--glass-bg-strong)",
        color: "#fff", fontSize: 13.5, fontWeight: 600,
        transition: "background 0.3s ease",
        boxShadow: hover ? "0 8px 22px -6px rgba(255,61,240,0.5)" : "none",
      }}>
        Coolcaséalo <Icon name="arrow" size={16} />
      </div>
    </button>
  );
}

function HomeView({ onPick }) {
  const brands = (window.PHONE_BRANDS || ["iPhone", "Samsung", "Xiaomi"]);
  const [filter, setFilter] = React.useState(brands[0]);
  const [query, setQuery] = React.useState("");
  const [limit, setLimit] = React.useState(48);

  const q = query.trim().toLowerCase();
  const all = CC.models;
  const models = React.useMemo(() => {
    let list = q ? all.filter((m) => m.name.toLowerCase().includes(q)) : all.filter((m) => m.brand === filter);
    return list;
  }, [q, filter, all]);
  const shown = models.slice(0, limit);

  React.useEffect(() => { setLimit(48); }, [filter, q]);

  const countByBrand = React.useMemo(() => {
    const c = {};
    all.forEach((m) => { c[m.brand] = (c[m.brand] || 0) + 1; });
    return c;
  }, [all]);

  return (
    <div className="page section-pad">
      {/* hero */}
      <div className="col" style={{ alignItems: "center", textAlign: "center", maxWidth: 880, margin: "0 auto 44px" }}>
        <div className="eyebrow rise" style={{ marginBottom: 22 }}>Paso 1 · Encuentra tu teléfono</div>
        <h1 className="display rise" style={{ fontSize: "clamp(46px, 6.6vw, 88px)", animationDelay: "0.05s" }}>
          Elige tu modelo<br/><span className="grad-text">y empieza a crear</span>
        </h1>
        <p className="rise" style={{ fontSize: 18, color: "var(--ink-70)", maxWidth: 560, marginTop: 20, lineHeight: 1.5, animationDelay: "0.1s" }}>
          Tenemos carcasas para <b style={{ color: "var(--ink)" }}>{all.length.toLocaleString("es-CL")}</b> modelos. Busca el tuyo o explora por marca.
        </p>
      </div>

      {/* search */}
      <div className="rise" style={{ maxWidth: 560, margin: "0 auto 26px", animationDelay: "0.12s" }}>
        <div className="glass" style={{ display: "flex", alignItems: "center", gap: 12, borderRadius: 999, padding: "4px 6px 4px 20px" }}>
          <Icon name="palette" size={20} stroke="var(--ink-50)" />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Busca tu modelo… ej: iPhone 15, A54, Redmi Note 13"
            style={{ flex: 1, background: "none", border: "none", outline: "none", color: "#fff", fontSize: 15.5, fontFamily: "var(--font-ui)", padding: "12px 0" }} />
          {query ? (
            <button onClick={() => setQuery("")} style={{ background: "var(--glass-bg)", border: "1px solid var(--glass-border)", borderRadius: "50%", width: 36, height: 36, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", color: "var(--ink-70)", flexShrink: 0 }}><Icon name="close" size={16} /></button>
          ) : null}
        </div>
      </div>

      {/* brand tabs (hidden while searching) */}
      {!q && (
        <div className="row rise" style={{ gap: 9, justifyContent: "center", marginBottom: 38, flexWrap: "wrap", animationDelay: "0.15s" }}>
          {brands.map((b) => {
            const active = b === filter;
            return (
              <button key={b} onClick={() => setFilter(b)} className="btn" style={{
                padding: "9px 18px", fontSize: 14,
                background: active ? "var(--grad-neon)" : "var(--glass-bg)",
                border: active ? "1px solid transparent" : "1px solid var(--glass-border)",
                color: "#fff", fontWeight: active ? 700 : 500,
                boxShadow: active ? "0 8px 22px -8px rgba(255,61,240,0.5)" : "none",
              }}>{b} <span style={{ opacity: 0.6, fontWeight: 500, marginLeft: 2 }}>{countByBrand[b]}</span></button>
            );
          })}
        </div>
      )}

      {/* result line */}
      <div className="row" style={{ justifyContent: "space-between", alignItems: "baseline", marginBottom: 20, flexWrap: "wrap", gap: 8 }}>
        <h2 style={{ fontSize: 22 }}>{q ? `Resultados para "${query}"` : filter}</h2>
        <span style={{ fontSize: 13.5, color: "var(--ink-50)" }}>{models.length.toLocaleString("es-CL")} modelo{models.length !== 1 ? "s" : ""}</span>
      </div>

      {/* grid */}
      {models.length === 0 ? (
        <div className="glass" style={{ borderRadius: 24, padding: "60px 20px", textAlign: "center", color: "var(--ink-50)" }}>
          <Icon name="image" size={42} stroke="var(--ink-30)" />
          <p style={{ fontSize: 15.5, marginTop: 12 }}>No encontramos ese modelo.<br/>Prueba con otro nombre o escríbenos por WhatsApp.</p>
        </div>
      ) : (
        <>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(232px, 1fr))", gap: 20 }}>
            {shown.map((m, i) => <ModelCard key={m.id} model={m} index={i} onPick={onPick} />)}
          </div>
          {models.length > limit && (
            <div className="row" style={{ justifyContent: "center", marginTop: 40 }}>
              <button className="btn btn-ghost" onClick={() => setLimit((l) => l + 48)} style={{ padding: "14px 28px" }}>
                Ver más modelos ({(models.length - limit).toLocaleString("es-CL")} restantes)
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

Object.assign(window, { HomeView });
