/* global React, ReactDOM, PRODUCTS, CATEGORIES, COLLECTIONS, PALETTES, makePattern */
const { useState, useEffect, useMemo, useRef } = React;

// ─── PlaceholderImage ─────────────────────────────────────────────
function PH({ product, label, frame = false, tile = 80, opacity = 1 }) {
  const palette = PALETTES[product.palette] || PALETTES.indigo;
  const url = makePattern(product.pattern, palette);
  const style = {
    "--ph-pattern": product.img ? "none" : `url("${url}")`,
    "--ph-tile": tile + "px",
    "--ph-opacity": opacity,
    background: palette.paper,
  };
  return (
    <div className="ph" style={style}>
      {product.img && <img src={product.img} alt={product.name} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 1 }} />}
      {frame && <div className="ph-frame" style={{ zIndex: 4 }} />}
      {!product.img && label && <div className="ph-label">{label}</div>}
    </div>
  );
}

function patternStyle(product) {
  const palette = PALETTES[product.palette] || PALETTES.indigo;
  const url = makePattern(product.pattern, palette);
  return { "--card-pattern": `url("${url}")`, background: palette.paper };
}

// ─── Header ───────────────────────────────────────────────────────
function Header({ route, navigate, cartCount, openCart, brand }) {
  const navItems = [
    { id: "accueil", label: "Accueil" },
    { id: "nappes", label: "Nappes" },
    { id: "pochettes", label: "Trousses & pochettes" },
    { id: "couettes", label: "Linge de lit" },
    { id: "sacs", label: "Sacs" },
  ];
  return (
    <header className="header">
      <div className="header-inner">
        <nav className="nav">
          {navItems.slice(0, 4).map((it) => (
            <button key={it.id} onClick={() => navigate({ page: it.id === "accueil" ? "home" : "catalog", category: it.id })} className={route.category === it.id ? "active" : ""}>
              {it.label}
            </button>
          ))}
        </nav>
        <button className="brand" onClick={() => navigate({ page: "home" })} style={{ background: "none", border: "none", padding: 0 }}>
          <img src="/images/logo-comptoir-indigo.svg" alt={brand.name} style={{ height: 160, width: "auto", display: "block" }} />
        </button>
        <div className="nav-right">
          <button className="icon-btn nav-catalogue" onClick={() => navigate({ page: "catalog", category: "all" })}>
            Catalogue
          </button>
          <a className="icon-btn" href="https://wa.me/33660501257" target="_blank" rel="noopener" title="WhatsApp">
            <svg className="nav-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.525 3.66 1.438 5.168L2 22l4.978-1.418A9.956 9.956 0 0012 22c5.523 0 10-4.477 10-10S17.523 2 12 2z" fill="currentColor"/>
              <path d="M17 14.57c-.275-.138-1.628-.803-1.88-.895-.25-.09-.433-.137-.615.138-.183.274-.707.895-.867 1.079-.16.183-.32.206-.594.069-.275-.138-1.16-.427-2.21-1.362-.817-.728-1.369-1.627-1.529-1.902-.16-.274-.017-.423.12-.56.124-.123.275-.32.412-.48.138-.16.183-.275.275-.458.091-.183.046-.343-.023-.48-.069-.138-.615-1.484-.843-2.033-.222-.534-.448-.46-.615-.469l-.524-.009c-.183 0-.48.069-.731.343-.252.275-.96.938-.96 2.285 0 1.348.983 2.65 1.12 2.833.137.183 1.934 2.95 4.687 4.136.655.283 1.166.452 1.565.578.658.209 1.257.18 1.73.11.527-.079 1.628-.666 1.857-1.309.228-.643.228-1.194.16-1.309-.069-.114-.251-.183-.526-.32z" fill="white"/>
            </svg>
            <span className="nav-label">WhatsApp</span>
          </a>
          <button className="icon-btn" onClick={openCart}>
            <svg className="nav-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/>
              <line x1="3" y1="6" x2="21" y2="6"/>
              <path d="M16 10a4 4 0 01-8 0"/>
            </svg>
            <span className="nav-label">Panier</span>
            {cartCount > 0 && <span className="badge">{cartCount}</span>}
          </button>
        </div>
      </div>
    </header>
  );
}

// ─── Hero ─────────────────────────────────────────────────────────
function Hero({ navigate, brand }) {
  const heroProduct = { palette: "indigo", pattern: "fleur" };
  return (
    <section className="hero">
      <div className="hero-text">
        <div className="hero-eyebrow">— Imprimé à la main · Jaipur, Rajasthan</div>
        <h1>
          La table<br />comme<br /><em>un voyage</em>.
        </h1>
        <p className="hero-lede">
          {brand.name} importe des textiles imprimés à la planche par des artisans du Rajasthan. Coton 100%, finitions main, motifs vivants — pour une table qui raconte un voyage.
        </p>
        <div className="hero-cta">
          <button className="btn" onClick={() => navigate({ page: "catalog", category: "nappes" })}>
            Découvrir les nappes
          </button>
          <button className="btn-link" onClick={() => navigate({ page: "catalog", category: "all" })}>
            Voir toute la collection →
          </button>
        </div>
      </div>
      <div className="hero-image">
        <img src="/images/bombay-1.jpg" alt="Nappe Bombay blockprint" style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center", display: "block" }} />
      </div>
    </section>
  );
}

// ─── Values bar ──────────────────────────────────────────────────
function Values() {
  const items = [
    { t: "Imprimé main", s: "Planches de bois, Bagru" },
    { t: "100% coton", s: "Tissé au Rajasthan" },
    { t: "Personnalisable", s: "Couettes & pochettes" },
    { t: "Livraison France", s: "Offerte dès 150 €" },
  ];
  return (
    <div className="values">
      {items.map((it, i) => (
        <div className="value" key={i}>
          <div className="value-title">{it.t}</div>
          <div className="value-sub">{it.s}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Catégories tuiles (page accueil) ────────────────────────────
function CategoryTiles({ navigate }) {
  const tiles = [
    { id: "nappes",  label: "Nappes",              lead: "Trois collections",          size: "large",  img: "/images/bombay-6.jpg" },
    { id: "couettes",label: "Plaids enfants",       lead: "Personnalisables au prénom", size: "medium", img: "/images/linge-1.jpg" },
{ id: "pochettes", label: "Trousses & pochettes", lead: "Blockprint, fermeture zip",  size: "small",  img: "/images/perso-1.jpg" },
    { id: "chemins",   label: "Chemins de table",   lead: "Pour rythmer la table",      size: "small",  img: "/images/chemins-15.jpg" },
    { id: "housses",   label: "Housses ordinateur",  lead: "100% coton blockprint",      size: "small",  img: "/images/housses-2.jpg" },
    { id: "sacs",      label: "Sacs",                lead: "Cabas, trousses perso",      size: "small",  img: "/images/Sacbleuetvert5.jpeg" },
  ];
  return (
    <section style={{ padding: "20px 0 0" }}>
      <div className="wrap">
        <div className="cat-grid">
          {tiles.map((t) => (
              <div
                key={t.id}
                className={`cat-card ${t.size}`}
                onClick={() => navigate({ page: "catalog", category: t.id })}
              >
                <div className="cat-card-img" style={{ "--cat-pattern": "none" }}>
                  <img src={t.img} alt={t.label} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center" }} />
                </div>
                <div className="cat-card-meta">
                  <div>
                    <h3>{t.label}</h3>
                    <p>{t.lead}</p>
                  </div>
                  <div className="cat-card-arrow">→</div>
                </div>
              </div>
            ))}
        </div>
      </div>
    </section>
  );
}

// ─── Editorial / story ───────────────────────────────────────────
function Editorial({ brand }) {
  const p = { palette: "terre", pattern: "buti" };
  return (
    <section className="section" style={{ background: "var(--paper-2)" }}>
      <div className="wrap">
        <div className="editorial">
          <div className="editorial-img">
            <img src="/images/bombay-6.jpg" alt="Nappe blockprint Rajasthan" style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center top", display: "block" }} />
          </div>
          <div className="editorial-body">
            <div className="section-eyebrow">— Notre démarche</div>
            <h2>Tissé, teint, imprimé <em>à la main</em>.</h2>
            <p>
              Nos pièces viennent toutes des ateliers de Jaipur et de Bagru, au Rajasthan, où l'impression à la planche de bois se transmet de génération en génération.
            </p>
            <p>
              Le coton est tissé localement, lavé à l'eau claire, puis imprimé planche après planche. Chaque pièce est unique — les légères irrégularités sont la signature du travail à la main.
            </p>
            <div className="editorial-stats">
              <div><strong>2 ateliers</strong>partenaires depuis 2024</div>
              <div><strong>100%</strong>coton, sans traitement</div>
              <div><strong>30+</strong>motifs au catalogue</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Featured products ───────────────────────────────────────────
function Featured({ navigate }) {
  const featured = PRODUCTS.filter((p) => p.tag).slice(0, 4);
  return (
    <section className="section">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="section-eyebrow">— Sélection</div>
            <h2 className="section-title">Nos pièces <em>signatures</em>.</h2>
          </div>
          <button className="btn-link" onClick={() => navigate({ page: "catalog", category: "all" })}>
            Voir tout →
          </button>
        </div>
        <div className="product-grid compact">
          {featured.map((p) => (
            <ProductCard key={p.id} product={p} navigate={navigate} />
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Product card ────────────────────────────────────────────────
function ProductCard({ product, navigate }) {
  const palette = PALETTES[product.palette];
  const url = makePattern(product.pattern, palette);
  const minPrice = Math.min(...product.sizes.map((s) => s.price));
  const sizeWord = product.sizes.length > 1 ? "Dès" : "";
  return (
    <div className="product-card" onClick={() => navigate({ page: "product", id: product.id })}>
      <div className="product-card-img" style={{ "--card-pattern": product.img ? "none" : `url("${url}")`, background: palette.paper }}>
        {product.img && <img src={product.img} alt={product.name} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", zIndex: 1 }} />}
        {product.tag && <div className="product-tag" style={{ zIndex: 3 }}>{product.tag}</div>}
      </div>
      <div className="product-card-info">
        {product.collection && <div className="product-card-collection">{product.collection}</div>}
        <h3 className="product-card-name">{product.name}</h3>
        <div className="product-card-price">{sizeWord} {minPrice} €</div>
      </div>
    </div>
  );
}

Object.assign(window, { PH, patternStyle, Header, Hero, Values, CategoryTiles, Editorial, Featured, ProductCard });
