// =========================================================
// Pages: Home, Category, Product Detail
// =========================================================

function HomePage({ navigate, onAdd, heroLayout }) {
  const [state] = useStore();
  const products = getProducts();
  const counts = getCountByCat();
  const featured = products.filter(p => p.tag === "Bestseller" || p.tag === "Sale" || p.tag === "Heritage").slice(0, 8);
  const newArrivals = products.filter(p => p.tag === "New").slice(0, 4);

  return (
    <main>
      {/* === HERO === */}
      <section className="hero" style={{ position: "relative" }}>
        <MountainStrip position="bottom" />
        <div className="wrap">
          <div>
            <div className="hero-eyebrow">
              <span className="dot" />
              <span className="h-mono">Vol. 12 · Spring 2026</span>
              <span className="h-rule" style={{ flex: 1 }} />
              <span className="h-mono" style={{ fontFamily: "var(--font-deva)" }}>संस्करण १२</span>
            </div>
            <h1 className="h-display">
              <span className="ne-line">हिमालयदेखि स्टेजसम्म</span>
              The instruments<br />of the <span className="it">himalaya</span>,<br />delivered.
            </h1>
            <p className="lead">
              From hand-carved sarangis of the eastern hills to gig-ready amplifiers — forty curated instruments, cash on delivery anywhere in Nepal.
            </p>
            <div className="hero-cta">
              <button className="btn" onClick={() => navigate({ name: "category", id: "traditional" })}>Shop Traditional</button>
              <button className="btn ghost" onClick={() => navigate({ name: "category", id: "guitars" })}>Browse Guitars</button>
            </div>
            <div className="meta">
              <span>40 Instruments</span>
              <span style={{ width: 4, height: 4, background: "var(--ink-3)", borderRadius: "50%" }} />
              <span>5 Categories</span>
              <span style={{ width: 4, height: 4, background: "var(--ink-3)", borderRadius: "50%" }} />
              <span>{toDeva("नगद डेलिभरी")} · CASH</span>
            </div>
          </div>
          {heroLayout === "marquee" ? (
            <React.Fragment>
              <div className="hero-stage"><Placeholder label="sarangi · editorial shot" tone="dark" style={{ height: "100%" }} /></div>
              <div className="hero-stage side"><Placeholder label="madal close-up" tone="saffron" style={{ height: "100%" }} /></div>
            </React.Fragment>
          ) : (
            <div className="hero-stage">
              <Placeholder label="hero · sarangi / madal editorial composition" tone="dark" style={{ height: "100%" }} />
            </div>
          )}
        </div>
      </section>

      {/* === CATEGORIES === */}
      <section className="section">
        <div className="wrap">
          <div className="section-head">
            <div>
              <span className="h-eyebrow">Browse by tradition</span>
              <h2 className="h-display">Five rooms,<br />one storefront.</h2>
            </div>
            <div className="meta h-mono">Choose a category →</div>
          </div>
          <div className="cat-strip">
            {CATS.map((c, i) => (
              <button key={c.id} className="cat-card" onClick={() => navigate({ name: "category", id: c.id })}>
                <span className="num">0{i + 1} / 0{CATS.length}</span>
                <div className="en">{c.en}</div>
                <div className="ne">{c.ne}</div>
                <div className="count">
                  <span>{counts[c.id]} items</span>
                  <span>↗</span>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* === FEATURED EDITORIAL BLOCK === */}
      <section className="section" style={{ borderTop: "1px solid var(--rule)" }}>
        <div className="wrap">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 56, alignItems: "center", marginBottom: 56 }}>
            <div>
              <span className="h-eyebrow">Featured maker · {toDeva("बनारस")}</span>
              <h2 className="h-display" style={{ fontSize: "clamp(36px, 4.5vw, 56px)", margin: "16px 0 18px" }}>
                The sarangi-makers<br />of Bhojpur.
              </h2>
              <p style={{ color: "var(--ink-2)", lineHeight: 1.7, maxWidth: "44ch" }}>
                For three generations, the Nepali family in Bhojpur has carved sarangis from a single block of khirra wood, drying each piece for two seasons before stringing. We source directly — every instrument signed inside the body.
              </p>
              <div style={{ marginTop: 28 }}>
                <button className="link-btn" onClick={() => navigate({ name: "product", id: "p02" })}>View the Bhojpur Sarangi →</button>
              </div>
            </div>
            <div style={{ aspectRatio: "1", border: "1px solid var(--rule)" }}>
              <Placeholder label="workshop · khirra wood / carving in progress" tone="" style={{ height: "100%" }} />
            </div>
          </div>
        </div>
      </section>

      {/* === BESTSELLERS === */}
      <section className="section">
        <div className="wrap">
          <div className="section-head">
            <div>
              <span className="h-eyebrow">Most ordered this season</span>
              <h2 className="h-display">Bestsellers.</h2>
            </div>
            <div className="meta">
              <button className="link-btn" onClick={() => navigate({ name: "category", id: "traditional" })}>View all →</button>
            </div>
          </div>
          <div className="product-grid">
            {featured.map(p => (
              <ProductCard key={p.id} p={p} onClick={pp => navigate({ name: "product", id: pp.id })} onAdd={onAdd} />
            ))}
          </div>
        </div>
      </section>

      {/* === NEW ARRIVALS BAR === */}
      <section className="section" style={{ background: "var(--bg-2)", borderTop: 0 }}>
        <div className="wrap">
          <div className="section-head">
            <div>
              <span className="h-eyebrow">Just landed in store</span>
              <h2 className="h-display">New arrivals.</h2>
            </div>
            <div className="meta h-mono"><span className="h-deva">नयाँ · </span>{toDeva(newArrivals.length)} items</div>
          </div>
          <div className="product-grid">
            {newArrivals.map(p => (
              <ProductCard key={p.id} p={p} onClick={pp => navigate({ name: "product", id: pp.id })} onAdd={onAdd} />
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

// =========================================================
// Category Page
// =========================================================
function CategoryPage({ catId, navigate, onAdd }) {
  const [state] = useStore();
  const cat = CAT_BY_ID[catId];
  const counts = getCountByCat();
  const allProducts = getProducts();
  const [sort, setSort] = React.useState("featured");
  const [priceBand, setPriceBand] = React.useState("all"); // all, low, mid, high
  const [tagFilter, setTagFilter] = React.useState("all");

  const products = React.useMemo(() => {
    let list = allProducts.filter(p => p.cat === catId);
    if (priceBand === "low") list = list.filter(p => p.price < 5000);
    if (priceBand === "mid") list = list.filter(p => p.price >= 5000 && p.price < 20000);
    if (priceBand === "high") list = list.filter(p => p.price >= 20000);
    if (tagFilter === "sale") list = list.filter(p => p.was);
    if (tagFilter === "new") list = list.filter(p => p.tag === "New");
    if (sort === "lowhigh") list = [...list].sort((a, b) => a.price - b.price);
    if (sort === "highlow") list = [...list].sort((a, b) => b.price - a.price);
    if (sort === "name") list = [...list].sort((a, b) => a.name.localeCompare(b.name));
    return list;
  }, [catId, sort, priceBand, tagFilter, allProducts]);

  return (
    <main className="cat-page">
      <div className="wrap">
        <div className="crumbs">
          <a onClick={() => navigate({ name: "home" })} style={{ cursor: "pointer" }}>Home</a>
          <span className="sep">/</span>
          <span>{cat.en}</span>
        </div>
        <div className="cat-hero">
          <div>
            <span className="h-eyebrow">{counts[catId]} instruments</span>
            <h1>{cat.en}</h1>
            <div className="ne">{cat.ne}</div>
          </div>
          <div>
            <p className="desc">{cat.desc}</p>
            <div className="stats">
              <span>{toDeva(counts[catId])} items</span>
              <span>·</span>
              <span>cash delivery</span>
              <span>·</span>
              <span>nepal-wide</span>
            </div>
          </div>
        </div>

        <div className="cat-toolbar">
          <span className="h-mono" style={{ marginRight: 8 }}>Price:</span>
          {[["all", "All"], ["low", "Under 5K"], ["mid", "5K – 20K"], ["high", "20K+"]].map(([k, label]) => (
            <button key={k} className="chip" aria-pressed={priceBand === k} onClick={() => setPriceBand(k)}>{label}</button>
          ))}
          <span className="h-mono" style={{ marginLeft: 16, marginRight: 8 }}>Tag:</span>
          {[["all", "All"], ["new", "New"], ["sale", "On Sale"]].map(([k, label]) => (
            <button key={k} className="chip" aria-pressed={tagFilter === k} onClick={() => setTagFilter(k)}>{label}</button>
          ))}
          <div className="toolbar-right">
            <span className="h-mono">Sort by:</span>
            <select className="select-bare" value={sort} onChange={e => setSort(e.target.value)}>
              <option value="featured">Featured</option>
              <option value="lowhigh">Price · Low to High</option>
              <option value="highlow">Price · High to Low</option>
              <option value="name">Name · A to Z</option>
            </select>
          </div>
        </div>

        {products.length === 0 ? (
          <div style={{ padding: "80px 0", textAlign: "center", color: "var(--ink-3)" }}>
            <div className="h-deva" style={{ fontSize: 28, color: "var(--ink-2)" }}>केही फेला परेन</div>
            <p>No items match these filters.</p>
          </div>
        ) : (
          <div className="product-grid">
            {products.map(p => (
              <ProductCard key={p.id} p={p} onClick={pp => navigate({ name: "product", id: pp.id })} onAdd={onAdd} />
            ))}
          </div>
        )}
      </div>
    </main>
  );
}

// =========================================================
// Product Detail Page
// =========================================================
function ProductPage({ id, navigate, onAdd }) {
  const [state] = useStore();
  const p = getProductById(id);
  const [qty, setQty] = React.useState(1);
  const [activeThumb, setActiveThumb] = React.useState(0);

  if (!p) return (
    <main className="pdp"><div className="wrap"><p>Product not found.</p></div></main>
  );

  const cat = CAT_BY_ID[p.cat];
  const tone = productPlaceholderTone(p.id);
  const phLabel = productPhLabel(p);
  const related = getProducts().filter(x => x.cat === p.cat && x.id !== p.id).slice(0, 4);

  return (
    <main className="pdp">
      <div className="wrap">
        <div className="crumbs">
          <a onClick={() => navigate({ name: "home" })} style={{ cursor: "pointer" }}>Home</a>
          <span className="sep">/</span>
          <a onClick={() => navigate({ name: "category", id: p.cat })} style={{ cursor: "pointer" }}>{cat.en}</a>
          <span className="sep">/</span>
          <span>{p.name}</span>
        </div>

        <div className="pdp-main">
          <div className="pdp-gallery">
            <div className="main-shot">
              <Placeholder
                label={[`${phLabel} · main`, `${phLabel} · detail`, `${phLabel} · in use`, `${phLabel} · scale`][activeThumb]}
                tone={[tone, "", "dark", "saffron"][activeThumb]}
                style={{ height: "100%" }} />
            </div>
            <div className="thumbs">
              {[0, 1, 2, 3].map(i => (
                <div key={i} className={"thumb" + (activeThumb === i ? " active" : "")} onClick={() => setActiveThumb(i)}>
                  <Placeholder label={"" + (i + 1)} tone={[tone, "", "dark", "saffron"][i]} style={{ height: "100%", padding: 4 }} />
                </div>
              ))}
            </div>
          </div>

          <div className="pdp-info">
            <div className="cat-line">
              <span>{cat.en}</span>
              <span style={{ width: 4, height: 4, background: "var(--ink-3)", borderRadius: "50%" }} />
              <span>{p.origin}</span>
              {p.tag && (<>
                <span style={{ width: 4, height: 4, background: "var(--ink-3)", borderRadius: "50%" }} />
                <span style={{ color: "var(--accent)" }}>{p.tag}</span>
              </>)}
            </div>
            <h1>{p.name}</h1>
            <div className="ne-name">{p.ne}</div>

            <div className="price-row">
              <span className="price-now">{NPR(p.price)}</span>
              {p.was && <span className="price-was">{NPR(p.was)}</span>}
              {p.was && <span className="h-mono" style={{ color: "var(--accent)" }}>SAVE {NPR(p.was - p.price)}</span>}
            </div>

            <p className="blurb">{p.desc}</p>

            <div className="specs">
              <div className="row"><span className="k">Origin</span><span>{p.origin}</span></div>
              <div className="row"><span className="k">Material</span><span>{p.body}</span></div>
              <div className="row"><span className="k">Category</span><span>{cat.en} · {cat.ne}</span></div>
              <div className="row"><span className="k">Payment</span><span>Cash on delivery</span></div>
              <div className="row"><span className="k">Delivery</span><span>Nepal-wide · 2–7 days</span></div>
            </div>

            <div className="qty-row">
              <div className="qty">
                <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
                <input value={qty} onChange={e => setQty(Math.max(1, parseInt(e.target.value) || 1))} />
                <button onClick={() => setQty(qty + 1)}>+</button>
              </div>
              <button className="btn accent" style={{ flex: 1 }} onClick={() => onAdd(p, qty)}>Add to cart · {NPR(p.price * qty)}</button>
            </div>

            <p className="h-mono" style={{ marginTop: 22, color: "var(--ink-3)" }}>
              ☎ Store keeper will call within 24 hours to confirm order ·{" "}
              <span className="h-deva">२४ घन्टा भित्र फोन गरिनेछ</span>
            </p>
          </div>
        </div>

        {related.length > 0 && (
          <section className="section" style={{ borderTop: "1px solid var(--rule)", marginTop: 80 }}>
            <div className="section-head">
              <div>
                <span className="h-eyebrow">You may also like</span>
                <h2 className="h-display" style={{ fontSize: "clamp(28px, 3.4vw, 40px)" }}>More from {cat.en}</h2>
              </div>
              <button className="link-btn" onClick={() => navigate({ name: "category", id: p.cat })}>View all →</button>
            </div>
            <div className="product-grid">
              {related.map(rp => (
                <ProductCard key={rp.id} p={rp} onClick={pp => navigate({ name: "product", id: pp.id })} onAdd={onAdd} />
              ))}
            </div>
          </section>
        )}
      </div>
    </main>
  );
}

Object.assign(window, { HomePage, CategoryPage, ProductPage });
