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

// -------- Icons (inline SVGs) --------
const Icon = {
  Search: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>),
  Heart: ({filled}) => (<svg width="14" height="14" viewBox="0 0 24 24" fill={filled?'currentColor':'none'} stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.29 1.51 4.04 3 5.5l7 7Z"/></svg>),
  X: () => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>),
  Bag: () => (<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"/><path d="M3 6h18"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>),
  Arrow: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>),
  Repeat: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/></svg>),
  Check: () => (<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>),
  Download: () => (<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>),
  Sparkle: () => (<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2 13.5 9 21 10.5 13.5 12 12 19.5 10.5 12 3 10.5 10.5 9Z"/></svg>),
};

// -------- Helpers --------
const fmt = (n) => n.toLocaleString('fr-FR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';
const fmt0 = (n) => Math.round(n).toLocaleString('fr-FR') + ' €';

// -------- Qty stepper --------
function QtyStepper({ value, onChange, min = 3 }) {
  const dec = () => onChange(Math.max(min, value - 1));
  const inc = () => onChange(value + 1);
  const set = (v) => {
    const n = parseInt(v, 10);
    if (isNaN(n)) onChange(min);
    else onChange(Math.max(min, n));
  };
  return (
    <div className="qty" onClick={(e) => e.stopPropagation()}>
      <button onClick={dec} disabled={value <= min} aria-label="moins">−</button>
      <input
        type="number"
        value={value}
        min={min}
        onChange={(e) => set(e.target.value)}
        onClick={(e) => e.target.select()}
      />
      <button onClick={inc} aria-label="plus">+</button>
    </div>
  );
}

// -------- Product Card --------
function ProductCard({ product, cartQty, onAdd, onSetQty, onFav, isFav, onQuickView, reordered }) {
  const inCart = cartQty > 0;
  const available = product.available;
  const isIdentified = !!(window.CLIENT && window.CLIENT.identified);
  const signupUrl = (window.EXTRANET_CONFIG?.base_url || '') + '/#auth';

  return (
    <article
      className={
        "card" +
        (inCart ? " in-cart" : "") +
        (!available ? " unavailable" : "")
      }
      onClick={() => {
        if (!isIdentified) { window.location.href = signupUrl; return; }
        if (available) onQuickView(product);
      }}
    >
      <div className="card-media">
        <img src={product.img} alt={product.name} loading="lazy"
             onError={(e)=>{e.target.style.opacity=0.2;e.target.src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><rect fill='%23efe7d8' width='100' height='100'/></svg>";}}/>
        <div className="card-badges">
          {product.isNew && <span className="badge new">Nouveau</span>}
          {product.popular && available && !product.isNew && <span className="badge popular">★ Best</span>}
          {!available && <span className="badge unavailable">Rupture</span>}
          {reordered && available && <span className="badge reordered">Déjà commandé</span>}
        </div>
        {isIdentified && (
          <button
            className={"fav-btn" + (isFav ? " active" : "")}
            onClick={(e) => { e.stopPropagation(); onFav(product.ref); }}
            aria-label="Favori"
          >
            <Icon.Heart filled={isFav} />
          </button>
        )}
        {available && isIdentified && <button className="quick-view-btn" onClick={(e) => { e.stopPropagation(); onQuickView(product); }}>Aperçu rapide</button>}
      </div>
      <div className="card-body">
        <div className="card-ref">{product.ref}</div>
        <h3 className="card-name">{product.name}</h3>
        <div className="card-foot">
          {isIdentified ? (
            <>
              <div className="card-price">
                {fmt(product.price)}
                <small>HT · min 3</small>
              </div>
              {available ? (
                inCart ? (
                  <QtyStepper value={cartQty} onChange={(q) => onSetQty(product.ref, q)} />
                ) : (
                  <button className="add-btn" onClick={(e) => { e.stopPropagation(); onAdd(product.ref); }}>
                    + Ajouter
                  </button>
                )
              ) : (
                <span className="unavailable-tag">Indispo.</span>
              )}
            </>
          ) : (
            <a className="add-btn" href={signupUrl} onClick={(e) => e.stopPropagation()} style={{flex:1, textAlign:'center', textDecoration:'none'}}>
              Devenir revendeur →
            </a>
          )}
        </div>
      </div>
    </article>
  );
}

// -------- Quick View Modal --------
function QuickViewModal({ product, onClose, cartQty, onSetQty, onAdd, productsByRef, onSwitch }) {
  useEffect(() => {
    const handler = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [onClose]);

  if (!product) return null;
  const cobought = (window.COBOUGHT[product.ref] || []).map(r => productsByRef[r]).filter(Boolean);
  const themeLabel = window.THEMES[product.theme] || '';
  const catLabel = (window.CATEGORIES.find(c => c.id === product.cat) || {}).label || '';

  return (
    <div className={"modal-backdrop open"} onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-media">
          <img src={product.img} alt={product.name} />
          <button className="icon-btn" style={{position:'absolute',top:14,left:14,background:'rgba(251,248,241,0.92)'}} onClick={onClose}><Icon.X /></button>
        </div>
        <div className="modal-body">
          <div className="card-ref">{product.ref}</div>
          <h2>{product.name}</h2>
          <div className="price">
            {fmt(product.price)} <small>HT · par 3 minimum</small>
          </div>
          <p className="desc">
            Kit créatif artisanal complet, livré avec tous les éléments nécessaires et le pas-à-pas illustré.
            Conçu et préparé à la main dans nos ateliers en France — idéal pour vos clients en quête d'une activité douce et inspirante.
          </p>
          <div className="modal-meta">
            <span className="meta-pill">Catégorie · {catLabel}</span>
            <span className="meta-pill">Type · {themeLabel}</span>
            <span className="meta-pill">Conditionné par 3</span>
            {product.popular && <span className="meta-pill" style={{borderColor:'var(--sage)',color:'var(--sage)'}}>★ Best-seller</span>}
          </div>
          <div className="modal-add">
            {cartQty > 0 ? (
              <QtyStepper value={cartQty} onChange={(q) => onSetQty(product.ref, q)} />
            ) : (
              <button className="send-btn" onClick={() => onAdd(product.ref)}><Icon.Bag /> Ajouter au bon de commande</button>
            )}
            {cartQty > 0 && <span style={{fontSize:13, color:'var(--ink-3)'}}>Sous-total : <strong style={{color:'var(--ink)', fontFamily:'Fraunces, serif', fontSize:16, fontWeight:400}}>{fmt(cartQty * product.price)}</strong></span>}
          </div>
          {cobought.length > 0 && (
            <div className="cobought">
              <div className="cobought-title">Souvent commandés ensemble</div>
              <div className="cobought-list">
                {cobought.slice(0, 3).map(p => (
                  <button key={p.ref} className="cobought-card" onClick={() => onSwitch(p)}>
                    <img src={p.img} alt={p.name} />
                    <div className="n">{p.name}</div>
                    <div className="p">{p.ref} · {fmt(p.price)}</div>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Expose
Object.assign(window, { QtyStepper, ProductCard, QuickViewModal, Icon, fmt, fmt0 });
