/* storefront.jsx — Home, Shop (browse + search), Product detail, About */

/* ---------------- Home ---------------- */
function Home() {
  const { t, lang, L, nav, db, addToCart } = useApp();
  const featured = db.products.filter((p) => p.featured).slice(0, 4);
  const cats = db.categories;

  return (
    <div>
      {/* HERO */}
      <section className="hero">
        <div className="wrap hero-in">
          <div className="hero-copy">
            <div className="kicker">{lang === "th" ? "ก่อตั้งในกรุงเทพฯ" : "Established in Bangkok"}</div>
            <h1 className="hero-title">
              {lang === "th" ? (<>ธนบัตรและเหรียญ<br/>สะสมหายาก</>) : (<>Rare notes &amp; coins,<br/>kept for collectors</>)}
            </h1>
            <p className="hero-sub">
              {lang === "th"
                ? "คัดสรรธนบัตรและเหรียญกษาปณ์ไทยที่หายาก ตรวจสอบความแท้ และส่งมอบอย่างพิถีพิถัน"
                : "A curated cabinet of authenticated Thai numismatics — examined, graded, and delivered with care."}
            </p>
            <div style={{ display: "flex", gap: 14, marginTop: 30, flexWrap: "wrap" }}>
              <Btn variant="gold" className="btn-lg" onClick={() => nav("shop")}>{t("hero_cta")}</Btn>
              <Btn variant="ghost" className="btn-lg" onClick={() => nav("about")}>{lang === "th" ? "เกี่ยวกับเรา" : "Our story"}</Btn>
            </div>
          </div>
          <div className="hero-art">
            <div className="hero-coin hero-coin-a"><Placeholder img={{ shape: "coin", tone: "gold", label: "" }} /></div>
            <div className="hero-coin hero-coin-b"><Placeholder img={{ shape: "note", tone: "paper", label: "" }} /></div>
            <div className="hero-coin hero-coin-c"><Placeholder img={{ shape: "coin", tone: "silver", label: "" }} /></div>
          </div>
        </div>
      </section>

      {/* FEATURED */}
      <section className="wrap" style={{ padding: "84px 0 20px" }}>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", marginBottom: 34, flexWrap: "wrap", gap: 12 }}>
          <div>
            <div className="kicker">{t("featured")}</div>
            <h2 className="section-title">{lang === "th" ? "รายการเด่นล่าสุด" : "Latest acquisitions"}</h2>
          </div>
          <a className="link-more" onClick={() => nav("shop")}>{lang === "th" ? "ดูทั้งหมด →" : "View all →"}</a>
        </div>
        <div className="grid">
          {featured.map((p) => <ProductCard key={p.id} p={p} />)}
        </div>
      </section>

      {/* CATEGORIES */}
      <section className="wrap" style={{ padding: "70px 0" }}>
        <div className="kicker" style={{ justifyContent: "center" }}>{t("browse_cat")}</div>
        <h2 className="section-title center" style={{ marginBottom: 38 }}>{lang === "th" ? "เลือกชมตามหมวดหมู่" : "Browse the cabinet"}</h2>
        <div className="cat-grid">
          {cats.map((c) => {
            const count = db.products.filter((p) => p.cat === c.id).length;
            const sample = db.products.find((p) => p.cat === c.id);
            return (
              <div key={c.id} className="cat-card" onClick={() => nav("shop", { catId: c.id })}>
                <div className="cat-thumb"><Placeholder img={sample ? sample.images[0] : { shape: "coin", tone: "gold" }} /></div>
                <div className="cat-info">
                  <h3 style={{ fontSize: 23 }}>{L(c, "name")}</h3>
                  <p className="muted" style={{ fontSize: 13, margin: "6px 0 0" }}>{L(c, "blurb")}</p>
                  <span className="cat-count">{count} {lang === "th" ? "รายการ" : "pieces"}</span>
                </div>
              </div>
            );
          })}
        </div>
      </section>

      {/* TRUST */}
      <section className="trust">
        <div className="wrap trust-in">
          {[
            { t: t("why1_t"), d: t("why1_d"), icon: "M12 3l7 3v5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6l7-3z M9.2 12l1.9 2 3.7-4" },
            { t: t("why2_t"), d: t("why2_d"), icon: "M3 7h11v8H3z M14 10h4l3 3v2h-7z M7 19a1.6 1.6 0 100-3.2A1.6 1.6 0 007 19z M18 19a1.6 1.6 0 100-3.2A1.6 1.6 0 0018 19z" },
            { t: t("why3_t"), d: t("why3_d"), icon: "M6 10V8a6 6 0 1112 0v2 M5 10h14v10H5z M12 14v3" },
          ].map((it, i) => (
            <div className="trust-item" key={i}>
              <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d={it.icon}/></svg>
              <div>
                <h4 style={{ fontSize: 18 }}>{it.t}</h4>
                <p className="muted" style={{ fontSize: 13.5, margin: "5px 0 0" }}>{it.d}</p>
              </div>
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

/* ---------------- Product Card ---------------- */
function ProductCard({ p }) {
  const { L, lang, nav } = useApp();
  const cat = DB.getCategory(p.cat);
  const soldOut = p.qty <= 0;
  return (
    <article className="card" onClick={() => nav("product", { id: p.id })}>
      <div style={{ position: "relative" }}>
        <Placeholder img={p.images[0]} />
        {p.certified && <span className="ribbon">{lang === "th" ? "มีใบรับรอง" : "Certified"}</span>}
      </div>
      <div className="card-body">
        <span className="card-era">{L(p, "era")}</span>
        <div className="card-name">{L(p, "name")}</div>
        <div className="card-meta">
          <span className="chip">{p.grade}</span>
          <span className="chip">{L(p, "material")}</span>
          {p.year_ce > 0 && <span className="chip">{p.year_ce}</span>}
        </div>
        <div className="card-foot">
          <span className="price">{DB.THB(p.price)}</span>
          <span className="price-sm">{soldOut ? (lang === "th" ? "ขายแล้ว" : "Sold") : `${p.qty} ${lang === "th" ? "ชิ้น" : "left"}`}</span>
        </div>
      </div>
    </article>
  );
}

/* ---------------- Shop / Browse ---------------- */
function Shop({ catId, q }) {
  const { L, lang, t, db, nav } = useApp();
  const [activeCat, setActiveCat] = useState(catId || "all");
  const [query, setQuery] = useState(q || "");
  const [sort, setSort] = useState("featured");

  useEffect(() => { if (catId) setActiveCat(catId); }, [catId]);

  const list = useMemo(() => {
    let r = db.products.slice();
    if (activeCat !== "all") r = r.filter((p) => p.cat === activeCat);
    if (query.trim()) {
      const k = query.toLowerCase();
      r = r.filter((p) => (p.name_en + p.name_th + p.era_en + p.era_th + p.material_en + p.denomination).toLowerCase().includes(k));
    }
    if (sort === "price_low") r.sort((a, b) => a.price - b.price);
    else if (sort === "price_high") r.sort((a, b) => b.price - a.price);
    else if (sort === "year") r.sort((a, b) => (a.year_ce || 9999) - (b.year_ce || 9999));
    else r.sort((a, b) => (b.featured ? 1 : 0) - (a.featured ? 1 : 0));
    return r;
  }, [db.products, activeCat, query, sort]);

  return (
    <div className="wrap" style={{ padding: "44px 0 80px" }}>
      <div className="kicker">{lang === "th" ? "คอลเลกชัน" : "The Collection"}</div>
      <h1 className="section-title" style={{ marginBottom: 26 }}>{lang === "th" ? "เลือกชมทั้งหมด" : "Browse all pieces"}</h1>

      <div className="shop-toolbar">
        <div className="search-box">
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="m21 21-4-4"/></svg>
          <input placeholder={t("search_ph")} value={query} onChange={(e) => setQuery(e.target.value)} />
        </div>
        <select value={sort} onChange={(e) => setSort(e.target.value)} style={{ width: "auto" }}>
          <option value="featured">{lang === "th" ? "แนะนำ" : "Featured"}</option>
          <option value="price_low">{lang === "th" ? "ราคาน้อย → มาก" : "Price: low → high"}</option>
          <option value="price_high">{lang === "th" ? "ราคามาก → น้อย" : "Price: high → low"}</option>
          <option value="year">{lang === "th" ? "ปีเก่าสุดก่อน" : "Oldest first"}</option>
        </select>
      </div>

      <div className="filter-row">
        <button className={`fil ${activeCat === "all" ? "on" : ""}`} onClick={() => setActiveCat("all")}>{t("all_items")}</button>
        {db.categories.map((c) => (
          <button key={c.id} className={`fil ${activeCat === c.id ? "on" : ""}`} onClick={() => setActiveCat(c.id)}>{L(c, "name")}</button>
        ))}
      </div>

      {list.length === 0 ? (
        <p className="muted" style={{ padding: "60px 0", textAlign: "center" }}>{lang === "th" ? "ไม่พบรายการที่ค้นหา" : "No pieces match your search."}</p>
      ) : (
        <div className="grid" style={{ marginTop: 28 }}>
          {list.map((p) => <ProductCard key={p.id} p={p} />)}
        </div>
      )}
    </div>
  );
}

/* ---------------- About ---------------- */
function AboutPage() {
  const { lang, nav } = useApp();
  return (
    <div className="wrap-narrow" style={{ maxWidth: 760, margin: "0 auto", padding: "60px 28px 90px" }}>
      <div className="kicker">{lang === "th" ? "เกี่ยวกับเรา" : "Our Story"}</div>
      <h1 className="section-title" style={{ marginBottom: 24 }}>{lang === "th" ? "สะสมประวัติศาสตร์ ทีละชิ้น" : "Collecting history, one piece at a time"}</h1>
      <p style={{ fontSize: 17, lineHeight: 1.8, color: "var(--ink-soft)" }}>
        {lang === "th"
          ? "สยามเฮอริเทจคัดสรรธนบัตรและเหรียญกษาปณ์ไทยที่หายาก ทุกชิ้นผ่านการตรวจสอบความแท้และประเมินสภาพโดยผู้เชี่ยวชาญ ก่อนส่งมอบให้นักสะสมอย่างพิถีพิถัน"
          : "Siam Heritage curates rare Thai banknotes and coins. Every piece is authenticated and graded by specialists before it reaches a collector's cabinet."}
      </p>
      <div style={{ marginTop: 36 }}>
        <Btn variant="gold" onClick={() => nav("shop")}>{lang === "th" ? "ชมคอลเลกชัน" : "Browse the collection"}</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { Home, ProductCard, Shop, AboutPage });
