// Home + Shop + Product pages

const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP } = React;

// ===== HOME =====
function HomePage() {
  const { t, lang, formatPrice, addToCart } = window.useStore();
  const C = MASKA_CONTENT;
  const flagship = MASKA_CATALOG.groups.hero_flagship;
  const wraps = MASKA_CATALOG.groups.wraps.slice(0, 4);

  return (
    <div data-screen-label="01 Home">
      {/* Hero */}
      <section className="hero">
        <div className="hero-bg"><img src="media/lifestyle-furoshiki-wrapping.webp" alt=""/></div>
        <div className="hero-meta">
          <div className="hero-meta-stack">
            <div><strong>EST.</strong> 2013 · Dubai</div>
            <div>522 products · 5 stores</div>
            <div>{lang === "ar" ? "مصنوع يدوياً في د3" : "Handmade in d3"}</div>
          </div>
        </div>
        <div className="shell hero-content">
          <div className="eyebrow" style={{color:"var(--gold)"}}>― {C.brand.since}</div>
          <h1 className="hero-h1" style={{marginTop: 16}}>
            {t("hero_h1_a")}<br/><em>{t("hero_h1_b")}</em>
          </h1>
          <p className="hero-sub">{t("hero_sub")}</p>
          <div className="hero-ctas">
            <a href="#/shop" className="btn">{t("shop_by_occasion_cta")} <Icon.arrow/></a>
            <a href="#/services" className="btn btn-ghost" style={{borderColor:"rgba(246,239,228,0.6)", color:"var(--paper)"}}>{t("book_wrapping")}</a>
          </div>
        </div>
      </section>

      {/* Shop by occasion */}
      <section className="section">
        <div className="shell">
          <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-end", flexWrap:"wrap", gap: 20, marginBottom: 40}}>
            <div>
              <div className="eyebrow">― {t("occasion_eyebrow")}</div>
              <h2 style={{marginTop: 14, fontStyle:"italic", fontWeight: 300}}>{t("occasion_title")}</h2>
              <p className="lede" style={{marginTop: 12}}>{t("occasion_sub")}</p>
            </div>
            <a href="#/shop" className="btn-link">{t("all_products")} <Icon.arrow/></a>
          </div>
          <div className="occasion-grid">
            {C.occasions.map(o => (
              <a key={o.id} className="occasion-tile" href={`#/c/${o.id}`}>
                <img src={o.img} alt=""/>
                <div className="occasion-tile-content">
                  <div className="occasion-tile-label">{lang === "ar" ? o.ar : o.en}</div>
                  <div className="occasion-tile-meta">{o.meta_en}</div>
                </div>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Signature */}
      <section className="section" style={{background: "var(--paper-2)"}}>
        <div className="shell">
          <div className="signature">
            <div className="signature-img-wrap">
              <img src="media/product-03-fabric-wrap.webp" alt="The original fabric wrap"/>
              <div className="signature-tag">↻ {lang === "ar" ? "قابل لإعادة الاستخدام" : "Reusable by design"}</div>
            </div>
            <div>
              <div className="eyebrow">― {t("signature_eyebrow")}</div>
              <h2 style={{marginTop: 14}}>{t("signature_title").split('.')[0]}.<br/><span className="it" style={{fontStyle:"italic"}}>{lang === "ar" ? "" : "Since 2013."}</span></h2>
              <p className="lede" style={{marginTop: 20}}>{t("signature_body")}</p>
              <div className="signature-feat-row">
                <div className="feat-chip"><span className="px">古</span> {lang === "ar" ? "تراث الفوروشيكي" : "Furoshiki heritage"}</div>
                <div className="feat-chip"><span className="px">↻</span> {t("reusable")}</div>
                <div className="feat-chip"><span className="px">✿</span> {lang === "ar" ? "صناعة يدوية" : "Hand-finished"}</div>
              </div>
              <div style={{marginTop: 32}}>
                <a href="#/c/wraps" className="btn">{t("shop_wraps")} <Icon.arrow/></a>
              </div>
            </div>
          </div>

          {/* flagship row */}
          <div style={{marginTop: 64}}>
            <div className="ribbon-rule" style={{marginBottom: 24}}>{lang === "ar" ? "المجموعات الأكثر شغفاً" : "The signature collection"}</div>
            <div className="product-grid">
              {flagship.map(p => <ProductCard key={p.handle} product={p}/>)}
            </div>
          </div>
        </div>
      </section>

      {/* Services teaser */}
      <section className="section">
        <div className="shell">
          <div style={{textAlign:"center", marginBottom: 48}}>
            <div className="eyebrow" style={{justifyContent:"center"}}>― {t("services_eyebrow")}</div>
            <h2 style={{marginTop: 14, fontStyle:"italic", fontWeight: 300}}>{t("services_title")}</h2>
          </div>
          <div className="service-row">
            <a href="#/services" className="service-card">
              <img src="media/service-door-to-door-01.webp" alt=""/>
              <div className="service-card-content">
                <div>
                  <div className="eyebrow" style={{color:"var(--gold)"}}>― 01 / Walk-in</div>
                  <h3 style={{fontFamily:"Fraunces, serif", fontStyle:"italic", marginTop:14, fontSize:36, color:"var(--paper)"}}>{t("svc_in_store_title")}</h3>
                </div>
                <div>
                  <p style={{maxWidth:"38ch", marginBottom: 20, lineHeight:1.6}}>{t("in_store_wrapping_body")}</p>
                  <span className="btn-link" style={{color:"var(--paper)", borderColor:"var(--gold)"}}>{t("learn_more")} <Icon.arrow/></span>
                </div>
              </div>
            </a>
            <a href="#/services" className="service-card">
              <img src="media/service-wrap-from-home.webp" alt=""/>
              <div className="service-card-content">
                <div>
                  <div className="eyebrow" style={{color:"var(--gold)"}}>― 02 / Door-to-Door</div>
                  <h3 style={{fontFamily:"Fraunces, serif", fontStyle:"italic", marginTop:14, fontSize:36, color:"var(--paper)"}}>{t("svc_door_title")}</h3>
                </div>
                <div>
                  <p style={{maxWidth:"38ch", marginBottom: 20, lineHeight:1.6}}>{t("door_to_door_body")}</p>
                  <span className="btn-link" style={{color:"var(--paper)", borderColor:"var(--gold)"}}>{t("book_now")} <Icon.arrow/></span>
                </div>
              </div>
            </a>
          </div>
        </div>
      </section>

      {/* Story band */}
      <section className="story-band">
        <div className="shell">
          <div className="story-band-inner">
            <div className="story-furoshiki-img">
              <img src="media/story-furoshiki-origin.webp" alt="Furoshiki origin"/>
              <div className="story-stamp">古 風呂敷<small>FUROSHIKI · JAPAN</small></div>
            </div>
            <div>
              <div className="eyebrow">― {t("story_eyebrow")}</div>
              <h2 style={{marginTop: 14, fontStyle:"italic", fontWeight: 300}}>{t("story_title")}</h2>
              <p className="lede" style={{marginTop: 22}}>{t("story_body")}</p>

              <div className="timeline-pills">
                <div className="timeline-pill"><b>2013</b> {lang === "ar" ? "بدأت من جميرا" : "Born in Jumeirah"}</div>
                <div className="timeline-pill"><b>2014</b> {lang === "ar" ? "مبادرة آلة الخياطة" : "Sewing Machine Initiative"}</div>
                <div className="timeline-pill"><b>2015</b> {lang === "ar" ? "استوديو في d3" : "Studio at d3"}</div>
                <div className="timeline-pill"><b>2024</b> {lang === "ar" ? "أسبوع دبي للتصميم" : "Dubai Design Week"}</div>
              </div>

              <div style={{marginTop: 32}}>
                <a href="#/our-story" className="btn-link">{t("read_story")} <Icon.arrow/></a>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Press row */}
      <section className="section-sm">
        <div className="shell">
          <div style={{textAlign:"center", marginBottom: 24}}>
            <div className="eyebrow">― {t("press_eyebrow")}</div>
          </div>
          <div className="press-row">
            {MASKA_CONTENT.press.map(p => <div key={p} className="press-item">{p}</div>)}
          </div>
        </div>
      </section>

      {/* Stores + Corporate CTA */}
      <section className="section" style={{background: "var(--ink)", color: "var(--paper)"}}>
        <div className="shell">
          <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 56, alignItems:"center"}} className="store-corp-split">
            <div>
              <div className="eyebrow" style={{color:"var(--gold)"}}>― {lang === "ar" ? "تجدنا في" : "Find us in"}</div>
              <h2 style={{marginTop: 14, fontStyle:"italic", fontWeight: 300, color:"var(--paper)"}}>{lang === "ar" ? "خمسة متاجر في دبي." : "Five stores across Dubai."}</h2>
              <p className="lede" style={{color:"rgba(246,239,228,0.78)", marginTop: 20}}>{lang === "ar" ? "من جميرا إلى ند الشبا — يمكنك المرور لتغليف هديتك في عشر دقائق، أو لتصفّح لفائفنا الموسمية." : "From Jumeirah to Nad Al Sheba — walk in to have a gift wrapped in ten minutes, or browse our seasonal wraps in person."}</p>
              <a href="#/stores" className="btn btn-gold" style={{marginTop: 32}}>{lang === "ar" ? "اعثر على متجر" : "Find a store"} <Icon.arrow/></a>
            </div>
            <div style={{borderLeft: "1px solid rgba(246,239,228,0.15)", paddingLeft: 48}}>
              <div className="eyebrow" style={{color:"var(--rouge)"}}>― {lang === "ar" ? "للشركات" : "For corporate"}</div>
              <h2 style={{marginTop: 14, fontStyle:"italic", fontWeight: 300, color:"var(--paper)"}}>{lang === "ar" ? "هدايا تحمل اسم علامتك." : "Gifts that carry your brand."}</h2>
              <p className="lede" style={{color:"rgba(246,239,228,0.78)", marginTop: 20}}>{lang === "ar" ? "من 50 إلى 5000 قطعة — مصممة، ملفوفة، موصلة بأسلوب ماسكا." : "From 50 to 5,000 pieces — designed, wrapped and dispatched the MASKA way."}</p>
              <a href="#/corporate" className="btn btn-rouge" style={{marginTop: 32}}>{lang === "ar" ? "أرسل طلباً" : "Send an enquiry"} <Icon.arrow/></a>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
window.HomePage = HomePage;

// ===== SHOP =====
function ShopPage({ filter = null }) {
  const { t, lang, formatPrice } = window.useStore();
  const C = MASKA_CONTENT;
  const route = useRoute();

  // Resolve products
  const collectionMeta = useMemoP(() => {
    if (!filter) return null;
    const occ = C.occasions.find(o => o.id === filter);
    if (occ) return { label: lang === "ar" ? occ.ar : occ.en, sub: occ.meta_en, group: occ.group, kind: "occasion" };
    const ty = C.types.find(o => o.id === filter);
    if (ty) return { label: lang === "ar" ? ty.ar : ty.en, sub: "", group: ty.group, kind: "type" };
    return null;
  }, [filter, lang]);

  const products = useMemoP(() => {
    if (!collectionMeta) {
      // shop hub — show variety from many groups
      const groups = ["giftsets", "wraps", "envelopes", "cards", "baskets", "boxes", "charms"];
      const all = [];
      const seen = new Set();
      for (const g of groups) {
        for (const p of (MASKA_CATALOG.groups[g] || [])) {
          if (!seen.has(p.handle)) { seen.add(p.handle); all.push(p); }
        }
      }
      return all;
    }
    return MASKA_CATALOG.groups[collectionMeta.group] || [];
  }, [collectionMeta]);

  const [sort, setSort] = useStateP("newest");
  const sorted = useMemoP(() => {
    const a = [...products];
    if (sort === "price_low") a.sort((x,y) => parseFloat(x.price) - parseFloat(y.price));
    else if (sort === "price_high") a.sort((x,y) => parseFloat(y.price) - parseFloat(x.price));
    return a;
  }, [products, sort]);

  // Determine which tab is "active" for hub view
  const activeTab = filter || "all";

  return (
    <div data-screen-label="02 Shop">
      {/* Shop hero */}
      <section className="shop-hero">
        <div className="shell">
          <div className="breadcrumb">
            <a href="#/">{lang === "ar" ? "الرئيسية" : "Home"}</a>
            <span className="sep">/</span>
            <a href="#/shop">{t("shop")}</a>
            {collectionMeta && <><span className="sep">/</span> {collectionMeta.label}</>}
          </div>
          <div className="eyebrow" style={{marginBottom: 12}}>― {collectionMeta ? (collectionMeta.kind === "occasion" ? t("shop_by_occasion") : t("shop_by_type")) : t("shop")}</div>
          <h1 className="shop-hero-title">{collectionMeta ? collectionMeta.label : (lang === "ar" ? "كل الهدايا" : "Everything we wrap.")}</h1>
          {collectionMeta?.sub && <p className="lede" style={{marginTop: 14}}>{collectionMeta.sub}</p>}

          {/* Two-track tabs */}
          <div style={{marginTop: 36, display:"grid", gap: 16}}>
            <div>
              <div className="eyebrow" style={{marginBottom: 10}}>{t("shop_by_occasion")}</div>
              <div className="shop-tab-bar">
                {C.occasions.map(o => (
                  <a key={o.id} href={`#/c/${o.id}`} className={"shop-tab " + (activeTab === o.id ? "active" : "")}>
                    {lang === "ar" ? o.ar : o.en}
                  </a>
                ))}
              </div>
            </div>
            <div>
              <div className="eyebrow" style={{marginBottom: 10}}>{t("shop_by_type")}</div>
              <div className="shop-tab-bar">
                <a href="#/shop" className={"shop-tab " + (activeTab === "all" ? "active" : "")}>{t("all_products")}</a>
                {C.types.map(o => (
                  <a key={o.id} href={`#/c/${o.id}`} className={"shop-tab " + (activeTab === o.id ? "active" : "")}>
                    {lang === "ar" ? o.ar : o.en}
                  </a>
                ))}
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Sort + count */}
      <section style={{padding:"24px 0", borderBottom:"1px solid var(--line)"}}>
        <div className="shell" style={{display:"flex", justifyContent:"space-between", alignItems:"center", gap:20, flexWrap:"wrap"}}>
          <div className="eyebrow">{sorted.length} {t("results_count")}</div>
          <div style={{display:"flex", alignItems:"center", gap:10}}>
            <span className="eyebrow">{t("sort")}:</span>
            <select value={sort} onChange={e => setSort(e.target.value)} style={{background:"transparent", border:0, fontSize:13, letterSpacing:"0.08em"}}>
              <option value="newest">{t("newest")}</option>
              <option value="price_low">{t("price_low")}</option>
              <option value="price_high">{t("price_high")}</option>
            </select>
          </div>
        </div>
      </section>

      {/* Grid */}
      <section style={{padding:"48px 0 96px"}}>
        <div className="shell">
          {sorted.length === 0 && (
            <div style={{textAlign:"center", padding:"80px 20px", color:"var(--muted)"}}>
              <p style={{fontFamily:"Fraunces, serif", fontSize: 22, fontStyle:"italic"}}>{lang === "ar" ? "لا توجد منتجات بعد." : "Nothing here yet."}</p>
              <a href="#/shop" className="btn-link" style={{marginTop: 20}}>{t("back_to_shop")} <Icon.arrow/></a>
            </div>
          )}
          <div className="product-grid">
            {sorted.map(p => <ProductCard key={p.handle} product={p}/>)}
          </div>
        </div>
      </section>
    </div>
  );
}
window.ShopPage = ShopPage;

// ===== PRODUCT =====
function ProductPage({ handle }) {
  const { t, lang, formatPrice, addToCart } = window.useStore();
  const product = MASKA_CATALOG.byHandle[handle];
  const [imgIdx, setImgIdx] = useStateP(0);
  const [variant, setVariant] = useStateP(product?.variants?.[0]?.title || null);
  const [qty, setQty] = useStateP(1);
  const [giftMsg, setGiftMsg] = useStateP("");

  useEffectP(() => { setImgIdx(0); setQty(1); setVariant(product?.variants?.[0]?.title || null); }, [handle]);

  if (!product) {
    return (
      <div className="shell" style={{padding:"120px 0", textAlign:"center"}}>
        <p>Product not found.</p>
        <a href="#/shop" className="btn-link" style={{marginTop: 20}}>{t("back_to_shop")} <Icon.arrow/></a>
      </div>
    );
  }

  const fp = formatPrice(product.price);
  const crossSell = MASKA_CATALOG.groups.wraps.filter(p => p.handle !== handle).slice(0, 4);

  return (
    <div data-screen-label="03 Product">
      <div className="shell">
        <div className="breadcrumb" style={{paddingTop: 24}}>
          <a href="#/">{lang === "ar" ? "الرئيسية" : "Home"}</a>
          <span className="sep">/</span>
          <a href="#/shop">{t("shop")}</a>
          <span className="sep">/</span> {product.title}
        </div>

        <div className="pdp">
          <div className="pdp-gallery">
            <div className="pdp-main-img"><img src={product.images[imgIdx]} alt={product.title}/></div>
            {product.images.length > 1 && (
              <div className="pdp-thumbs">
                {product.images.map((img, i) => (
                  <div key={i} className={"pdp-thumb " + (i === imgIdx ? "active" : "")} onClick={() => setImgIdx(i)}>
                    <img src={img} alt=""/>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="pdp-info">
            <div className="pdp-tags">
              {(product.tags || []).filter(t => !/website|maska/i.test(t)).slice(0, 4).map(t => <div key={t} className="pdp-tag-chip">{t}</div>)}
            </div>
            <h1 className="pdp-title">{product.title}</h1>
            <div className="pdp-price"><span className="ccy">{fp.ccy}</span>{fp.num}</div>

            {product.body && (
              <p className="pdp-desc">{product.body}</p>
            )}

            {product.variants && product.variants.length > 1 && (
              <div className="pdp-section">
                <h4>{t("variants_title")}</h4>
                <div className="variant-row">
                  {product.variants.map(v => (
                    <button key={v.title} className={"variant-pill " + (variant === v.title ? "active" : "")} onClick={() => setVariant(v.title)}>
                      {v.title}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="pdp-section">
              <h4>{t("gift_message")}</h4>
              <textarea className="pdp-gift-msg" placeholder={t("gift_message_placeholder")} value={giftMsg} onChange={e => setGiftMsg(e.target.value)}/>
            </div>

            <div className="pdp-add">
              <div className="qty-stepper">
                <button onClick={() => setQty(Math.max(1, qty - 1))}><Icon.minus/></button>
                <span>{qty}</span>
                <button onClick={() => setQty(qty + 1)}><Icon.plus/></button>
              </div>
              <button className="btn" onClick={() => addToCart(product, variant, qty)}>{t("add_to_bag")} · {fp.ccy} {(parseFloat(fp.num) * qty).toFixed(2)}</button>
            </div>

            <div style={{display:"flex", gap:24, marginTop:32, paddingTop:24, borderTop:"1px solid var(--line)", fontSize:12, color:"var(--ink-2)", flexWrap:"wrap"}}>
              <div style={{display:"flex", gap:8, alignItems:"center"}}><span style={{color:"var(--gold)"}}>↻</span> {t("reusable")}</div>
              <div style={{display:"flex", gap:8, alignItems:"center"}}><span style={{color:"var(--gold)"}}>✿</span> {t("handmade_in_dubai")}</div>
              <div style={{display:"flex", gap:8, alignItems:"center"}}><span style={{color:"var(--gold)"}}>★</span> {t("free_wrap_on_request")}</div>
            </div>
          </div>
        </div>
      </div>

      {/* Cross sell */}
      <section style={{padding:"80px 0", background:"var(--paper-2)"}}>
        <div className="shell">
          <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-end", marginBottom: 32, flexWrap:"wrap", gap:16}}>
            <div>
              <div className="eyebrow">― {lang === "ar" ? "أكمل الهدية" : "Complete the gift"}</div>
              <h2 style={{marginTop: 14, fontStyle:"italic", fontWeight: 300}}>{t("complete_the_gift")}</h2>
              <p style={{color:"var(--muted)", marginTop: 8}}>{t("cross_sell_sub")}</p>
            </div>
          </div>
          <div className="product-grid">
            {crossSell.map(p => <ProductCard key={p.handle} product={p}/>)}
          </div>
        </div>
      </section>
    </div>
  );
}
window.ProductPage = ProductPage;
