// catalog.jsx — Moliterni Motos: header, hero, catálogo com filtros

function waLink(text) {
  return `https://wa.me/${STORE.whatsapp}?text=${encodeURIComponent(text)}`;
}

// marca reutilizável (foto da moto + wordmark)
function Brand({ size = 38 }) {
  const bike = (window.__resources && window.__resources.logo) || "assets/moliterni-bike.png";
  const strokeW = Math.max(0.5, size * 0.022); // engorda o texto p/ casar com a fonte do logo
  return (
    <span style={{ display: "flex", alignItems: "center", gap: Math.round(size * 0.30) }}>
      <img src={bike} alt="" style={{ height: Math.round(size * 1.0), width: "auto", borderRadius: Math.round(size * 0.20), display: "block" }} />
      <span style={{ display: "flex", flexDirection: "column", lineHeight: 0.88, fontFamily: "var(--font-display)", fontStyle: "italic", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".01em" }}>
        <span style={{ fontSize: size * 0.52, color: "var(--text)", WebkitTextStroke: strokeW + "px var(--text)" }}>Moliterni</span>
        <span style={{ fontSize: size * 0.52, color: "var(--accent)", WebkitTextStroke: strokeW + "px var(--accent)" }}>Motos</span>
      </span>
    </span>
  );
}

// ---------- Header ----------
function Header({ navigate, view }) {
  const go = (where) => navigate(where);
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 100,
      background: "color-mix(in oklch, var(--bg) 82%, transparent)", backdropFilter: "blur(14px)",
      borderBottom: "1px solid var(--border-soft)" }}>
      <div className="wrap" style={{ height: 70, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 }}>
        <button onClick={() => go("home")} style={{ background: "none", border: "none", padding: 0, cursor: "pointer", display: "flex", alignItems: "center" }}>
          <Brand size={40} />
        </button>
        <nav style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <a href="#estoque" className="navlink">Estoque</a>
          <a href="#contato" className="navlink">Contato</a>
          <a href={STORE.instagramUrl} target="_blank" rel="noopener" className="btn btn-ig btn-sm navonly"><IconInsta size={16} /> Instagram</a>
          <a href={waLink("Olá! Vim pelo site da Moliterni Motos e gostaria de mais informações.")} target="_blank" rel="noopener"
             className="btn btn-wa btn-sm"><IconWhats size={16} /> WhatsApp</a>
          <button onClick={() => go("admin")} className="btn btn-ghost btn-sm" title="Área do vendedor"><IconLock size={15} /></button>
        </nav>
      </div>
      <style>{`
        .navlink { padding: 9px 14px; border-radius: 999px; font-weight: 600; font-size: 15px; color: var(--muted); transition: all .14s; }
        .navlink:hover { color: var(--text); background: var(--surface-2); }
        @media (max-width: 760px){ .navlink, .navonly{ display:none !important; } }
      `}</style>
    </header>
  );
}

// ---------- Hero ----------
function Hero({ featured, onOpen, scrollToEstoque }) {
  if (!featured) return null;
  return (
    <section className="wrap" style={{ paddingTop: 44, paddingBottom: 20 }}>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) minmax(0,1.15fr)", gap: 36, alignItems: "center" }} className="hero-grid">
        <div className="fade-in">
          <span className="badge badge-oferta" style={{ marginBottom: 18 }}><IconBolt size={13} /> Destaque da semana</span>
          <h1 style={{ fontSize: "clamp(34px, 5vw, 58px)", lineHeight: 1.02, marginTop: 4 }}>
            Sua próxima<br />moto está aqui.
          </h1>
          <p style={{ fontSize: 18, color: "var(--muted)", maxWidth: 450, marginTop: 18, lineHeight: 1.55 }}>
            O maior estoque de motos usadas de Porto Alegre. Há mais de 10 anos realizando sonhos — atendimento com hora marcada, direto pelo WhatsApp.
          </p>
          <div style={{ display: "flex", gap: 12, marginTop: 26, flexWrap: "wrap" }}>
            <button onClick={scrollToEstoque} className="btn btn-primary btn-lg">Ver estoque <IconArrowRight size={18} /></button>
            <button onClick={() => onOpen(featured)} className="btn btn-ghost btn-lg">Ver destaque</button>
          </div>
          <div style={{ display: "flex", gap: 28, marginTop: 34, flexWrap: "wrap" }}>
            {[["+10 anos", "realizando sonhos"], ["Maior estoque", "de usadas em POA"], ["Hora marcada", "sob agendamento"]].map(([a, b]) => (
              <div key={b}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 700 }}>{a}</div>
                <div style={{ fontSize: 13, color: "var(--faint)" }}>{b}</div>
              </div>
            ))}
          </div>
        </div>
        <button onClick={() => onOpen(featured)} className="fade-in" style={{ background: "none", border: "none", padding: 0, textAlign: "left", cursor: "pointer" }}>
          <div className="card" style={{ overflow: "hidden", boxShadow: "var(--shadow)" }}>
            <div style={{ position: "relative", aspectRatio: "16 / 11" }}>
              <VehiclePhoto vehicle={featured} style={{ width: "100%", height: "100%" }} rounded={false} />
              <div style={{ position: "absolute", top: 14, left: 14 }}><StatusBadge status={featured.status} /></div>
            </div>
            <div style={{ padding: "18px 20px", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
              <div>
                <div style={{ fontSize: 12.5, color: "var(--faint)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{featured.marca} · {featured.ano}</div>
                <h3 style={{ fontSize: 24, marginTop: 3 }}>{featured.modelo}</h3>
              </div>
              <div style={{ textAlign: "right" }}>
                {featured.precoAntigo > featured.preco && <div style={{ fontSize: 13, color: "var(--faint)", textDecoration: "line-through" }}>{formatBRL(featured.precoAntigo)}</div>}
                <div style={{ fontFamily: "var(--font-display)", fontSize: 26, fontWeight: 700, color: featured.status === "oferta" ? "var(--warn)" : "var(--text)" }}>{formatBRL(featured.preco)}</div>
              </div>
            </div>
          </div>
        </button>
      </div>
      <style>{`@media (max-width: 880px){ .hero-grid{ grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

// ---------- Filtros + catálogo ----------
function Catalog({ vehicles, onOpen }) {
  const [cat, setCat] = React.useState("todos");
  const [q, setQ] = React.useState("");
  const [sort, setSort] = React.useState("recentes");
  const maxPreco = React.useMemo(() => Math.max(20000, ...vehicles.map((v) => v.preco)), [vehicles]);
  const [precoMax, setPrecoMax] = React.useState(maxPreco);
  React.useEffect(() => { setPrecoMax(maxPreco); }, [maxPreco]);
  const [showVendidos, setShowVendidos] = React.useState(false);

  const filtered = React.useMemo(() => {
    let list = vehicles.filter((v) => {
      if (cat !== "todos" && v.categoria !== cat) return false;
      if (!showVendidos && v.status === "vendido") return false;
      if (v.preco > precoMax) return false;
      if (q.trim()) {
        const hay = (v.marca + " " + v.modelo + " " + v.cor + " " + v.ano + " " + segLabel(v.categoria)).toLowerCase();
        if (!hay.includes(q.trim().toLowerCase())) return false;
      }
      return true;
    });
    const by = {
      recentes: (a, b) => b.createdAt - a.createdAt,
      menor: (a, b) => a.preco - b.preco,
      maior: (a, b) => b.preco - a.preco,
      km: (a, b) => a.km - b.km,
      ano: (a, b) => b.ano - a.ano,
    }[sort];
    return [...list].sort(by);
  }, [vehicles, cat, q, sort, precoMax, showVendidos]);

  const cats = [{ id: "todos", label: "Todas" }, ...SEGMENTOS];

  return (
    <section id="estoque" className="wrap" style={{ paddingTop: 42, paddingBottom: 60, scrollMarginTop: 80 }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
        <div>
          <h2 style={{ fontSize: 30 }}>Estoque</h2>
          <p style={{ color: "var(--muted)", marginTop: 4 }}>{filtered.length} {filtered.length === 1 ? "moto disponível" : "motos disponíveis"}</p>
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {cats.map((c) => (
            <button key={c.id} className="chip" data-active={cat === c.id} onClick={() => setCat(c.id)}>{c.label}</button>
          ))}
        </div>
      </div>

      {/* barra de filtros */}
      <div className="card filterbar" style={{ padding: 16, marginBottom: 26, display: "grid", gridTemplateColumns: "minmax(0,1.4fr) minmax(0,1.3fr) minmax(0,1fr)", gap: 16, alignItems: "center" }}>
          <div style={{ position: "relative" }}>
            <IconSearch size={18} style={{ position: "absolute", left: 13, top: "50%", transform: "translateY(-50%)", color: "var(--faint)" }} />
            <input className="input" placeholder="Buscar por marca, modelo, cor…" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 40 }} />
          </div>
          <div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, color: "var(--faint)", fontWeight: 600, marginBottom: 4 }}>
              <span>Preço até</span><span style={{ color: "var(--accent)", fontWeight: 700 }}>{formatBRL(precoMax)}</span>
            </div>
            <input type="range" min={Math.min(...vehicles.map((v) => v.preco), 10000)} max={maxPreco} step={1000} value={precoMax}
              onChange={(e) => setPrecoMax(Number(e.target.value))} style={{ width: "100%", accentColor: "var(--accent)" }} />
          </div>
          <select className="select" value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="recentes">Mais recentes</option>
            <option value="menor">Menor preço</option>
            <option value="maior">Maior preço</option>
            <option value="km">Menor km</option>
            <option value="ano">Ano mais novo</option>
          </select>
      </div>

      {filtered.length === 0 ? (
        <div className="card" style={{ padding: "60px 20px", textAlign: "center", color: "var(--muted)" }}>
          <IconSearch size={32} style={{ color: "var(--faint)", marginBottom: 10 }} />
          <p style={{ fontWeight: 600 }}>Nenhuma moto encontrada com esses filtros.</p>
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(265px, 1fr))", gap: 22 }}>
          {filtered.map((v) => <VehicleCard key={v.id} vehicle={v} onOpen={onOpen} />)}
        </div>
      )}

      <label style={{ display: "inline-flex", alignItems: "center", gap: 8, marginTop: 22, fontSize: 14, color: "var(--muted)", cursor: "pointer", fontWeight: 600 }}>
        <input type="checkbox" checked={showVendidos} onChange={(e) => setShowVendidos(e.target.checked)} style={{ accentColor: "var(--accent)", width: 16, height: 16 }} />
        Mostrar motos já vendidas
      </label>

      <style>{`@media (max-width: 760px){ .filterbar{ grid-template-columns: 1fr !important; } #estoque .card[style*="repeat"]{ grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

Object.assign(window, { Header, Hero, Catalog, Brand, waLink });
