/* eslint-disable */
/* CollectionPage — parametric PLP. Reads ?handle= from URL, fetches the
   collection from Shopify (with the bundled mock catalog as fallback),
   then renders sub-tab chips, sort, filters, and a responsive product grid. */

// Sub-tab chips for each REAL Shopify collection handle. Each chip is a
// tag-filter against the same parent handle (using ?filter=<tag>) — drives
// real Storefront API filter queries against the tags we wrote on the catalog.
const tab = (label, handle, filter) => [label, handle, filter || null];
const SUBTAB_MAP = {
  // Top-level catalog (women-led)
  "shop-all":   [tab("All","shop-all"), tab("Necklaces","necklaces"), tab("Earrings","earrings"), tab("Bracelets","bracelets"), tab("Rings","rings"), tab("Sale","sale"), tab("New","new-arrivals")],
  // Womens — same data as shop-all (women-led catalog) but presented as "Womens"
  womens:       [tab("All","womens"), tab("Necklaces","necklaces"), tab("Earrings","earrings"), tab("Bracelets","bracelets"), tab("Rings","rings"), tab("Sale","sale"), tab("New","new-arrivals")],
  // Per-category, chips become tag filters on the same collection. Sub-cat
  // taxonomy reflects what's actually in the catalog (audit 2026-05-07) —
  // empty styles like Choker/Lariat/Curb/Figaro/Cuff/Tennis/Anklet/Signet
  // are deliberately omitted until the catalog grows.
  necklaces:    [tab("All","necklaces"), tab("Chains","necklaces","Chain"), tab("Pendants","necklaces","Pendant"), tab("Cuban","necklaces","Cuban"), tab("Charms","necklaces","Charm"), tab("Snake","necklaces","Snake")],
  earrings:     [tab("All","earrings"), tab("Hoops","earrings","Hoops"), tab("Studs","earrings","Studs"), tab("Huggies","earrings","Huggies"), tab("Drops","earrings","Drops")],
  bracelets:    [tab("All","bracelets"), tab("Charm","bracelets","Charm"), tab("Chains","bracelets","Chain"), tab("Cuban","bracelets","Cuban"), tab("Pearl","bracelets","Pearl"), tab("Watch","bracelets","Watch")],
  rings:        [tab("All","rings"), tab("Bands","rings","Band"), tab("Stacking","rings","Stacking"), tab("Statement","rings","Statement")],
  // Men's catalog
  mens:         [tab("All","mens"), tab("Chains","mens","Chain"), tab("Cuban","mens","Cuban"), tab("Bracelets","mens","Bracelets"), tab("Rings","mens","Rings"), tab("Apparel","mens","Apparel")],
  // Kids
  "kids-apparel": [tab("All","kids-apparel"), tab("Tees","kids-apparel","Tee"), tab("Hoodies","kids-apparel","Hoodie"), tab("Hats","kids-apparel","Hat")],
  hats:         [tab("All","hats"), tab("Tees","hats","Tee"), tab("Hoodies","hats","Hoodie"), tab("Hats","hats","Hat")],
  // Sale + new — show category breakdown
  sale:         [tab("All","sale"), tab("Necklaces","sale","Necklaces"), tab("Earrings","sale","Earrings"), tab("Bracelets","sale","Bracelets"), tab("Rings","sale","Rings")],
  "new-arrivals": [tab("All","new-arrivals"), tab("Necklaces","new-arrivals","Necklaces"), tab("Earrings","new-arrivals","Earrings"), tab("Bracelets","new-arrivals","Bracelets"), tab("Rings","new-arrivals","Rings")],
  bundles:      [tab("All","bundles"), tab("Necklaces","bundles","Necklaces"), tab("Sets","bundles","Sets")],
};

function findSubtabRow(handle) {
  if (SUBTAB_MAP[handle]) return { row: SUBTAB_MAP[handle], parentLabel: titleFor(handle) };
  // Walk up parent: necklaces-chains -> necklaces
  const parts = handle.split("-");
  while (parts.length > 1) {
    parts.pop();
    const p = parts.join("-");
    if (SUBTAB_MAP[p]) return { row: SUBTAB_MAP[p], parentLabel: titleFor(p) };
  }
  return null;
}

const subtabHref = (h, f) => "collection.html?handle=" + h + (f ? "&filter=" + encodeURIComponent(f) : "");

// Aliases applied at fetch time only — URL handle stays "womens"/"mens" so the
// breadcrumb + title read as the line, not the underlying Shopify collection.
const FETCH_ALIAS = { womens: "shop-all", mens: "mens" };
const TITLE_OVERRIDE = { womens: "Womens", mens: "Mens", "kids-apparel": "Kids" };
// Gender-narrow when the URL handle is a line page. shop-all is the full
// catalog (women + unisex + mens), so the womens line filters to Women-tagged
// products only — without this, mens chains/rings bleed into Womens.
const GENDER_FILTER = { womens: "Women", mens: "Men", "kids-apparel": "Kids" };

function titleFor(h) {
  if (TITLE_OVERRIDE[h]) return TITLE_OVERRIDE[h];
  return h.split("-").map(w => w[0]?.toUpperCase() + w.slice(1)).join(" ");
}

function heroFor(handle) {
  if (handle.startsWith("men")) return "assets/hero-mens.jpg";
  if (handle.startsWith("kids")) return "assets/banner-bundles.jpg";
  if (handle.includes("apparel")) return "assets/banner-apparel.jpg";
  if (handle.includes("ring")) return "assets/product-amelia-ring.jpg";
  if (handle.includes("necklace")) return "assets/hero-necklaces.jpg";
  return "assets/hero-main.jpg";
}

const SORT_OPTIONS = [
  ["Best selling", "BEST_SELLING", false],
  ["Newest", "CREATED", true],
  ["Price: low to high", "PRICE", false],
  ["Price: high to low", "PRICE", true],
  ["Top rated", "RELEVANCE", false],
];

// Filter rail groups. The keys are mostly tag-equality matches against the
// catalog tags written by drop-catalog-writer; "price" buckets against the
// product price; "subcat" surfaces the relevant sub-types per parent handle.
const FILTER_GROUPS_BASE = {
  metal:    ["Gold", "Silver", "Rose Gold"],
  feature:  ["Waterproof", "Hypoallergenic", "Tarnish-free"],
  price:    ["Under $25", "Under $50", "Under $75", "Under $100"],
};
// Per-parent subcategory chips (matches the tags we wrote)
const SUBCAT_BY_PARENT = {
  necklaces: ["Chain", "Pendant", "Cuban", "Snake", "Charm", "Miami", "Rope"],
  earrings:  ["Hoops", "Studs", "Huggies", "Drops"],
  bracelets: ["Charm", "Chain", "Cuban", "Pearl", "Watch"],
  rings:     ["Band", "Stacking", "Statement"],
  mens:      ["Chain", "Cuban", "Bracelets", "Rings", "Apparel"],
  "kids-apparel": ["Tee", "Hoodie", "Hat"],
  hats:      ["Tee", "Hoodie", "Hat"],
};

function CollectionPage() {
  const params = new URLSearchParams(window.location.search);
  const handle = params.get("handle") || "shop-all";
  const urlFilter = params.get("filter") || "";  // tag-filter from mega-menu sub-tabs
  const [collection, setCollection] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [sortIdx, setSortIdx] = React.useState(0);
  const [filters, setFilters] = React.useState(() => urlFilter ? { tag: [urlFilter] } : {});
  const [filterOpen, setFilterOpen] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    setLoading(true);
    const sort = SORT_OPTIONS[sortIdx];
    const fetchHandle = FETCH_ALIAS[handle] || handle;
    const fetchCol = async () => {
      try {
        if (window.Shopify?.isConfigured?.()) {
          // Pull the full collection up front (default first=100) — all
          // tag/category/metal/feature/price filtering happens client-side
          // because Storefront API filters require Search & Discovery setup.
          const c = await window.Shopify.getCollection(fetchHandle, { sortKey: sort[1], reverse: sort[2] });
          if (!cancelled && c) {
            setCollection(c); setLoading(false); return;
          }
        }
        const mock = { handle, title: titleFor(handle), description: "", image: heroFor(handle), products: window.PRODUCTS || [] };
        if (!cancelled) { setCollection(mock); setLoading(false); }
      } catch (e) {
        if (!cancelled) {
          setError(e.message);
          setCollection({ handle, title: titleFor(handle), description: "", image: heroFor(handle), products: window.PRODUCTS || [] });
          setLoading(false);
        }
      }
    };
    fetchCol();
    return () => { cancelled = true; };
  }, [handle, sortIdx]);

  React.useEffect(() => {
    if (window.dropTrack) window.dropTrack("view_collection", { handle });
  }, [handle]);

  const subtabInfo = findSubtabRow(handle);
  const heroImg = collection?.image || heroFor(handle);
  // TITLE_OVERRIDE wins over Shopify's collection title (e.g. land /handle=womens
  // on shop-all data but still display "Womens" in the breadcrumb + h1).
  const displayTitle = TITLE_OVERRIDE[handle] || collection?.title || titleFor(handle);

  // Client-side filtering. Storefront API's `filters: [ProductFilter]` is
  // silently ignored unless the collection has Search & Discovery filter
  // configuration set up — which it doesn't on skinbymic. So everything
  // (subtab tag, sub-category, metal, feature, price) filters here.
  const products = (collection?.products || []).filter(p => {
    const f = filters;
    const tagSet = new Set((p.tags || []).map(t => t.toLowerCase()));
    const genderTag = GENDER_FILTER[handle];
    if (genderTag && !tagSet.has(genderTag.toLowerCase())) return false;
    if (urlFilter && !tagSet.has(urlFilter.toLowerCase())) return false;
    if (f.subcat?.length  && !f.subcat.every(x  => tagSet.has(x.toLowerCase()))) return false;
    if (f.metal?.length   && !f.metal.every(x   => tagSet.has(x.toLowerCase()))) return false;
    if (f.feature?.length && !f.feature.every(x => tagSet.has(x.toLowerCase()))) return false;
    if (f.price?.length) {
      const ok = f.price.some(b => {
        const m = b.match(/Under \$(\d+)/);
        return m ? p.price < Number(m[1]) : true;
      });
      if (!ok) return false;
    }
    return true;
  });

  const toggleFilter = (group, val) => {
    setFilters(f => {
      const cur = f[group] || [];
      const next = cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val];
      return { ...f, [group]: next };
    });
  };
  const clearFilters = () => setFilters({});
  const activeFilterCount = Object.values(filters).flat().length;

  return (
    <main className="plp">
      {/* Hero band */}
      <section className="plp-hero">
        <div className="plp-hero-img" style={{backgroundImage:`url(${heroImg})`}}></div>
        <div className="plp-hero-text">
          <div className="plp-crumb">
            <a href="index.html">Home</a> <span>/</span> <span>{displayTitle}</span>
          </div>
          <h1 className="plp-title">{displayTitle}</h1>
          {collection?.description && <p className="plp-desc">{collection.description}</p>}
        </div>
      </section>

      {/* Sub-tab chips — drive ?filter= against the same parent collection. */}
      {subtabInfo && (
        <nav className="plp-subtabs" aria-label="Sub-categories">
          <div className="plp-subtabs-inner">
            {subtabInfo.row.map(([label, h, f]) => {
              const isActive = h === handle && (f || null) === (urlFilter || null);
              return (
                <a key={label + h + (f||"")}
                   href={subtabHref(h, f)}
                   className={"subtab " + (isActive ? "is-active" : "")}
                   aria-current={isActive ? "page" : undefined}>
                  {label}
                </a>
              );
            })}
          </div>
        </nav>
      )}

      {/* Toolbar */}
      <div className="plp-toolbar">
        <button className="plp-filter-toggle" onClick={() => setFilterOpen(o => !o)}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="14" y2="12"/><line x1="4" y1="18" x2="9" y2="18"/></svg>
          <span>Filter{activeFilterCount > 0 ? ` (${activeFilterCount})` : ""}</span>
        </button>
        <div className="plp-count">{products.length} {products.length === 1 ? "piece" : "pieces"}</div>
        <div className="plp-sort">
          <label>Sort</label>
          <select value={sortIdx} onChange={e => setSortIdx(Number(e.target.value))}>
            {SORT_OPTIONS.map((o, i) => <option key={i} value={i}>{o[0]}</option>)}
          </select>
        </div>
      </div>

      {/* Active filter chips */}
      {activeFilterCount > 0 && (
        <div className="plp-active-filters">
          {Object.entries(filters).flatMap(([g, vals]) => vals.map(v => (
            <button key={g+v} className="active-chip" onClick={() => toggleFilter(g, v)}>
              {v} <span>×</span>
            </button>
          )))}
          <button className="clear-all" onClick={clearFilters}>Clear all</button>
        </div>
      )}

      <div className={"plp-body " + (filterOpen ? "filters-open" : "")}>
        {/* Filter rail */}
        <aside className="plp-rail">
          {/* Mobile filter sheet header (only renders inside the open sheet) */}
          <div className="plp-rail-mobile-head">
            <span className="filter-h" style={{margin:0, fontSize:14}}>Filters</span>
            <button className="plp-rail-close" onClick={() => setFilterOpen(false)} aria-label="Close filters">×</button>
          </div>
          {SUBCAT_BY_PARENT[handle] && (
            <div className="filter-group">
              <div className="filter-h">Sub-category</div>
              {SUBCAT_BY_PARENT[handle].map(opt => (
                <label key={opt} className={"filter-opt " + ((filters.subcat || []).includes(opt) ? "is-on" : "")}>
                  <input type="checkbox" checked={(filters.subcat || []).includes(opt)} onChange={() => toggleFilter("subcat", opt)} />
                  <span>{opt}</span>
                </label>
              ))}
            </div>
          )}
          {Object.entries(FILTER_GROUPS_BASE).map(([group, opts]) => (
            <div key={group} className="filter-group">
              <div className="filter-h">{group[0].toUpperCase() + group.slice(1)}</div>
              {opts.map(opt => (
                <label key={opt} className={"filter-opt " + ((filters[group] || []).includes(opt) ? "is-on" : "")}>
                  <input type="checkbox" checked={(filters[group] || []).includes(opt)} onChange={() => toggleFilter(group, opt)} />
                  <span>{opt}</span>
                </label>
              ))}
            </div>
          ))}
          {/* Mobile sheet footer */}
          <div className="plp-rail-mobile-foot">
            <button className="btn-secondary" onClick={clearFilters}>Clear all</button>
            <button className="btn-primary" onClick={() => setFilterOpen(false)}>Show {products.length}</button>
          </div>
        </aside>

        {/* Grid */}
        <section className="plp-grid">
          {loading && Array(8).fill(0).map((_, i) => <div key={i} className="pcard skel"><div className="pcard-img"></div><div className="pcard-meta"><div className="skel-line"></div><div className="skel-line short"></div></div></div>)}
          {!loading && products.length === 0 && (
            <div className="plp-empty">
              <h3>Nothing matches yet.</h3>
              <p>Try clearing filters or <a href="collection.html?handle=shop-all">browse bestsellers</a>.</p>
              <button className="btn-primary" onClick={clearFilters}>Clear filters</button>
            </div>
          )}
          {!loading && products.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)} />
          ))}
        </section>
      </div>

      {/* USP belt */}
      <section className="plp-usp">
        <div><strong>Free shipping $75+</strong><span>Fast US delivery</span></div>
        <div><strong>30-day returns</strong><span>No questions asked</span></div>
        <div><strong>★ 4.9 / 5</strong><span>50,000+ reviews</span></div>
        <div><strong>VIP texts</strong><span>20% off your first order</span></div>
      </section>

      {/* Editorial cross-link strip */}
      <section className="plp-edit">
        <div className="plp-edit-text">
          <div className="eyebrow">NEED HELP DECIDING?</div>
          <h3>Let our <em>AI Stylist</em> curate your look in 30 seconds.</h3>
          <button className="btn-primary" onClick={() => window.Drop?.openAI()}>FIND YOUR LOOK →</button>
        </div>
        <div className="plp-edit-img" style={{backgroundImage: "url('assets/hero-main.jpg')"}}></div>
      </section>
    </main>
  );
}
window.CollectionPage = CollectionPage;
