/* global React */
const { useState, useMemo, useCallback } = React;

/* ============================== TopBar ============================== */
function TopBar({ cartCount, onOpenCart, niche }) {
  return (
    <header className="hl-topbar">
      <div className="hl-topbar__inner">
        <a href="https://heliance.com" className="hl-brand" aria-label="Heliance">
          <img src="assets/logos/heliance.jpg" alt="Heliance" className="hl-brand__logo"/>
        </a>
        <div className="hl-topbar__eyebrow">{niche}</div>
        <div className="hl-topbar__right">
          <a href="#aide" className="hl-link-muted">Aide</a>
          <button className="hl-cart-btn" onClick={onOpenCart} aria-label="Voir panier">
            Panier
            <span className="hl-cart-pill">{cartCount}</span>
          </button>
        </div>
      </div>
    </header>
  );
}

/* ============================== Hero ============================== */
function Hero({ data }) {
  return (
    <section className="hl-hero">
      <div className="hl-hero__banner" aria-hidden="true">
        <img src="assets/boutique-scenes/boutique-aquarium.jpg" alt="" loading="eager"/>
        <div className="hl-hero__banner-overlay"/>
      </div>
      <div className="hl-hero__eyebrow">FABRICANT DISTRIBUTEUR</div>
      <h1 className="hl-hero__title">
        selection Heliance : <em className="hl-hero__title-aqua">{data.name}</em>
      </h1>
      <p className="hl-hero__sub">
        {data.totalRefs} pièces aquatiques en {data.materials} —
        pinces, manchettes, bagues, boucles d'oreilles, colliers et broches.
        Conçues et fabriquées en atelier pour les {data.audience}, livrées en direct sans intermédiaire.
      </p>
      <div className="hl-hero__meta">
        <span>{data.totalRefs} références</span>
        <span>{data.priceRange}</span>
        <span>Sans minimum d'achat</span>
      </div>
    </section>
  );
}

/* ============================== HowToOrder (3 étapes) ============================== */
function HowToOrder() {
  return (
    <div className="hl-howto" id="aide">
      <div className="hl-howto__inner">
        <div className="hl-howto__step">
          <span className="hl-howto__num">1</span>
          <span className="hl-howto__text">Ajoutez vos references</span>
        </div>
        <span className="hl-howto__arrow" aria-hidden="true">&rsaquo;</span>
        <div className="hl-howto__step">
          <span className="hl-howto__num">2</span>
          <span className="hl-howto__text">Choisissez la livraison</span>
        </div>
        <span className="hl-howto__arrow" aria-hidden="true">&rsaquo;</span>
        <div className="hl-howto__step">
          <span className="hl-howto__num">3</span>
          <span className="hl-howto__text">Envoyez par WhatsApp</span>
        </div>
      </div>
    </div>
  );
}

/* ============================== SectionHeader ============================== */
function SectionHeader({ title, count, index }) {
  const idx = String(index).padStart(2, "0");
  return (
    <div className="hl-section-header">
      <h2 className="hl-section-header__title">{title}</h2>
      <span className="hl-section-header__count">{count} ref.</span>
      <span className="hl-section-header__anchor">§ {idx}</span>
    </div>
  );
}

/* ============================== ColorSwatches ============================== */
function ColorSwatches({ colors, selectedIdx, onSelect }) {
  if (!colors || colors.length === 0) return null;
  if (colors.length === 1 && colors[0].label === "Unique") {
    return <span className="hl-swatches__single">1 coloris</span>;
  }
  return (
    <div className="hl-swatches" role="radiogroup" aria-label="Choix du coloris">
      {colors.map((c, i) => (
        <button
          key={c.label + i}
          type="button"
          role="radio"
          aria-checked={i === selectedIdx}
          aria-label={c.label}
          title={c.label}
          className={"hl-swatch" + (i === selectedIdx ? " is-selected" : "")}
          style={{ backgroundColor: c.hex }}
          onClick={(e) => { e.stopPropagation(); onSelect(i); }}
        />
      ))}
    </div>
  );
}

/* ============================== ProductCard ============================== */
function ProductCard({ item, cart, onAdd, onRemove }) {
  const [selectedIdx, setSelectedIdx] = useState(0);
  const color = item.colors[selectedIdx] || item.colors[0];
  const key = item.ref + "::" + (color ? color.label : "Unique");
  const qty = cart[key] || 0;
  const priceFr = item.price.toFixed(2).replace(".", ",");
  const themeChip = item.theme && item.theme !== "Marin" ? item.theme : null;
  const displayImg = (color && color.img) || item.img;

  return (
    <article className={"hl-card" + (qty > 0 ? " is-added" : "")}>
      <div className="hl-card__img">
        {displayImg ? <img src={displayImg} alt={item.name} loading="lazy" /> : <div className="hl-card__img-empty" />}
        {qty > 0 && <span className="hl-card__qty-badge">{qty}</span>}
      </div>
      <div className="hl-card__body">
        <div className="hl-card__ref">
          {item.ref}
          {themeChip && <> · <span className="hl-card__theme">{themeChip}</span></>}
        </div>
        <div className="hl-card__name">{item.name}</div>
        <ColorSwatches colors={item.colors} selectedIdx={selectedIdx} onSelect={setSelectedIdx} />
        <div className="hl-card__price">{priceFr} € HT</div>
      </div>
      {qty === 0 ? (
        <button className="hl-card__add" onClick={() => onAdd(item, color)}>+ Ajouter</button>
      ) : (
        <div className="hl-card__qty">
          <button className="hl-card__qty-btn" onClick={() => onRemove(item, color)}>−</button>
          <span className="hl-card__qty-num">{qty}</span>
          <button className="hl-card__qty-btn" onClick={() => onAdd(item, color)}>+</button>
        </div>
      )}
    </article>
  );
}

/* ============================== OrderBar ============================== */
function OrderBar({ count, total, onOpenCart, onOrder }) {
  const totalFr = total.toFixed(2).replace(".", ",");
  return (
    <div className="hl-orderbar">
      <div className="hl-orderbar__inner">
        <div className="hl-orderbar__total">
          <div className="hl-orderbar__label">
            Panier · {count} {count === 1 ? "référence" : "références"}
          </div>
          <div className="hl-orderbar__amount">{totalFr} € HT</div>
        </div>
        <div className="hl-orderbar__progress">
          Sans minimum d'achat · <strong>livraison offerte partout, même à l'étranger</strong>
        </div>
        <div className="hl-orderbar__actions">
          <button className="hl-btn hl-btn--ghost" onClick={onOpenCart} disabled={count === 0}>
            Voir panier
          </button>
          <button className="hl-btn hl-btn--wa" onClick={onOrder} disabled={count === 0}>
            <WaIcon />
            Commander par WhatsApp
          </button>
        </div>
      </div>
    </div>
  );
}

/* ============================== CartDrawer ============================== */
function CartDrawer({ open, lines, total, delivery, deliveryIdx, onSelectDelivery, onClose, onAdd, onRemove, onOrder }) {
  const fmt = (n) => n.toFixed(2).replace(".", ",");
  const opts = (delivery && delivery.options) || [];
  const deliv = opts[deliveryIdx] || opts[0] || { price: 0 };
  const grand = total + (deliv.price || 0);
  return (
    <>
      <div className={"hl-overlay" + (open ? " is-open" : "")} onClick={onClose} />
      <aside className={"hl-drawer" + (open ? " is-open" : "")} aria-hidden={!open}>
        <header className="hl-drawer__head">
          <div className="hl-drawer__title">Votre panier</div>
          <button className="hl-drawer__close" onClick={onClose} aria-label="Fermer">
            <CloseIcon />
          </button>
        </header>
        {lines.length === 0 ? (
          <div className="hl-drawer__empty">
            Votre panier est vide. <br/>
            Cliquez sur «&nbsp;+ Ajouter&nbsp;» sur un produit.
          </div>
        ) : (
          <ul className="hl-drawer__list">
            {lines.map(line => {
              const lineTotal = (line.qty * line.item.price).toFixed(2).replace(".", ",");
              return (
                <li key={line.key} className="hl-drawer__item">
                  {(line.color && line.color.img) ? <img src={line.color.img} alt="" className="hl-drawer__thumb"/> : (line.item.img && <img src={line.item.img} alt="" className="hl-drawer__thumb"/>)}
                  <div className="hl-drawer__meta">
                    <div className="hl-drawer__ref">
                      {line.item.ref}
                      {line.color && line.color.label !== "Unique" && (
                        <> · <span className="hl-drawer__color">
                          <span className="hl-drawer__color-dot" style={{ backgroundColor: line.color.hex }} />
                          {line.color.label}
                        </span></>
                      )}
                    </div>
                    <div className="hl-drawer__name">{line.item.name}</div>
                    <div className="hl-drawer__qty">
                      <button onClick={() => onRemove(line.item, line.color)}>−</button>
                      <span>{line.qty}</span>
                      <button onClick={() => onAdd(line.item, line.color)}>+</button>
                    </div>
                  </div>
                  <div className="hl-drawer__line">{lineTotal} €</div>
                </li>
              );
            })}
          </ul>
        )}
        <footer className="hl-drawer__foot">
          <div className="hl-drawer__sub">
            <span>Sous-total HT</span><span>{fmt(total)} €</span>
          </div>
          <div className="hl-drawer__delivery">
            <div className="hl-drawer__delivery-title">Livraison offerte, sans minimum</div>
            {opts.map((o, i) => (
              <label key={i} className={"hl-deliv-opt" + (i === deliveryIdx ? " is-selected" : "")}>
                <input type="checkbox" checked={i === deliveryIdx} onChange={() => onSelectDelivery(i)} />
                <span className="hl-deliv-opt__label">{o.label}</span>
                <span className="hl-deliv-opt__price">{o.price > 0 ? `${fmt(o.price)} €` : "Offerte"}</span>
              </label>
            ))}
          </div>
          <div className="hl-drawer__sub hl-drawer__sub--total">
            <span>Total HT</span><span>{fmt(grand)} €</span>
          </div>
          <button className="hl-btn hl-btn--wa hl-btn--block" disabled={lines.length === 0} onClick={onOrder}>
            <WaIcon />
            Commander par WhatsApp
          </button>
        </footer>
      </aside>
    </>
  );
}

/* ============================== ValidityFooter ============================== */
function ValidityFooter({ data, deliveryIdx, onSelectDelivery }) {
  const fmt = (n) => n.toFixed(2).replace(".", ",");
  const opts = (data.delivery && data.delivery.options) || [];
  return (
    <footer className="hl-validfoot">
      <div className="hl-validfoot__note">
        Collection préparée le <strong>{data.preparedOn}</strong>, valable 30 jours
        (expire le <strong>{data.expiresOn}</strong>).
      </div>
      <div className="hl-validfoot__delivery">
        <div className="hl-validfoot__delivery-title">Livraison offerte, sans minimum</div>
        <div className="hl-deliv-grid">
          {opts.map((o, i) => (
            <label key={i} className={"hl-deliv-opt" + (i === deliveryIdx ? " is-selected" : "")}>
              <input type="checkbox" checked={i === deliveryIdx} onChange={() => onSelectDelivery(i)} />
              <span className="hl-deliv-opt__label">{o.label}</span>
              <span className="hl-deliv-opt__price">{o.price > 0 ? `${fmt(o.price)} €` : "Offerte"}</span>
            </label>
          ))}
        </div>
        <div className="hl-validfoot__delivery-hint">Le mode coché part dans votre message de commande WhatsApp.</div>
      </div>
      <div className="hl-validfoot__grid">
        <div><div className="hl-validfoot__label">Prix</div><div className="hl-validfoot__val">Tous en <strong>HT</strong> (revente professionnelle)</div></div>
        <div><div className="hl-validfoot__label">Commande</div><div className="hl-validfoot__val">Par WhatsApp ou email</div></div>
      </div>
      <div className="hl-validfoot__contact">
        Ou par email : <a href={"mailto:" + data.contactMail}>{data.contactMail}</a>
      </div>
      <div className="hl-validfoot__sig">
        <img src="assets/logos/heliance-icon.png" alt="" className="hl-validfoot__icon"/>
        <span>Heliance · Fabricant distributeur</span>
        <span>·</span>
        <span>{data.niche}</span>
      </div>
    </footer>
  );
}

/* ============================== Icons ============================== */
function WaIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16" aria-hidden="true">
      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893A11.821 11.821 0 0 0 20.464 3.488"/>
    </svg>
  );
}
function CloseIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" width="18" height="18">
      <path d="M18 6 6 18M6 6l12 12"/>
    </svg>
  );
}

/* ============================== WhatsAppFloating ============================== */
function WhatsAppFloating({ number, niche }) {
  const greeting = `Bonjour, je consulte votre selection ${niche || "Heliance"}. J'aurais une question.`;
  const url = `https://wa.me/${(number || "").replace(/\D/g, "")}?text=${encodeURIComponent(greeting)}`;
  return (
    <a
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      className="hl-wa-float"
      aria-label="Discuter sur WhatsApp"
      title="Discuter avec Heliance sur WhatsApp"
    >
      <WaIcon />
      <span className="hl-wa-float__label">Discuter</span>
    </a>
  );
}

Object.assign(window, { TopBar, Hero, SectionHeader, ProductCard, ColorSwatches, OrderBar, CartDrawer, ValidityFooter, WhatsAppFloating, WaIcon, CloseIcon });
