// Homepage + BrandPage (design Joinsteer, classes hp-*/bp-*) branchés sur les vraies données.
// Lit window.CATALOG_INDEX (marques + modèles) et window.VEHICLES (fiches complètes).

const CAT = () => window.CATALOG_INDEX || [];
function vehBySlug(slug) { return (window.VEHICLES || []).find(v => v.slug === slug); }
function fmtN(n) { return (n == null || n === "") ? "—" : new Intl.NumberFormat("fr-FR").format(n); }
const LOGO = <svg viewBox="0 0 37.468 35.933" fill="currentColor" width="26" height="26"><path d="M 37.468 30.774 L 37.021 30.011 C 36.708 29.428 36.216 28.441 35.501 27.993 L 30.404 25.121 L 28.213 25.75 L 25.575 16.553 C 25.038 15.252 24.1 14.131 22.848 13.413 L 0 0 L 1.833 5.069 C 2.057 5.832 2.549 6.415 3.13 6.908 L 16.99 16.553 L 4.471 11.26 C 4.471 11.305 5.5 14.938 5.5 14.938 C 5.589 15.297 5.768 15.656 5.991 15.925 C 6.081 16.06 6.215 16.194 6.349 16.329 L 17.438 24.045 L 8.45 20.277 L 9.658 24.718 C 9.881 25.57 10.597 26.288 11.044 26.736 L 20.12 35.933 C 21.104 34.273 23.429 32.703 27.006 31.267 C 28.571 30.639 30.046 30.236 31.477 30.011 C 33.847 29.652 35.903 29.832 37.468 30.011 Z"/></svg>;

function HpNav() {
  return (
    <nav className="hp-nav">
      <a className="hp-nav-lockup" href="/" style={{textDecoration:"none"}}>{LOGO}<span>JOINSTEER</span></a>
      <div className="hp-nav-links">
        <a>Marketplace</a><a className="is-on" href="/">Fiches techniques</a><a>Financement</a><a>À propos</a>
      </div>
      <div className="hp-nav-right">
        <button className="hp-nav-search-btn"><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="6" cy="6" r="4" stroke="currentColor" strokeWidth="1.5"/><path d="M11 11l-2-2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg></button>
        <button className="hp-nav-avatar">JD</button>
      </div>
    </nav>
  );
}
function HpFooter() {
  return (
    <footer className="hp-footer"><div className="hp-footer-inner">
      <div className="hp-footer-lockup">{LOGO}<span>JOINSTEER</span></div>
      <p>© 2026 Joinsteer · Toutes les fiches techniques.</p>
    </div></footer>
  );
}

function Homepage() {
  const cat = CAT();
  const [query, setQuery] = React.useState("");
  const [brand, setBrand] = React.useState("");
  const [model, setModel] = React.useState("");
  const brands = cat.map(c => c.brand);
  const models = brand ? (cat.find(c => c.brand === brand)?.models || []) : [];
  const suggestions = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    if (q.length < 1) return [];
    const out = [];
    cat.forEach(c => {
      if (c.brand.toLowerCase().includes(q)) out.push({ brand: c.brand, label: "", href: c.slug, type: "Marque" });
      c.models.forEach(m => { if ((c.brand + " " + m.name).toLowerCase().includes(q)) out.push({ brand: c.brand, label: m.name, href: m.slug, type: "Modèle" }); });
    });
    return out.slice(0, 7);
  }, [query]);
  const totalModels = cat.reduce((s, c) => s + c.count, 0);
  const _fseen = new Set();
  const featured = [];
  [...(window.VEHICLES || [])].sort((a, b) => (b.marketplaceCount || 0) - (a.marketplaceCount || 0)).forEach(v => {
    if (!_fseen.has(v.modelSlug)) { _fseen.add(v.modelSlug); featured.push(v); }
  });
  const goHref = brand && model ? model : brand ? (cat.find(c => c.brand === brand)?.slug) : null;
  return (
    <div className="hp-root">
      <HpNav />
      <header className="hp-hero"><div className="hp-hero-bg" />
        <div className="hp-hero-inner">
          <p className="eyebrow hp-hero-eyebrow">Fiches techniques · données vérifiées</p>
          <h1 className="hp-hero-title">TOUTES LES <span className="hp-hero-accent">FICHES TECHNIQUES</span><br />DES VOITURES <em>QUI COMPTENT.</em></h1>
          <p className="hp-hero-lede">Performances, dimensions, motorisations, consommation — croisées depuis plusieurs sources, avec les vrais exemplaires disponibles en LOA sur Joinsteer.</p>
          <div className="hp-search">
            <div className="hp-search-input-wrap">
              <svg className="hp-search-icon" width="20" height="20" viewBox="0 0 20 20" fill="none"><circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="1.8" /><path d="M14 14l4 4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" /></svg>
              <input className="hp-search-input" value={query} onChange={e => setQuery(e.target.value)} placeholder="Rechercher une marque, un modèle…" />
              {query && <button className="hp-search-clear" onClick={() => setQuery("")}>✕</button>}
            </div>
            {suggestions.length > 0 && (
              <div className="hp-search-results">
                {suggestions.map((s, i) => (
                  <a key={i} className="hp-search-row" href={"/" + s.href}>
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7l4 4 6-9" stroke="currentColor" strokeWidth="1.4" fill="none" /></svg>
                    <span><b>{s.brand}</b>{s.label ? " " + s.label : ""}</span>
                    <span className="hp-search-arrow">→</span>
                  </a>
                ))}
              </div>
            )}
          </div>
          <div className="hp-or"><span>OU SÉLECTIONNEZ</span></div>
          <div className="hp-selectors">
            <div className="hp-select"><label>Marque</label>
              <select value={brand} onChange={e => { setBrand(e.target.value); setModel(""); }}>
                <option value="">Choisir…</option>{brands.map(b => <option key={b} value={b}>{b}</option>)}
              </select></div>
            <div className="hp-select"><label>Modèle</label>
              <select value={model} disabled={!brand} onChange={e => setModel(e.target.value)}>
                <option value="">{brand ? "Choisir…" : "Marque d'abord"}</option>
                {models.map(m => <option key={m.slug} value={m.slug}>{m.name}</option>)}
              </select></div>
            <div className="hp-select"><label>Année</label>
              <select disabled><option>—</option></select></div>
            <a className="hp-go" href={goHref ? ("/" + goHref) : undefined} style={goHref ? {} : { pointerEvents: "none", opacity: .4 }}>
              <span>{brand && model ? "Voir la fiche" : brand ? "Voir la marque" : "Voir la fiche"}</span>
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M5 10h10m0 0l-4-4m4 4l-4 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </a>
          </div>
          <div className="hp-trust">
            <div><b>{fmtN(totalModels)}</b><span>fiches vérifiées</span></div>
            <div><b>{cat.length}</b><span>marques</span></div>
            <div><b>Réelles</b><span>photos & annonces</span></div>
            <div><b>LOA</b><span>financement 48h</span></div>
          </div>
        </div>
      </header>

      <section className="hp-section">
        <div className="hp-section-head"><div><p className="eyebrow">01 · Parcourir</p><h2 className="hp-section-title">PAR MARQUE</h2></div></div>
        <div className="hp-brand-grid">
          {cat.map(c => (
            <a key={c.slug} className="hp-brand-card" href={"/" + c.slug}>
              <div className="hp-brand-logo"><img src={"assets/logo-" + c.slug + ".png"} alt={c.brand} /></div>
              <div className="hp-brand-meta"><span className="hp-brand-name">{c.brand}</span><span className="hp-brand-count">{c.count} modèles</span></div>
              <svg className="hp-brand-arrow" width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4 8h8m0 0l-3-3m3 3l-3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </a>
          ))}
        </div>
      </section>

      <section className="hp-section">
        <div className="hp-section-head"><div><p className="eyebrow">02 · À la une</p><h2 className="hp-section-title">MODÈLES POPULAIRES</h2></div></div>
        <div className="hp-recent-grid">
          {featured.slice(0, 4).map((v, i) => (
            <a key={i} className="hp-recent-card" href={"/" + v.modelSlug}>
              <div className="hp-recent-photo"><img src={(v.photos || [v.photoMain])[0]} alt={v.brand + " " + v.model} /></div>
              <div className="hp-recent-meta">
                <span className="hp-recent-brand">{v.brand}</span>
                <div className="hp-recent-row1"><span className="hp-recent-model">{v.model}</span><span className="hp-recent-year">{v.year}</span></div>
                <div className="hp-recent-stats"><span><b>{v.power_hp}</b>ch</span><span><b>{String(v.acceleration_0_100_s || "").replace(".", ",")}</b>s</span></div>
              </div>
            </a>
          ))}
        </div>
      </section>
      <HpFooter />
    </div>
  );
}

function BrandPage({ brandSlug }) {
  const cat = CAT();
  const c = cat.find(x => x.slug === brandSlug) || cat[0];
  const models = c.models;  // entrées modèle (name, slug=page modèle, photo, versionCount, hp, priceFrom, segment)
  const [filterType, setFilterType] = React.useState("all");
  const types = [...new Set(models.map(m => m.segment).filter(Boolean))];
  const shown = filterType === "all" ? models : models.filter(m => m.segment === filterType);
  const brand = c.brand;
  const totalAnnonces = models.reduce((s, m) => s + (m.marketplaceCount || 0), 0);
  const prices = models.map(m => m.priceFrom).filter(Boolean);
  const heroPhoto = (models[0] || {}).photo;
  return (
    <div className="bp-root">
      <HpNav />
      <div className="bp-crumbs"><a href="/">Fiches techniques</a> <span>›</span> <span className="bp-crumbs-current">{brand}</span></div>
      <header className="bp-hero">
        <div className="bp-hero-left">
          <p className="eyebrow" style={{ color: "var(--color-dark-green-30)" }}>Marque</p>
          <div className="bp-hero-row"><div className="bp-hero-logo"><img src={"assets/logo-" + c.slug + ".png"} alt={brand} /></div><h1 className="bp-hero-title">{brand.toUpperCase()}</h1></div>
          <p className="bp-hero-lede">{models.length} modèles · {fmtN(totalAnnonces)} exemplaires disponibles en LOA sur Joinsteer. Fiches techniques vérifiées, données croisées.</p>
          <div className="bp-hero-stats">
            <div><b>{models.length}</b><span>Modèles</span></div>
            <div><b>{fmtN(totalAnnonces)}</b><span>Annonces</span></div>
            <div><b>{types.length}</b><span>Catégories</span></div>
            <div><b>{prices.length ? Math.round(Math.min(...prices) / 1000) + "k€" : "—"}</b><span>Dès</span></div>
          </div>
        </div>
        <div className="bp-hero-right">{heroPhoto && <img src={heroPhoto} alt={brand} />}</div>
      </header>
      <div className="bp-filters">
        <div className="bp-filter-group">
          <button className={"bp-pill " + (filterType === "all" ? "is-on" : "")} onClick={() => setFilterType("all")}>Tous <span>({models.length})</span></button>
          {types.map(t => <button key={t} className={"bp-pill " + (filterType === t ? "is-on" : "")} onClick={() => setFilterType(t)}>{t} <span>({models.filter(m => m.segment === t).length})</span></button>)}
        </div>
      </div>
      <section className="bp-models">
        {shown.map(m => (
          <a key={m.slug} className="bp-model-card" href={"/" + m.slug}>
            <div className="bp-model-photo">{m.photo && <img src={m.photo} alt={brand + " " + m.name} />}{m.segment && <span className="bp-model-type">{m.segment}</span>}</div>
            <div className="bp-model-body">
              <div className="bp-model-header">
                <div><p className="eyebrow" style={{ color: "var(--color-dark-green-30)" }}>{brand}</p><h3 className="bp-model-name">{m.name}</h3></div>
                {m.priceFrom ? <div className="bp-model-price"><span>dès</span><b>{Math.round(m.priceFrom / 1000)} k€</b></div> : null}
              </div>
              <p className="bp-model-body-type">{m.versionCount} version{m.versionCount > 1 ? "s" : ""} · jusqu'à {m.hp} ch</p>
              <div className="bp-model-stats">
                <div className="bp-model-stat"><span className="bp-stat-lbl">Versions</span><span className="bp-stat-val">{m.versionCount}</span></div>
                <div className="bp-model-stat"><span className="bp-stat-lbl">Puissance</span><span className="bp-stat-val">{m.hp} ch</span></div>
                <div className="bp-model-stat"><span className="bp-stat-lbl">Annonces</span><span className="bp-stat-val">{fmtN(m.marketplaceCount)}</span></div>
              </div>
              <div className="bp-model-action"><span>Voir les {m.versionCount} versions</span><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M4 7h6m0 0l-2-2m2 2l-2 2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg></div>
            </div>
          </a>
        ))}
      </section>
      <HpFooter />
    </div>
  );
}

// Page MODÈLE : liste des modèles spé (versions) -> chacun mène à sa fiche
function ModelPage({ modelSlug }) {
  const cat = CAT();
  let bc = null, model = null;
  cat.forEach(c => c.models.forEach(m => { if (m.slug === modelSlug) { bc = c; model = m; } }));
  if (!model) { bc = cat[0]; model = (cat[0] || {}).models[0]; }
  const versions = (window.VEHICLES || []).filter(v => v.modelSlug === modelSlug);
  const hps = versions.map(v => v.power_hp).filter(Boolean);
  const fuelClass = f => f === "Électrique" ? "ev" : f === "Diesel" ? "diesel" : "petrol";
  return (
    <div className="mp-root">
      <HpNav />
      <div className="bp-crumbs">
        <a href="/">Fiches techniques</a> <span>›</span> <a href={"/" + bc.slug}>{bc.brand}</a> <span>›</span>
        <span className="bp-crumbs-current">{model.name}</span>
      </div>
      <header className="mp-hero">
        <div className="mp-hero-content">
          <div className="mp-hero-eyebrow"><span className="mp-hier-brand">{bc.brand}</span><span className="mp-hier-sep">›</span><span className="mp-hier-model">{model.name}</span></div>
          <h1 className="mp-hero-title">{model.name.toUpperCase()}</h1>
          <p className="mp-hero-lede">{versions.length} version{versions.length > 1 ? "s" : ""} documentée{versions.length > 1 ? "s" : ""} · {fmtN(model.marketplaceCount)} exemplaires disponibles en LOA sur Joinsteer.</p>
          <div className="mp-hero-kpis">
            <div><b>{versions.length}</b><span>Versions</span></div>
            <div><b>{hps.length ? Math.min(...hps) : "—"}<small>ch</small></b><span>Mini</span></div>
            <div><b>{hps.length ? Math.max(...hps) : "—"}<small>ch</small></b><span>Maxi</span></div>
            <div><b>{model.priceFrom ? Math.round(model.priceFrom / 1000) + "k€" : "—"}</b><span>Dès</span></div>
          </div>
        </div>
        <div className="mp-hero-image">{model.photo && <img src={model.photo} alt={bc.brand + " " + model.name} />}</div>
      </header>
      <section className="mp-gens">
        <div className="mp-gens-head"><div><p className="eyebrow" style={{ color: "var(--color-dark-green-30)" }}>Modèles spé</p><h2 className="mp-section-title">{versions.length} VERSIONS</h2></div></div>
        <div className="mp-gens-list"><article className="mp-gen">
          <table className="mp-version-table">
            <thead><tr><th>Modèle spé</th><th>Carburant</th><th className="mp-th-num">Puissance</th><th className="mp-th-num">0-100 km/h</th><th className="mp-th-num">Année</th><th></th></tr></thead>
            <tbody>
              {versions.map(v => (
                <tr key={v.slug}>
                  <td className="mp-td-version"><span className="mp-version-name">{v.modele_sp || v.version || v.model}</span></td>
                  <td><span className={"mp-fuel-pill mp-fuel-" + fuelClass(v.fuel)}>{v.fuel}</span></td>
                  <td className="mp-td-num"><b>{v.power_hp}</b><small>ch</small></td>
                  <td className="mp-td-num"><b>{String(v.acceleration_0_100_s || "—").replace(".", ",")}</b><small>s</small></td>
                  <td className="mp-td-num">{v.year}</td>
                  <td className="mp-td-action"><a className="mp-row-cta" href={"/" + v.slug}>Voir la fiche <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M3 6h6m0 0l-2-2m2 2l-2 2" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg></a></td>
                </tr>
              ))}
            </tbody>
          </table>
        </article></div>
      </section>
      <HpFooter />
    </div>
  );
}

window.Homepage = Homepage;
window.BrandPage = BrandPage;
window.ModelPage = ModelPage;
