// Webshop / Modellen overzicht
const { useState, useEffect, useContext } = React;

const PageShop = ({ setPage, initialFilter = "all" }) => {
  const cart = useContext(CartContext);
  const langCtx = useContext(window.LangContext || React.createContext({ lang:"nl", t: (nl)=>nl }));
  const t = langCtx.t || ((nl) => nl);
  const lang = langCtx.lang || "nl";
  const LP = window.LP || ((o, f) => o && o[f]);
  const [filter, setFilter] = useState(initialFilter);
  const [sort, setSort] = useState("popular");
  const [q, setQ] = useState("");

  // Build unified product list
  const all = [
    ...Object.values(PRODUCTS).map(p => ({...p, kind:"bike"})),
    ...ACCESSORIES.map(a => ({...a, kind:"accessoire"})),
  ].filter(p => p.active !== false);

  const filtered = all
    .filter(p => filter === "all" ? true :
      filter === "fatbike" ? (p.id === "v20") :
      filter === "crossbike" ? (p.id === "gt2000") :
      filter === "accessoire" ? (p.kind === "accessoire") : true)
    .filter(p => !q || ((LP(p,"name",lang) || p.name || "") + " " + (LP(p,"short",lang) || p.short || "") + " " + (LP(p,"desc",lang) || p.desc || "")).toLowerCase().includes(q.toLowerCase()))
    .sort((a,b) => sort === "lowhigh" ? a.price - b.price :
                   sort === "highlow" ? b.price - a.price :
                   (a.kind === "bike" ? -1 : 1)); // bikes first

  return (
    <div className="page">
      {/* Header */}
      <section style={{padding:"48px 0 32px", borderBottom:"1px solid var(--line)", background:"var(--paper)"}}>
        <div className="wrap">
          <div className="eyebrow" style={{marginBottom:14}}>{t("Webshop · 2 modellen · 7 accessoires","Shop · 2 models · 7 accessories")}</div>
          <h1 className="h-display" style={{fontSize:"clamp(36px, 5vw, 64px)"}}>
            {t("De volledige","The complete")} <span className="accent">Zyro</span> {t("collectie.","collection.")}
          </h1>
          <p style={{color:"var(--ink-dim)", marginTop:14, maxWidth:640, fontSize:16}}>
            {t(
              "Twee EU type-goedgekeurde 250W e-bikes plus alle accessoires om er veilig en stoer mee op pad te gaan.",
              "Two EU type-approved 250W e-bikes plus all the accessories to ride safely and in style."
            )}
          </p>
        </div>
      </section>

      {/* Filter bar */}
      <section style={{padding:"24px 0", position:"sticky", top:"var(--nav-h)", background:"var(--bg)", zIndex:20, borderBottom:"1px solid var(--line)"}}>
        <div className="wrap" style={{display:"flex", gap:16, alignItems:"center", flexWrap:"wrap"}}>
          <div className="gap-8" style={{flexWrap:"wrap"}}>
            {[
              {id:"all", label:t("Alles","All")},
              {id:"fatbike", label:t("Fatbike","Fat-bike")},
              {id:"crossbike", label:t("Crossbike","Cross-bike")},
              {id:"accessoire", label:t("Accessoires","Accessories")},
            ].map(f => (
              <button key={f.id} onClick={()=>setFilter(f.id)}
                style={{
                  padding:"8px 14px", borderRadius:8, fontSize:13.5, fontWeight:500,
                  background: filter === f.id ? "var(--ink)" : "var(--paper)",
                  color: filter === f.id ? "var(--bg)" : "var(--ink)",
                  border: `1px solid ${filter === f.id ? "var(--ink)" : "var(--line)"}`,
                  cursor:"pointer", transition:"all .12s"
                }}>{f.label}</button>
            ))}
          </div>
          <div style={{display:"flex", alignItems:"center", gap:10, marginLeft:"auto", flexWrap:"wrap"}}>
            <div style={{position:"relative"}}>
              <Icon name="search" size={14} style={{position:"absolute", left:10, top:"50%", transform:"translateY(-50%)", color:"var(--ink-mute)"}}/>
              <input value={q} onChange={e=>setQ(e.target.value)} placeholder={t("Zoek…","Search…")} className="input" style={{height:38, paddingLeft:32, fontSize:13, width:180}}/>
            </div>
            <select value={sort} onChange={e=>setSort(e.target.value)} className="select" style={{height:38, fontSize:13, width:"auto"}}>
              <option value="popular">{t("Sorteer: populair","Sort: popular")}</option>
              <option value="lowhigh">{t("Prijs: laag → hoog","Price: low → high")}</option>
              <option value="highlow">{t("Prijs: hoog → laag","Price: high → low")}</option>
            </select>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section className="section-sm">
        <div className="wrap">
          {filtered.length === 0 ? (
            <div className="card" style={{padding:60, textAlign:"center"}}>
              <Icon name="search" size={30} style={{color:"var(--ink-mute)", margin:"0 auto 14px"}}/>
              <h3 className="h-display" style={{fontSize:22, marginBottom:8}}>{t("Geen producten gevonden","No products found")}</h3>
              <p style={{color:"var(--ink-dim)"}}>{t("Probeer een andere zoekterm of filter.","Try a different search or filter.")}</p>
            </div>
          ) : (
            <div className="prod-grid">
              {filtered.map(p => {
                const specs = LP(p, "specs", lang) || p.specs || {};
                const battery = lang === "en" ? specs.Battery : specs.Accu;
                const range = lang === "en" ? specs.Range : specs.Actieradius;
                const showDiscount = window.hasDiscount && window.hasDiscount(p);
                const buyable = window.isProductBuyable ? window.isProductBuyable(p) : (p.active !== false);
                const availLabel = (!buyable && window.availabilityLabel) ? window.availabilityLabel(p.availability_status, lang) : null;
                return (
                <article key={p.id} className="prod-card" onClick={() => p.kind === "bike" ? setPage(p.id) : null}
                  style={!buyable ? { opacity: 0.78 } : null}>
                  <div className="stage">
                    {p.kind === "bike" ? (
                      <img src={(window.GALLERY && window.GALLERY[p.id] && window.GALLERY[p.id][0]) || `assets/${p.id}-hero.jpg`}
                        alt={LP(p,"short",lang) || p.short}
                        style={{width:"100%", height:"100%", objectFit:"contain", display:"block", filter: buyable ? "none" : "grayscale(35%)"}}/>
                    ) : (
                      <div style={{padding:30, filter: buyable ? "none" : "grayscale(35%)"}}>{Acc[p.icon] && React.createElement(Acc[p.icon], {size: 130})}</div>
                    )}
                    <div style={{position:"absolute", top:12, left:12, display:"flex", gap:6}}>
                      {p.badge && <span className="tag dark-tag">{LP(p,"badge",lang)}</span>}
                      {availLabel && <span className="tag" style={{background:"var(--ink)", color:"#fff"}}>{availLabel}</span>}
                    </div>
                    {showDiscount && buyable && (
                      <div style={{position:"absolute", top:12, right:12}}>
                        <span className="tag warn">{window.discountLabel(p, lang)}</span>
                      </div>
                    )}
                  </div>
                  <div className="body">
                    <div className="mono" style={{fontSize:10.5, letterSpacing:".12em", color:"var(--ink-mute)", textTransform:"uppercase"}}>
                      {p.kind === "bike" ? `${LP(p,"type",lang)} · ${LP(p,"color",lang)}` : (LP(p,"type",lang) || t("Accessoire","Accessory"))}
                    </div>
                    <h3>{LP(p,"short",lang) || LP(p,"name",lang) || p.short || p.name}</h3>
                    {p.kind === "bike" && <div style={{marginTop:4}}><CardRating slug={p.id}/></div>}
                    <p className="desc">{p.kind === "bike" ? LP(p,"blurb",lang) : LP(p,"desc",lang)}</p>
                    {p.kind === "bike" && (
                      <div className="gap-8" style={{flexWrap:"wrap"}}>
                        <span className="tag"><Icon name="battery" size={11}/> {(battery || "").split(" · ")[1] || battery}</span>
                        <span className="tag"><Icon name="range" size={11}/> {range}</span>
                      </div>
                    )}
                    <div className="price-row">
                      <span className="price">{formatEUR(p.price)}</span>
                      {showDiscount && <span className="old">{formatEUR(p.oldPrice)}</span>}
                    </div>
                    {window.vatLabel && (
                      <div className="mono" style={{fontSize:10.5, color:"var(--ink-mute)", marginTop:-4, marginBottom:8}}>
                        {window.vatLabel(langCtx.lang)}
                      </div>
                    )}
                    <div className="ctas">
                      {p.kind === "bike" ? (
                        <>
                          <button className="btn btn-primary" style={{flex:1}} onClick={(e)=>{ e.stopPropagation(); setPage(p.id); }}>{t("Bekijk product","View product")}</button>
                          <button className="btn btn-ghost" onClick={(e)=>{ e.stopPropagation(); if (buyable) cart.add(p.id); }} disabled={!buyable} aria-label={t("In winkelmand","Add to cart")}><Icon name="cart" size={14}/></button>
                        </>
                      ) : buyable ? (
                        <button className="btn btn-accent btn-block" onClick={(e)=>{ e.stopPropagation(); cart.add(p.id); }}>
                          <Icon name="cart" size={14}/> {t("Voeg toe","Add")} · {formatEUR(p.price)}
                        </button>
                      ) : (
                        <button className="btn btn-ghost btn-block" disabled style={{opacity:.7, cursor:"not-allowed"}}>
                          {availLabel || (p.availability_status === "sold_out" ? t("Uitverkocht","Sold out") : t("Tijdelijk niet beschikbaar","Temporarily unavailable"))}
                        </button>
                      )}
                    </div>
                  </div>
                </article>
              );})}
            </div>
          )}
        </div>
      </section>

      {/* Promo strip */}
      <section className="section-sm">
        <div className="wrap">
          <div className="card dark" style={{padding:"32px 40px", display:"flex", justifyContent:"space-between", alignItems:"center", gap:24, flexWrap:"wrap", borderRadius:"var(--r-lg)"}}>
            <div>
              <div className="eyebrow" style={{color:"var(--accent)"}}>{t("Bundeldeal","Bundle deal")}</div>
              <h3 className="h-display" style={{fontSize:28, marginTop:8}}>{t("Zyro V20 Pro + ART-3 slot + helm","Zyro V20 Pro + ART-3 lock + helmet")}</h3>
              <p style={{color:"#aaa", marginTop:8, fontSize:14}}>{t("Compleet pakket — bespaar € 79 op accessoires.","Complete package — save €79 on accessories.")}</p>
            </div>
            <button className="btn btn-accent btn-lg" onClick={()=>setPage("v20")}>{t("Bekijk bundel","View bundle")} <Icon name="arrow" size={15}/></button>
          </div>
        </div>
      </section>
    </div>
  );
};

window.PageShop = PageShop;
