// pages-shop.jsx — catalog, detail, cart, checkout success
const { useEffect: shUseEffect, useRef: shUseRef, useState: shUseState, useMemo: shUseMemo } = React;
const { ScriptCard: ShopCard } = window.HomeSections;

// ---------- Catalog ----------
function Catalog({ onOpen }) {
  const [scripts, setScripts] = shUseState(() => window.AppData.getScripts());
  const [filter, setFilter] = shUseState(() => {
    try {
      const f = sessionStorage.getItem("pa_filter");
      sessionStorage.removeItem("pa_filter");
      if (f && ["All", "AE", "Blender", "UE5"].includes(f)) return f;
    } catch (e) {}
    return "All";
  });
  const [sort, setSort] = shUseState("popular");
  const titleRef = shUseRef(null);

  shUseEffect(() => {
    const upd = () => setScripts(window.AppData.getScripts());
    window.addEventListener("pa:scripts", upd);
    return () => window.removeEventListener("pa:scripts", upd);
  }, []);

  shUseEffect(() => {
    if (!window.gsap || !titleRef.current) return;
    window.ScrollFX.splitText(titleRef.current.querySelector("[data-split]"));
    const chars = titleRef.current.querySelectorAll(".split-char");
    window.gsap.set(chars, { yPercent: 110, opacity: 0 });
    window.gsap.to(chars, { yPercent: 0, opacity: 1, duration: 1.1, ease: "power4.out", stagger: { each: 0.02, from: "random" } });
  }, []);

  const cats = ["All", "AE", "Blender", "UE5"];
  const filtered = shUseMemo(() => {
    let r = scripts.slice();
    if (filter !== "All") r = r.filter(s => s.software === filter);
    if (sort === "popular") r.sort((a, b) => b.downloads - a.downloads);
    if (sort === "price-low") r.sort((a, b) => a.price - b.price);
    if (sort === "price-high") r.sort((a, b) => b.price - a.price);
    return r;
  }, [scripts, filter, sort]);

  return (
    <main className="page-enter">
      <section className="catalog">
        <div className="wrap">
          <div className="catalog__head">
            <h1 ref={titleRef}><span data-split>Index of scripts</span></h1>
            <p style={{maxWidth:"360px", color:"var(--fg-2)", fontSize:"14px", lineHeight:1.65}}>
              {filtered.length} releases across After Effects, Blender and Unreal. Every script ships with source, presets, README and a year of patches on its major version.
            </p>
          </div>
          <div className="catalog__filters">
            {cats.map(c => (
              <button key={c} className={`chip ${filter === c ? "is-active" : ""}`} onClick={() => setFilter(c)} data-cursor="button">{c === "All" ? "All software" : c}</button>
            ))}
            <span style={{width:"1px", height:"22px", background:"var(--line-2)", margin:"0 8px"}}></span>
            <button className={`chip ${sort === "popular" ? "is-active" : ""}`} onClick={() => setSort("popular")} data-cursor="button">Popular</button>
            <button className={`chip ${sort === "price-low" ? "is-active" : ""}`} onClick={() => setSort("price-low")} data-cursor="button">Price ↑</button>
            <button className={`chip ${sort === "price-high" ? "is-active" : ""}`} onClick={() => setSort("price-high")} data-cursor="button">Price ↓</button>
            <span className="catalog__count">{filtered.length} / {scripts.length}</span>
          </div>
          <div className="catalog__grid">
            {filtered.map(s => <ShopCard key={s.id} s={s} onOpen={onOpen} />)}
          </div>
        </div>
      </section>
    </main>
  );
}

// ---------- Detail ----------
function Detail({ id, onGo, openAuth }) {
  const scripts = window.AppData.getScripts();
  const s = scripts.find(x => x.id === id);
  const mediaRef = shUseRef(null);
  const [activeImg, setActiveImg] = shUseState(0);
  const [inCart, setInCart] = shUseState(() => !!window.AppData.getCart().find(x => x.id === id));

  shUseEffect(() => {
    const upd = () => setInCart(!!window.AppData.getCart().find(x => x.id === id));
    window.addEventListener("pa:cart", upd);
    return () => window.removeEventListener("pa:cart", upd);
  }, [id]);

  shUseEffect(() => {
    if (!window.gsap || !mediaRef.current) return;
    // clip-path reveal of the media
    window.gsap.fromTo(mediaRef.current, { clipPath: "inset(0 100% 0 0)" }, { clipPath: "inset(0 0% 0 0)", duration: 1.2, ease: "power4.out" });
  }, [id]);

  if (!s) return (
    <main className="wrap" style={{padding:"160px 0", textAlign:"center"}}>
      <h1 className="display" style={{fontSize:"64px"}}>Not found.</h1>
      <a href="#/scripts" className="btn" style={{marginTop:"32px"}} onClick={(e)=>{e.preventDefault(); onGo("/scripts");}}>Back to catalog</a>
    </main>
  );

  const palettes = window.AppData.PALETTES;
  const p = palettes[s.palette % palettes.length];
  const galleryColors = [p[0], p[1], p[2], "#ffffff", "#1a1a1a"];

  const onAdd = () => {
    if (inCart) onGo("/cart");
    else { window.AppData.addToCart(s.id); }
  };
  const onBuyNow = () => {
    if (!window.AppData.currentUser()) { openAuth("/cart"); return; }
    window.AppData.addToCart(s.id);
    onGo("/cart");
  };

  return (
    <main className="page-enter">
      <section className="detail wrap">
        <a href="#/scripts" className="detail__back" onClick={(e)=>{e.preventDefault(); onGo("/scripts");}}>← All scripts</a>
        <div className="detail__grid">
          <div>
            <div className="detail__media" ref={mediaRef}>
              <div className="grid-overlay"></div>
              <div className="blob" style={{
                background: `radial-gradient(circle at 30% 30%, ${galleryColors[activeImg]} 0%, transparent 60%), radial-gradient(circle at 70% 70%, ${p[(activeImg+1)%3]} 0%, transparent 60%)`,
                animation: "blobShift 14s ease-in-out infinite alternate"
              }}></div>
              <style>{`@keyframes blobShift { 0% { transform: scale(1) translate(0,0); } 100% { transform: scale(1.15) translate(-4%,4%); } }`}</style>
              <div style={{position:"absolute", top:"24px", left:"24px", fontSize:"11px", letterSpacing:"0.18em", textTransform:"uppercase", color:"var(--fg)", zIndex:2}}>
                <span style={{display:"inline-block", padding:"4px 10px", background:"rgba(10,10,10,0.6)", border:"1px solid var(--line-2)", borderRadius:"999px", backdropFilter:"blur(8px)"}}>Preview · {activeImg + 1} / 5</span>
              </div>
              <div style={{position:"absolute", bottom:"24px", right:"24px", fontFamily:"Clash Display", fontSize:"96px", lineHeight:1, color:"var(--fg)", opacity:0.6, zIndex:2}}>
                {String(scripts.findIndex(x=>x.id===s.id)+1).padStart(2,"0")}
              </div>
            </div>
            <div style={{display:"grid", gridTemplateColumns:"repeat(5, 1fr)", gap:"4px", marginTop:"4px"}}>
              {galleryColors.map((c, i) => (
                <button key={i} onClick={() => setActiveImg(i)} data-cursor="ring" data-cursor-label="View" style={{
                  aspectRatio:"1/1", background: `radial-gradient(circle at 50% 50%, ${c} 0%, ${p[(i+1)%3]} 70%, var(--bg-2) 100%)`,
                  filter:"blur(0.5px)", border: activeImg === i ? "2px solid var(--accent)" : "1px solid var(--line-2)",
                  borderRadius:"2px", cursor:"none"
                }}></button>
              ))}
            </div>
          </div>
          <div>
            <div className="detail__tag-row">
              <span className="script-card__tag" style={{position:"static"}}>{s.software}</span>
              <span className="script-card__tag" style={{position:"static"}}>{s.category}</span>
              <span className="script-card__tag" style={{position:"static"}}>v{s.version}</span>
            </div>
            <h1 className="detail__title">{s.title}</h1>
            <p className="detail__lead">{s.summary}</p>
            <div className="detail__specs">
              <div className="detail__spec"><span>Compatibility</span><span>{s.compatibility}</span></div>
              <div className="detail__spec"><span>File size</span><span>{s.fileSize}</span></div>
              <div className="detail__spec"><span>Version</span><span>v{s.version}</span></div>
              <div className="detail__spec"><span>Downloads</span><span>{s.downloads.toLocaleString()}</span></div>
              <div className="detail__spec"><span>Rating</span><span>{s.rating.toFixed(1)} ★ / 5.0</span></div>
              <div className="detail__spec"><span>Licence</span><span>Commercial up to $1M / yr</span></div>
            </div>
            <div className="detail__price-row">
              <div>
                <div className="detail__price"><span className="currency">$</span>{s.price}</div>
                <div className="detail__price-meta">One-time · lifetime patches</div>
              </div>
              <div style={{textAlign:"right"}}>
                <div style={{fontSize:"11px", color:"var(--fg-3)", letterSpacing:"0.1em", textTransform:"uppercase"}}>or unlock all</div>
                <a href="#/membership" style={{color:"var(--accent)", fontSize:"13px", letterSpacing:"0.08em", textTransform:"uppercase"}} onClick={(e)=>{e.preventDefault(); onGo("/membership");}}>Membership →</a>
              </div>
            </div>
            <div className="detail__actions">
              <button className="magnetic" data-magnetic data-cursor="button" onClick={onAdd}>
                <span className="btn btn--ghost btn--block magnetic-inner">{inCart ? "In cart — view" : "Add to cart"}</span>
              </button>
              <button className="magnetic" data-magnetic data-cursor="button" onClick={onBuyNow}>
                <span className="btn btn--block magnetic-inner"><span>Buy now</span><span className="btn__arrow">→</span></span>
              </button>
            </div>
            <div style={{marginTop:"40px", padding:"20px 24px", background:"var(--bg-2)", display:"flex", gap:"20px", flexWrap:"wrap", fontSize:"12px", letterSpacing:"0.08em", color:"var(--fg-2)", textTransform:"uppercase"}}>
              <span>↘ Includes</span>
              <span style={{color:"var(--fg)"}}>Source ZIP</span>
              <span style={{color:"var(--fg)"}}>README.md</span>
              <span style={{color:"var(--fg)"}}>5× Preview</span>
              <span style={{color:"var(--fg)"}}>Walkthrough Video</span>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ---------- Cart ----------
function Cart({ onGo, openAuth }) {
  const [cart, setCart] = shUseState(() => window.AppData.getCart());
  const [code, setCode] = shUseState("");
  const [discount, setDiscount] = shUseState(0);

  shUseEffect(() => {
    const upd = () => setCart(window.AppData.getCart());
    window.addEventListener("pa:cart", upd);
    return () => window.removeEventListener("pa:cart", upd);
  }, []);

  const scripts = window.AppData.getScripts();
  const items = cart.map(c => ({ ...scripts.find(s => s.id === c.id), qty: c.qty })).filter(x => x.id);
  const subtotal = items.reduce((a, b) => a + b.price * b.qty, 0);
  const tax = Math.round(subtotal * 0.1 * 100) / 100;
  const total = Math.max(0, subtotal + tax - discount);

  const applyCode = () => {
    if (code.trim().toUpperCase() === "STUDIO10") { setDiscount(Math.round(subtotal * 0.1 * 100) / 100); }
    else if (code.trim().toUpperCase() === "AWWWARDS") { setDiscount(20); }
    else { setDiscount(0); }
  };

  const checkout = () => {
    if (!window.AppData.currentUser()) { openAuth("/cart"); return; }
    window.AppData.placeOrder(items.map(i => ({ id: i.id, title: i.title, price: i.price, qty: i.qty })), total);
    onGo("/success");
  };

  if (!items.length) {
    return (
      <main className="page-enter">
        <section className="cart wrap">
          <h1>Your cart is empty.</h1>
          <div className="cart__empty">Add a script to get started.</div>
          <a className="btn magnetic-inner" href="#/scripts" data-cursor="button" onClick={(e)=>{e.preventDefault(); onGo("/scripts");}}>Browse scripts →</a>
        </section>
      </main>
    );
  }

  return (
    <main className="page-enter">
      <section className="cart wrap">
        <h1>Cart · <em style={{fontStyle:"normal", color:"var(--fg-3)"}}>{items.length} {items.length === 1 ? "item" : "items"}</em></h1>
        <div className="cart__layout">
          <div className="cart__list">
            {items.map(it => {
              const p = window.AppData.PALETTES[it.palette % window.AppData.PALETTES.length];
              return (
                <div className="cart__item" key={it.id}>
                  <div className="cart__item-thumb">
                    <div className="blob" style={{background:`radial-gradient(circle at 30% 30%, ${p[0]} 0%, transparent 60%), radial-gradient(circle at 70% 70%, ${p[1]} 0%, transparent 60%)`}}></div>
                  </div>
                  <div>
                    <div className="cart__item-title">{it.title}</div>
                    <div className="cart__item-meta">{it.software} · v{it.version} · {it.fileSize}</div>
                  </div>
                  <div className="cart__qty">
                    <button onClick={() => window.AppData.setCartQty(it.id, it.qty - 1)} data-cursor="button">−</button>
                    <span>{it.qty}</span>
                    <button onClick={() => window.AppData.setCartQty(it.id, it.qty + 1)} data-cursor="button">+</button>
                  </div>
                  <div style={{fontFamily:"Clash Display", fontSize:"22px", fontWeight:500, minWidth:"80px", textAlign:"right"}}>${it.price * it.qty}</div>
                  <button className="cart__remove" onClick={() => window.AppData.removeFromCart(it.id)} data-cursor="button">Remove</button>
                </div>
              );
            })}
          </div>
          <aside className="cart__summary">
            <h3>Order summary</h3>
            <div className="cart__summary-row"><span>Subtotal</span><span style={{color:"var(--fg)"}}>${subtotal.toFixed(2)}</span></div>
            <div className="cart__summary-row"><span>Tax (10%)</span><span style={{color:"var(--fg)"}}>${tax.toFixed(2)}</span></div>
            {discount > 0 && <div className="cart__summary-row"><span>Discount</span><span style={{color:"var(--accent)"}}>−${discount.toFixed(2)}</span></div>}
            <div className="cart__discount">
              <input value={code} onChange={e => setCode(e.target.value)} placeholder="Promo code (try STUDIO10)" />
              <button className="btn btn--ghost" style={{padding:"14px 18px"}} onClick={applyCode} data-cursor="button">Apply</button>
            </div>
            <div className="cart__summary-total"><span>Total</span><span>${total.toFixed(2)}</span></div>
            <button className="magnetic" data-magnetic style={{display:"block", marginTop:"24px"}} onClick={checkout} data-cursor="button">
              <span className="btn btn--block magnetic-inner"><span>Checkout</span><span className="btn__arrow">→</span></span>
            </button>
            <p style={{marginTop:"20px", fontSize:"12px", color:"var(--fg-3)", lineHeight:1.5}}>
              Members save 100% on all scripts. <a href="#/membership" style={{color:"var(--accent)"}} onClick={(e)=>{e.preventDefault(); onGo("/membership");}}>Join membership →</a>
            </p>
          </aside>
        </div>
      </section>
    </main>
  );
}

// ---------- Checkout success ----------
function Success({ onGo }) {
  shUseEffect(() => {
    if (!window.gsap) return;
    window.gsap.from(".success > *", { opacity: 0, y: 30, duration: 0.9, ease: "power3.out", stagger: 0.1 });
  }, []);
  return (
    <main className="page-enter">
      <section className="success">
        <div className="check">✓</div>
        <h1>Thank you.</h1>
        <p className="sub">Your order has been placed. Download links are now in your account.</p>
        <div style={{display:"flex", gap:"12px"}}>
          <a className="btn" href="#/account" data-cursor="button" onClick={(e)=>{e.preventDefault(); onGo("/account");}}>Go to account</a>
          <a className="btn btn--ghost" href="#/scripts" data-cursor="button" onClick={(e)=>{e.preventDefault(); onGo("/scripts");}}>Keep browsing</a>
        </div>
      </section>
    </main>
  );
}

window.ShopPages = { Catalog, Detail, Cart, Success };
