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

const STRAINS = [
  { name: "Honeyrock OG",      type: "Pure Indica",  thc: "28%", terp: "Amber Citrus",
    blurb: "Sticky amber rosin with a sleepy candied-citrus finish.", tone: "gold" },
  { name: "Golden Hibernation", type: "Indica",       thc: "31%", terp: "Candied Pine",
    blurb: "Heavy resin heads, deep canopy calm, dusk-purple bud.", tone: "amber" },
  { name: "Pollen Empress",     type: "Indica-dom",   thc: "27%", terp: "Lavender Cream",
    blurb: "Royal terpene stack — lavender, cream, warm honey.", tone: "sage" },
  { name: "Amber Den Kush",     type: "Pure Indica",  thc: "30%", terp: "Gassy Honey",
    blurb: "Record rosin yield. Gassy honey nose, velvet sit-down.", tone: "amber" },
  { name: "Sunset Grizzly",     type: "Indica",       thc: "29%", terp: "Sweet Earth",
    blurb: "Sweet earth & stonefruit. The den-keeper's nightcap.", tone: "gold" },
];

/* offset (relative to active) -> 3D transform preset. Center is reserved for the bear,
   so the featured panel sits to the right; flanks recede left & right. */
const POS = {
  "0":  { x: 340,  z: 60,   ry: -10, s: 1.0,  o: 1,    blur: 0 },
  "1":  { x: 500,  z: -170, ry: -26, s: 0.78, o: 0.46, blur: 1.5 },
  "2":  { x: 590,  z: -330, ry: -33, s: 0.60, o: 0.18, blur: 3 },
  "-1": { x: -380, z: -170, ry: 26,  s: 0.78, o: 0.46, blur: 1.5 },
  "-2": { x: -540, z: -330, ry: 33,  s: 0.60, o: 0.18, blur: 3 },
};

function relOffset(i, active, n) {
  let d = i - active;
  if (d > n / 2) d -= n;
  if (d < -n / 2) d += n;
  return d;
}

function StrainPanel({ s, offset, onClick, mobile }) {
  const p = mobile ? null : (POS[String(offset)] || { x: 0, z: -560, ry: 0, s: 0.4, o: 0, blur: 6 });
  const featured = offset === 0;
  const style = mobile ? {} : {
    transform: `translate(-50%,-50%) translateX(${p.x}px) translateZ(${p.z}px) rotateY(${p.ry}deg) scale(${p.s})`,
    opacity: p.o,
    filter: p.blur ? `blur(${p.blur}px)` : "none",
    zIndex: 20 - Math.abs(offset),
    pointerEvents: Math.abs(offset) > 1 ? "none" : "auto",
  };
  return (
    <article
      className={`panel panel--${s.tone} ${featured ? "is-featured" : ""} ${mobile ? "panel--mobile" : ""}`}
      style={style}
      onClick={() => !featured && onClick && onClick()}
    >
      <div className="panel-sheen" />
      <div className="panel-top">
        <span className="eyebrow">Reserve Genetics</span>
        <span className={`leaf-dot leaf-dot--${s.tone}`} />
      </div>
      <h3 className="panel-name street">{s.name}</h3>
      <p className="panel-blurb">{s.blurb}</p>
      <div className="panel-chips">
        <span className="chip">{s.type}</span>
        <span className="chip chip--solid">THC {s.thc}</span>
        <span className="chip">{s.terp}</span>
      </div>
      <div className="panel-foot">
        <span className="panel-link">View genetics
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </span>
      </div>
    </article>
  );
}

function Hero() {
  const [active, setActive] = useState(0);
  const [mobile, setMobile] = useState(false);
  const n = STRAINS.length;

  useEffect(() => {
    const mq = window.matchMedia("(max-width: 760px)");
    const update = () => setMobile(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  const go = useCallback((dir) => setActive(a => (a + dir + n) % n), [n]);

  // Swipe / drag to advance (no autoplay — user-driven only).
  const drag = useRef(null);
  const onPointerDown = (e) => { drag.current = { x: e.clientX, t: Date.now() }; };
  const onPointerUp = (e) => {
    const d = drag.current; drag.current = null;
    if (!d) return;
    const dx = e.clientX - d.x;
    if (Math.abs(dx) > 40 && Date.now() - d.t < 800) go(dx < 0 ? 1 : -1);
  };

  useEffect(() => {
    const onKey = (e) => { if (e.key === "ArrowRight") go(1); if (e.key === "ArrowLeft") go(-1); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [go]);

  return (
    <section className="hero">
      <div className="stage" role="region" aria-label="Featured genetics carousel"
           onPointerDown={onPointerDown} onPointerUp={onPointerUp}
           style={{ touchAction: "pan-y" }}>
        <div className="bear-glow" />
        <img className="bear" src="assets/goldenbear.png" alt="Satocrop golden bear holding honeycomb" />
        <div className="bear-shadow" />

        <div className={`carousel ${mobile ? "carousel--mobile" : ""}`}>
          {mobile
            ? <StrainPanel s={STRAINS[active]} offset={0} mobile />
            : STRAINS.map((s, i) => (
                <StrainPanel key={s.name} s={s} offset={relOffset(i, active, n)} onClick={() => setActive(i)} />
              ))
          }
        </div>

        <button className="stage-arrow stage-arrow--left" aria-label="Previous" onClick={() => go(-1)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M15 5l-7 7 7 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
        <button className="stage-arrow stage-arrow--right" aria-label="Next" onClick={() => go(1)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </button>
      </div>

      <div className="dots">
        {STRAINS.map((s, i) => (
          <button key={s.name} className={`dot ${i === active ? "is-active" : ""}`}
                  aria-label={`Show ${s.name}`} onClick={() => setActive(i)} />
        ))}
      </div>
    </section>
  );
}

window.Hero = Hero;
