/* eslint-disable */
/* ProductPage — full-page PDP. Reads ?handle= from URL, fetches the product
   from Shopify (with mock fallback), renders gallery, variant pickers,
   accordions, sticky mobile ATC, and a related-products grid. */

function ProductPage() {
  const params = new URLSearchParams(window.location.search);
  // Clean URLs (/products/:handle) are server-rewritten to product.html with no
  // ?handle= on the client; fall back to parsing the path segment.
  const _seg = window.location.pathname.split("/").filter(Boolean);
  const handle = params.get("handle") || (_seg[0] === "products" && _seg[1] ? decodeURIComponent(_seg[1]) : null);
  const [product, setProduct] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [imgIdx, setImgIdx] = React.useState(0);
  const [selectedOptions, setSelectedOptions] = React.useState({});
  const [qty, setQty] = React.useState(1);
  const [openAcc, setOpenAcc] = React.useState("details");
  const [related, setRelated] = React.useState([]);

  React.useEffect(() => {
    let cancelled = false;
    const load = async () => {
      try {
        if (window.Shopify?.isConfigured?.() && handle) {
          const p = await window.Shopify.getProduct(handle);
          if (!cancelled && p) {
            setProduct(p);
            // Pre-select first option of each
            const sel = {};
            p.options.forEach(o => { sel[o.name] = o.values[0]; });
            setSelectedOptions(sel);
            setLoading(false);
            // Related: fall back to first 4 mock products
            setRelated((window.PRODUCTS || []).slice(0, 4));
            if (window.dropTrack) window.dropTrack("view_item", { id: p.id, name: p.name, price: p.price });
            return;
          }
        }
        // Mock fallback
        const mock = (window.PRODUCTS || [])[0];
        if (!cancelled && mock) {
          setProduct({...mock, images: [mock.img, "assets/hero-necklaces.jpg", "assets/banner-bundles.jpg", "assets/hero-mens.jpg"], variants: [{id: "mock-1", title: "Default", price: {amount: mock.price}, availableForSale: true}], options: []});
          setLoading(false);
          setRelated((window.PRODUCTS || []).slice(1, 5));
        }
      } catch (e) {
        if (!cancelled) setLoading(false);
      }
    };
    if (handle || (window.PRODUCTS || []).length) load(); else setLoading(false);
    return () => { cancelled = true; };
  }, [handle]);

  if (loading) {
    return (
      <main className="pdp">
        <div className="pdp-grid">
          <div className="pdp-gallery"><div className="pdp-main-img skel" style={{background:"var(--bg-2)"}}></div></div>
          <div className="pdp-info"><div className="skel-line" style={{width:"60%", height:"32px"}}></div><div className="skel-line" style={{width:"40%"}}></div></div>
        </div>
      </main>
    );
  }
  if (!product) {
    return (
      <main className="pdp">
        <div style={{textAlign:"center", padding:"80px 20px"}}>
          <h1 style={{fontFamily:"var(--font-display)", fontWeight:300}}>Piece not found</h1>
          <p>That product handle didn't match anything in our catalog.</p>
          <a className="btn-primary" href="collection.html?handle=womens">Shop Womens →</a>
        </div>
      </main>
    );
  }

  const matchVariant = () => {
    if (!product.variants || product.variants.length === 0) return null;
    if (product.options.length === 0) return product.variants[0];
    return product.variants.find(v =>
      v.selectedOptions?.every(o => selectedOptions[o.name] === o.value)
    ) || product.variants[0];
  };
  const variant = matchVariant();
  // Sold out when Shopify reports no purchasable inventory (product- or selected-
  // variant-level availableForSale=false). Gates the buy CTAs below.
  const soldOut = product.available === false || (variant && variant.availableForSale === false);
  const unitPrice = variant?.price?.amount ? parseFloat(variant.price.amount) : product.price;
  const total = (unitPrice * qty).toFixed(0);

  const onAdd = () => {
    window.Drop?.addToCart(product, qty, variant);
  };
  const onShopPay = async () => {
    if (variant?.id && window.Shopify?.isConfigured?.()) {
      // Authoritative set = the cart the shopper already has (drawer/localStorage)
      // plus this item. Reconcile so checkout bills exactly that — never stale
      // items left on the Shopify cart from an earlier session.
      let lines = [];
      try { lines = JSON.parse(localStorage.getItem("DROP_LOCAL_CART_V1") || "[]"); } catch (e) { lines = []; }
      lines = lines.map(i => ({ variantId: i.variantId || null, qty: i.qty, handle: i.handle }));
      const existing = lines.find(l => l.variantId === variant.id);
      if (existing) existing.qty += qty;
      else lines.push({ variantId: variant.id, qty, handle: product.handle });
      const url = await window.Shopify.cart.checkoutUrlFor(lines);
      if (url) { window.location.href = url; return; }
    }
    onAdd();
  };

  const acc = (key, label, body) => (
    <div className={"pdp-acc-row " + (openAcc === key ? "is-open" : "")} onClick={() => setOpenAcc(openAcc === key ? null : key)}>
      <div className="pdp-acc-h"><span>{label}</span><span>{openAcc === key ? "−" : "+"}</span></div>
      {openAcc === key && <div className="pdp-acc-body">{body}</div>}
    </div>
  );

  return (
    <React.Fragment>
      <main className="pdp">
        <div className="pdp-grid">
          {/* Gallery */}
          <div className="pdp-gallery">
            <div className="pdp-main-img" style={{backgroundImage:`url(${product.images?.[imgIdx] || product.img})`}}></div>
            {(product.images?.length > 1) && (
              <div className="pdp-thumbs">
                {product.images.map((src, i) => (
                  <div key={i} className={"pdp-thumb " + (i === imgIdx ? "is-active" : "")}
                    style={{backgroundImage:`url(${src})`}}
                    onClick={() => setImgIdx(i)} />
                ))}
              </div>
            )}
          </div>

          {/* Info */}
          <div className="pdp-info">
            <div className="crumb"><a href="index.html">Home</a> / <a href="collection.html?handle=women">Shop</a> / <span>{product.name}</span></div>
            <h1 className="pdp-name">{product.name}</h1>
            <div className="pdp-meta">{product.meta}</div>
            <div className="pdp-rating">
              <span className="stars">★★★★★</span>
              <span>4.9</span>
              <a className="muted-link">2,481 reviews</a>
            </div>

            <div className="pdp-price-row">
              {product.was && <span className="pdp-price was">${product.was}</span>}
              <span className="pdp-price">${unitPrice.toFixed(0)}</span>
              {product.was && <span className="pdp-save-pill">SAVE ${product.was - unitPrice}</span>}
            </div>
            <div className="pdp-pay-meta">or 4 interest-free payments of ${(unitPrice/4).toFixed(2)} with Shop Pay</div>

            {product.lowStock && (
              <div className="pdp-low">● Only {product.lowStock} left — selling fast</div>
            )}

            {product.options?.map(opt => (
              <div key={opt.name} className="pdp-opt">
                <div className="pdp-opt-h"><span>{opt.name}</span><em>{selectedOptions[opt.name]}</em></div>
                <div className="pdp-swatch-row">
                  {opt.values.map(v => (
                    <button key={v}
                      className={"pdp-swatch " + (selectedOptions[opt.name] === v ? "is-active" : "")}
                      onClick={() => setSelectedOptions(s => ({...s, [opt.name]: v}))}>
                      {v}
                    </button>
                  ))}
                </div>
              </div>
            ))}

            <div className="pdp-opt">
              <div className="pdp-opt-h"><span>Quantity</span></div>
              <div className="qty">
                <button onClick={() => setQty(Math.max(1, qty-1))}>−</button>
                <span>{qty}</span>
                <button onClick={() => setQty(qty+1)}>+</button>
              </div>
            </div>

            <div className="pdp-cta">
              {soldOut ? (
                <button className="btn-primary btn-block is-soldout" disabled>SOLD OUT</button>
              ) : (
                <>
                  <button className="btn-primary btn-block" onClick={onAdd}>
                    ADD TO BAG — ${total}
                  </button>
                  {window.DROP_CONFIG?.enableShopPay && (
                    <button className="shoppay" onClick={onShopPay}>Buy now with Shop Pay</button>
                  )}
                </>
              )}
            </div>

            <div className="pdp-trust">
              <div><strong>Free shipping</strong><span>over $75</span></div>
              <div><strong>30-day returns</strong><span>no questions</span></div>
              <div><strong>Tarnish-free</strong><span>or money back</span></div>
            </div>

            <div className="pdp-acc">
              {(product.description || "").trim() && acc("details", "Details & care", product.description)}
              {acc("ship", "Shipping & returns", "Ships within 1–2 business days. Free shipping on orders over $75. Returns accepted within 30 days, unworn, in original packaging.")}
              {acc("size", "Size guide", "All necklaces are 16\" with a 2\" extender. Bracelets are 6.5\" with a 1\" extender. Rings run true to size — check the size guide for fit notes.")}
              {acc("reviews", "Reviews (2,481)", "Average rating 4.9. Most-helpful: \"Wore it to the beach all summer — zero tarnish. Best chain I own.\"")}
            </div>
          </div>
        </div>
      </main>

      {/* Sticky mobile ATC */}
      <div className="pdp-sticky-atc">
        <button className="btn-primary" onClick={onAdd}>ADD — ${total}</button>
      </div>

      {/* Related */}
      <section className="pdp-related">
        <h3>You might also love</h3>
        <div className="pdp-related-grid">
          {related.map(p => (
            <ProductCard key={p.id || p.handle} p={p}
              onAdd={() => window.Drop?.addToCart(p)}
              onClick={() => p.handle ? window.location.href = "product.html?handle=" + p.handle : window.Drop?.openProduct(p)} />
          ))}
        </div>
      </section>
    </React.Fragment>
  );
}
window.ProductPage = ProductPage;
