// Vue détail produit avec scroll-reveal

const useReveal = () => {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.reveal--in)");
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("reveal--in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -60px 0px" });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
};

const ProductMedia = ({ product, size }) => {
  if (product.image) {
    return <img src={product.image} alt={product.name} />;
  }
  return <div className="product__emoji" style={size ? { fontSize: size } : {}}>{product.emoji}</div>;
};

const ProductDetail = ({ product, open, onClose, onAdd }) => {
  const scrollRef = React.useRef(null);
  const progressRef = React.useRef(null);
  const [weight, setWeight] = React.useState("3g");
  const [qty, setQty] = React.useState(1);

  useReveal();

  React.useEffect(() => {
    if (open) {
      document.body.style.overflow = "hidden";
      setWeight("5g"); setQty(1);
      requestAnimationFrame(() => {
        if (scrollRef.current) scrollRef.current.scrollTop = 0;
      });
    } else {
      document.body.style.overflow = "";
    }
    return () => { document.body.style.overflow = ""; };
  }, [open, product?.id]);

  const onScroll = (e) => {
    const el = e.target;
    const max = el.scrollHeight - el.clientHeight;
    const pct = max > 0 ? el.scrollTop / max : 0;
    if (progressRef.current) progressRef.current.style.transform = `scaleX(${pct})`;
  };

  if (!product) return null;

  const price = product.prices[weight];
  const total = (price * qty).toFixed(2).replace(".", ",");

  return (
    <div
      className={"detail " + (open ? "detail--open" : "")}
      onScroll={onScroll}
      ref={scrollRef}
      data-screen-label="04 Détail produit"
    >
      <div className="detail__progress" ref={progressRef}></div>
      <button className="detail__close" onClick={onClose} aria-label="Fermer">✕</button>

      {/* HERO PRODUIT */}
      <section className="detail-hero">
        <div className="detail-hero__media reveal">
          <div className="detail-hero__rings">
            <div className="detail-hero__ring" style={{ animationDelay: "0s" }}></div>
            <div className="detail-hero__ring" style={{ animationDelay: "1.1s" }}></div>
            <div className="detail-hero__ring" style={{ animationDelay: "2.2s" }}></div>
          </div>
          <div className="detail-hero__orb">
            <div className="detail-hero__orb-content">
              <ProductMedia product={product} size="8rem" />
            </div>
          </div>
        </div>

        <div className="detail-hero__info">
          <div className="detail-hero__crumbs reveal">Boutique → {product.typeFull} → {product.name}</div>
          <h1 className="detail-hero__name reveal reveal--d1">
            {product.nameRest && <span>{product.nameRest} </span>}
            <em>{product.italic}</em>
          </h1>
          <p className="detail-hero__tagline reveal reveal--d2">{product.tagline}</p>
          <p className="detail-hero__desc reveal reveal--d2">{product.description}</p>

          <div className="detail-hero__specs reveal reveal--d3">
            <div className="spec">
              <div className="spec__val">{product.cbd}%</div>
              <div className="spec__lbl">CBD</div>
            </div>
            <div className="spec">
              <div className="spec__val">&lt;{product.thc}%</div>
              <div className="spec__lbl">THC</div>
            </div>
            <div className="spec">
              <div className="spec__val" style={{ fontSize: 14, paddingTop: 6, letterSpacing: "0.06em" }}>
                {product.type}
              </div>
              <div className="spec__lbl">Culture</div>
            </div>
            <div className="spec">
              <div className="spec__val" style={{ fontSize: 14, paddingTop: 6, letterSpacing: "0.06em" }}>UE</div>
              <div className="spec__lbl">Légal</div>
            </div>
          </div>

          {product.stock && (
            <div className={"detail-hero__stock reveal reveal--d3" + (product.inStock ? "" : " detail-hero__stock--out")}>
              <span className="detail-hero__stock-dot"></span>{product.stock}
            </div>
          )}

          <div className="weight-select reveal reveal--d3">
            {Object.entries(product.prices).map(([w, p]) => (
              <button
                key={w}
                className={"weight-select__btn " + (weight === w ? "weight-select__btn--active" : "")}
                onClick={() => setWeight(w)}
              >
                <span className="weight-select__g">{w}</span>
                <span className="weight-select__p">€{p.toFixed(2).replace(".", ",")}</span>
              </button>
            ))}
          </div>

          <p className="detail-hero__quantity-note reveal reveal--d3">
            Pour une autre quantité, faites la demande par mail :{" "}
            <a href="mailto:mrrodcbd@yahoo.com">mrrodcbd@yahoo.com</a>
          </p>

          {product.inStock ? (
            <div className="detail-hero__purchase reveal reveal--d4">
              <div className="qty">
                <button className="qty__btn" onClick={() => setQty(Math.max(1, qty - 1))} aria-label="Moins">−</button>
                <span className="qty__value">{qty}</span>
                <button className="qty__btn" onClick={() => setQty(qty + 1)} aria-label="Plus">+</button>
              </div>
              <button
                className="btn btn--gold detail-hero__add"
                onClick={() => onAdd(product, weight, qty)}
              >
                Ajouter — €{total}
                <span className="btn__arrow">→</span>
              </button>
            </div>
          ) : (
            <div className="detail-hero__purchase reveal reveal--d4">
              <button className="btn detail-hero__add detail-hero__add--out" disabled>
                Victime de son succès — bientôt de retour
              </button>
            </div>
          )}
        </div>
      </section>

      {/* ORIGINE */}
      <section className="detail-section detail-origin">
        <div className="detail-section__inner detail-origin__inner">
          <div className="detail-origin__media reveal">
            <ProductMedia product={product} />
            <div className="detail-origin__caption">{product.origin}</div>
          </div>
          <div>
            <div className="detail-origin__label reveal">Origine & culture</div>
            <h2 className="detail-origin__title reveal reveal--d1">
              Du <em>champ</em> au<br/>sachet.
            </h2>
            <p className="detail-origin__text reveal reveal--d2">{product.description}</p>
            <p className="detail-origin__text reveal reveal--d3" style={{ color: "var(--gold-light)", fontStyle: "italic" }}>
              Chaque lot est tracé, analysé en laboratoire indépendant français.
              Le COA est consultable sur demande.
            </p>
          </div>
        </div>
      </section>

      {/* EFFETS */}
      <section className="detail-section detail-effects">
        <div className="detail-section__inner">
          <div className="detail-effects__header reveal">
            <div className="section-eyebrow">Ressenti attendu</div>
            <h2 className="section-title" style={{ marginTop: 16 }}>
              Ce que <em>vous</em> allez ressentir
            </h2>
          </div>
          <div className="detail-effects__grid">
            {product.effects.map((eff, i) => (
              <div key={i} className={`effect reveal reveal--d${(i % 4) + 1}`}>
                <div className="effect__icon"><Icon kind={eff.icon} /></div>
                <div className="effect__name">{eff.name}</div>
                <div className="effect__desc">{eff.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* AROMES */}
      <section className="detail-section detail-aroma">
        <div className="detail-section__inner detail-aroma__inner">
          <div>
            <div className="section-eyebrow reveal">Profil aromatique</div>
            <h2 className="section-title reveal reveal--d1" style={{ marginTop: 16 }}>
              Cinq <em>notes</em>,<br/>une seule fleur.
            </h2>
            <p className="section-lead reveal reveal--d2" style={{ marginTop: 24, maxWidth: 500 }}>
              Le bouquet terpénique de cette variété a été analysé sur GC-MS.
              Voici les arômes dominants identifiés — ouvrez votre sachet, fermez les yeux,
              ils sont tous là.
            </p>
          </div>
          <div className="aroma-wheel reveal reveal--d3">
            <div className="aroma-wheel__ring"></div>
            <div className="aroma-wheel__ring aroma-wheel__ring--inner"></div>
            <div className="aroma-wheel__ring aroma-wheel__ring--core"></div>
            {product.aromas.map((a, i) => {
              const total = product.aromas.length;
              const angle = (i / total) * Math.PI * 2 - Math.PI / 2;
              const radius = 42;
              const x = 50 + Math.cos(angle) * radius;
              const y = 50 + Math.sin(angle) * radius;
              return (
                <div
                  key={a}
                  className="aroma-tag"
                  style={{
                    left: `${x}%`,
                    top: `${y}%`,
                    transform: "translate(-50%, -50%)",
                  }}
                >{a}</div>
              );
            })}
          </div>
        </div>
      </section>

      {/* CERTIFICATIONS */}
      <section className="detail-section detail-cert">
        <div className="detail-section__inner">
          <div className="detail-cert__header reveal">
            <div className="section-eyebrow">Transparence</div>
            <h2 className="section-title" style={{ marginTop: 16 }}>
              Trois <em>preuves</em>.<br/>Zéro promesse en l'air.
            </h2>
          </div>
          <div className="detail-cert__grid">
            <div className="cert-card reveal reveal--d1">
              <div className="cert-card__seal">✓</div>
              <div className="cert-card__name">Analyse COA</div>
              <div className="cert-card__desc">
                Certificat d'analyse complet : taux CBD, THC, terpènes, pesticides, métaux lourds.
                Effectué par un laboratoire français indépendant.
              </div>
            </div>
            <div className="cert-card reveal reveal--d2">
              <div className="cert-card__seal" style={{ fontSize: 13 }}>&lt;0.3</div>
              <div className="cert-card__name">THC conforme UE</div>
              <div className="cert-card__desc">
                Tous nos lots sont testés et garantis sous le seuil réglementaire européen
                de 0,3% de THC. Légalement commercialisable.
              </div>
            </div>
            <div className="cert-card reveal reveal--d3">
              <div className="cert-card__seal"><Icon kind="leaf2" size={18} /></div>
              <div className="cert-card__name">Sans pesticides</div>
              <div className="cert-card__desc">
                Pas de pesticides, pas d'herbicides chimiques, pas de métaux lourds.
                Nos partenaires cultivateurs sont sélectionnés sur ces critères stricts.
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* CTA FINAL */}
      <section className="detail-section" style={{ background: "var(--dark2)", borderTop: "1px solid var(--border)" }}>
        <div className="detail-section__inner reveal" style={{ textAlign: "center" }}>
          <div style={{
            background: "var(--dark)",
            border: "1px solid var(--border-gold)",
            padding: "72px 48px",
            position: "relative",
          }}>
            <div className="section-eyebrow" style={{ marginBottom: 18 }}>{product.inStock ? "Prêt à essayer ?" : "Bientôt de retour"}</div>
            <h3 className="h-display" style={{ fontSize: "clamp(36px, 4vw, 56px)", marginBottom: 32 }}>
              {product.nameRest && <span>{product.nameRest} </span>}<em>{product.italic}</em>
              <br/>
              <span style={{ fontSize: "0.5em", color: "var(--muted)", fontStyle: "normal" }}>
                {product.inStock ? `${weight} · €${total}` : "Victime de son succès"}
              </span>
            </h3>
            {product.inStock ? (
              <button className="btn btn--gold" onClick={() => onAdd(product, weight, qty)}>
                Ajouter au panier
                <span className="btn__arrow">→</span>
              </button>
            ) : (
              <button className="btn detail-hero__add--out" disabled>Bientôt de retour</button>
            )}
          </div>
        </div>
      </section>
    </div>
  );
};

Object.assign(window, { ProductDetail, ProductMedia });
