/* global React, PRODUCTS, CATEGORIES, COLLECTIONS, PALETTES, makePattern, ProductCard, PH */
const { useState: useStateC, useMemo: useMemoC } = React;

// ─── Catalog page ────────────────────────────────────────────────
function Catalog({ route, navigate }) {
  const cat = route.category || "all";
  const catMeta = CATEGORIES.find((c) => c.id === cat);

  const baseProducts = useMemoC(() => {
    if (cat === "all" || !catMeta) return PRODUCTS;
    return PRODUCTS.filter((p) => p.category === cat);
  }, [cat]);

  const collections = useMemoC(() => {
    const s = new Set(baseProducts.map((p) => p.collection).filter(Boolean));
    return [...s];
  }, [baseProducts]);

  const palettes = useMemoC(() => {
    const s = new Set(baseProducts.map((p) => p.palette));
    return [...s];
  }, [baseProducts]);

  const [collec, setCollec] = useStateC("all");
  const [palette, setPalette] = useStateC("all");
  const [sort, setSort] = useStateC("default");

  const products = useMemoC(() => {
    let r = baseProducts;
    if (collec !== "all") r = r.filter((p) => p.collection === collec);
    if (palette !== "all") r = r.filter((p) => p.palette === palette);
    if (sort === "price-asc") r = [...r].sort((a, b) => Math.min(...a.sizes.map((s) => s.price)) - Math.min(...b.sizes.map((s) => s.price)));
    if (sort === "price-desc") r = [...r].sort((a, b) => Math.min(...b.sizes.map((s) => s.price)) - Math.min(...a.sizes.map((s) => s.price)));
    return r;
  }, [baseProducts, collec, palette, sort]);

  const title = cat === "all" ? "Tout le catalogue" : (catMeta ? catMeta.label : "Catalogue");
  const lead = cat === "all" ? "Toute la collection — nappes, linge, accessoires." : (catMeta ? catMeta.lead : "");

  return (
    <div className="wrap">
      <div className="catalog-head">
        <div className="crumbs">
          <a onClick={() => navigate({ page: "home" })} style={{ cursor: "pointer" }}>Accueil</a>
          <span> / </span>
          <span>{title}</span>
        </div>
        <h1>{title}</h1>
        <p style={{ color: "var(--ink-2)", fontSize: 17, maxWidth: 560, margin: 0 }}>{lead}</p>
      </div>

      <div className="catalog-toolbar">
        <div className="filters">
          {collections.length > 1 && (
            <select value={collec} onChange={(e) => setCollec(e.target.value)}>
              <option value="all">Collection — toutes</option>
              {collections.map((c) => <option key={c} value={c}>Collection {c}</option>)}
            </select>
          )}
          {palettes.length > 1 && (
            <select value={palette} onChange={(e) => setPalette(e.target.value)}>
              <option value="all">Couleur — toutes</option>
              {palettes.map((p) => <option key={p} value={p}>{paletteLabel(p)}</option>)}
            </select>
          )}
          <select value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="default">Tri — sélection</option>
            <option value="price-asc">Prix croissant</option>
            <option value="price-desc">Prix décroissant</option>
          </select>
        </div>
        <div>{products.length} {products.length > 1 ? "pièces" : "pièce"}</div>
      </div>

      <div className="product-grid">
        {products.map((p) => <ProductCard key={p.id} product={p} navigate={navigate} />)}
      </div>
    </div>
  );
}

function paletteLabel(id) {
  return ({ indigo: "Indigo", terre: "Terracotta", safran: "Safran", rose: "Rose", vert: "Vert sauge", noir: "Noir", bleuPaon: "Bleu paon", ocre: "Ocre" })[id] || id;
}

// ─── Product detail ──────────────────────────────────────────────
function Product({ route, navigate, addToCart }) {
  const product = PRODUCTS.find((p) => p.id === route.id);
  const [sizeIdx, setSizeIdx] = useStateC(0);
  const [qty, setQty] = useStateC(1);
  const [customName, setCustomName] = useStateC("");
  const [view, setView] = useStateC(0);

  if (!product) {
    return <div className="wrap" style={{ padding: 80 }}>Produit introuvable. <a onClick={() => navigate({ page: "home" })} style={{ borderBottom: "1px solid", cursor: "pointer" }}>Retour</a></div>;
  }

  const palette = PALETTES[product.palette];
  const url = makePattern(product.pattern, palette);
  const size = product.sizes[sizeIdx];

  const altPatterns = ["fleur", "buti", "jaali", "stripes"];
  const galleryItems = product.gallery
    ? product.gallery.map((src) => ({ ...product, img: src }))
    : product.img
      ? [product]
      : altPatterns.map((p) => ({ ...product, pattern: p }));

  const handleAdd = () => {
    addToCart({
      id: product.id + "-" + sizeIdx + (customName ? "-" + customName : ""),
      productId: product.id,
      name: product.name,
      size: size.label,
      price: size.price,
      qty,
      pattern: product.pattern,
      palette: product.palette,
      img: product.img || null,
      customName: customName || null,
    });
    setQty(1);
    setCustomName("");
  };

  const related = PRODUCTS.filter((p) => p.category === product.category && p.id !== product.id).slice(0, 4);

  return (
    <div className="wrap">
      <div className="catalog-head" style={{ paddingBottom: 16, marginBottom: 0, borderBottom: "none" }}>
        <div className="crumbs">
          <a onClick={() => navigate({ page: "home" })} style={{ cursor: "pointer" }}>Accueil</a>
          <span> / </span>
          <a onClick={() => navigate({ page: "catalog", category: product.category })} style={{ cursor: "pointer" }}>
            {(CATEGORIES.find((c) => c.id === product.category) || {}).label}
          </a>
          <span> / </span>
          <span>{product.name}</span>
        </div>
      </div>

      <div className="pd">
        <div className="pd-gallery">
          <div className="pd-main">
            <PH product={galleryItems[view]} label="Photo produit · à venir" frame tile={120} />
          </div>
          {galleryItems.length > 1 && (
            <div className="pd-thumbs">
              {galleryItems.map((g, i) => (
                <div key={i} className={"pd-thumb" + (i === view ? " active" : "")} onClick={() => setView(i)}>
                  <PH product={g} tile={50} />
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="pd-info">
          <div className="pd-collec">{product.collection ? `Collection ${product.collection}` : (CATEGORIES.find((c) => c.id === product.category) || {}).label}</div>
          <h1>{product.name}</h1>
          <div className="pd-price">{size.price} €</div>
          <p className="pd-desc">{product.desc}</p>

          <div className="pd-section-label">— Choisir une dimension</div>
          <div className="pd-sizes">
            {product.sizes.map((s, i) => (
              <button key={i} className={"pd-size" + (i === sizeIdx ? " active" : "")} onClick={() => setSizeIdx(i)}>
                <span>{s.label}</span>
                <strong>{s.price} €</strong>
              </button>
            ))}
          </div>

          {product.custom && (
            <div className="pd-custom">
              <label>Personnaliser</label>
              <input type="text" placeholder="Prénom à broder (optionnel)" value={customName} onChange={(e) => setCustomName(e.target.value.slice(0, 14))} />
            </div>
          )}

          <div className="pd-add">
            <div className="qty">
              <button onClick={() => setQty(Math.max(1, qty - 1))}>−</button>
              <span>{qty}</span>
              <button onClick={() => setQty(qty + 1)}>+</button>
            </div>
            <button className="btn" onClick={handleAdd}>Ajouter au panier · {qty * size.price} €</button>
          </div>

          <div className="pd-meta">
            <div>100% coton</div>
            <div>Made in Jaipur with ♥</div>
            <div>Lavage machine 30°</div>
            <div>Livraison sous 5 jours</div>
          </div>

          <div style={{ marginTop: 32, padding: 20, background: "var(--paper-2)", borderLeft: "2px solid var(--terre)" }}>
            <div className="pd-section-label" style={{ marginBottom: 8 }}>— Une question ?</div>
            <p style={{ margin: 0, fontSize: 14, color: "var(--ink-2)" }}>
              Échangez avec nous directement par WhatsApp au <strong style={{ color: "var(--ink)" }}>+33 6 60 50 12 57</strong>.
            </p>
            <a href="https://wa.me/33660501257?text=Bonjour, je souhaite des informations sur le produit %22{product.name}%22" className="btn-link" style={{ marginTop: 12, display: "inline-block" }} target="_blank" rel="noopener">
              Ouvrir WhatsApp →
            </a>
          </div>
        </div>
      </div>

      {related.length > 0 && (
        <div className="section-tight" style={{ borderTop: "1px solid var(--line)" }}>
          <div className="section-head">
            <h2 className="section-title" style={{ fontSize: 36 }}>Vous aimerez aussi</h2>
          </div>
          <div className="product-grid compact">
            {related.map((p) => <ProductCard key={p.id} product={p} navigate={navigate} />)}
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Cart drawer ─────────────────────────────────────────────────
function Cart({ open, close, items, setQty, removeItem, navigate }) {
  const total = items.reduce((sum, it) => sum + it.price * it.qty, 0);
  const freeFromAt = 150;
  const remaining = Math.max(0, freeFromAt - total);

  return (
    <>
      <div className={"cart-overlay" + (open ? " open" : "")} onClick={close} />
      <aside className={"cart-drawer" + (open ? " open" : "")}>
        <div className="cart-head">
          <h3>Panier {items.length > 0 && <span style={{ color: "var(--ink-2)", fontSize: 14, fontFamily: "var(--mono)", letterSpacing: "0.16em", marginLeft: 8 }}>{items.length}</span>}</h3>
          <button className="close" onClick={close}>×</button>
        </div>
        <div className="cart-items">
          {items.length === 0 ? (
            <div className="cart-empty">
              <p>Votre panier est vide.</p>
              <button className="btn" onClick={() => { close(); navigate({ page: "catalog", category: "all" }); }}>Découvrir le catalogue</button>
            </div>
          ) : (
            items.map((it) => {
              const palette = PALETTES[it.palette];
              const url = makePattern(it.pattern, palette);
              return (
                <div className="cart-item" key={it.id}>
                  <div className="cart-item-img" style={it.img
                    ? { backgroundImage: `url("${it.img}")`, backgroundSize: "cover", backgroundPosition: "center" }
                    : { background: `${palette.paper} url("${url}")`, backgroundSize: "60px 60px" }} />
                  <div>
                    <div className="cart-item-name">{it.name}</div>
                    <div className="cart-item-meta">{it.size}</div>
                    {it.customName && <div className="cart-item-meta" style={{ color: "var(--indigo)" }}>↪ Brodé : « {it.customName} »</div>}
                    <div className="cart-item-actions">
                      <button onClick={() => setQty(it.id, Math.max(1, it.qty - 1))}>−</button>
                      <span>{it.qty}</span>
                      <button onClick={() => setQty(it.id, it.qty + 1)}>+</button>
                      <button onClick={() => removeItem(it.id)}>Retirer</button>
                    </div>
                  </div>
                  <div className="cart-item-price">{it.price * it.qty} €</div>
                </div>
              );
            })
          )}
        </div>
        {items.length > 0 && (
          <div className="cart-foot">
            {remaining > 0 ? (
              <div className="cart-shipping">Plus que {remaining} € pour la livraison offerte</div>
            ) : (
              <div className="cart-shipping" style={{ color: "var(--indigo)" }}>✓ Livraison offerte en France</div>
            )}
            <div className="cart-total">
              <span>Total estimé</span>
              <span>{total} €</span>
            </div>
            <a
              href={(() => {
                const lines = items.map(it =>
                  `• ${it.qty > 1 ? it.qty + "× " : ""}${it.name} — ${it.size} — ${it.price * it.qty} €` +
                  (it.customName ? `\n  ↳ Brodé : « ${it.customName} »` : "")
                );
                const msg =
                  `Bonjour ! Je souhaite commander les articles suivants :\n\n` +
                  lines.join("\n") +
                  `\n\nTotal : ${total} €\n\nMerci de me confirmer la disponibilité 🙏`;
                return "https://wa.me/33660501257?text=" + encodeURIComponent(msg);
              })()}
              target="_blank"
              rel="noopener"
              className="btn"
              style={{ width: "100%", justifyContent: "center", display: "flex" }}
            >
              Commander via WhatsApp →
            </a>
          </div>
        )}
      </aside>
    </>
  );
}

// ─── Footer ──────────────────────────────────────────────────────
function Footer({ navigate, brand }) {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-brand">
            <img src="/images/logo-comptoir-indigo.svg" alt={brand.name} style={{ height: 80, width: "auto", display: "block", marginBottom: 12, filter: "brightness(0) invert(1)" }} />
            <p>Textiles imprimés à la main au Rajasthan.</p>
          </div>
          <div className="footer-col">
            <h4>Boutique</h4>
            <ul>
              <li><a onClick={() => navigate({ page: "catalog", category: "nappes" })} style={{ cursor: "pointer" }}>Nappes</a></li>
<li><a onClick={() => navigate({ page: "catalog", category: "sacs" })} style={{ cursor: "pointer" }}>Sacs</a></li>
              <li><a onClick={() => navigate({ page: "catalog", category: "pochettes" })} style={{ cursor: "pointer" }}>Trousses & pochettes</a></li>
              <li><a onClick={() => navigate({ page: "catalog", category: "chemins" })} style={{ cursor: "pointer" }}>Chemins de table</a></li>
              <li><a onClick={() => navigate({ page: "catalog", category: "couettes" })} style={{ cursor: "pointer" }}>Couettes enfants</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Contact</h4>
            <ul>
              <li><a href="https://wa.me/33660501257" target="_blank" rel="noopener">WhatsApp · +33 6 60 50 12 57</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bot">
          <span>© 2026 {brand.name}</span>
          <span>Made in Jaipur with ♥ · Curated in Paris</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Catalog, Product, Cart, Footer });
