// Hero — gallery + buy box. Subscription/quantity/variant pickers wired up.

const PRODUCT = {
  name: "Sleep Truffles",
  pack: "10 Count Pouch",
  variants: [
    { id: "original", label: "Original Cocoa", dot: "cocoa" },
    { id: "mint",     label: "Dark Mint",      dot: "gold" },
  ],
  plans: [
    {
      id: "sub-monthly",
      label: "Monthly subscription",
      sub: "1 pouch every 30 days · skip or cancel anytime",
      now: 49,
      was: 65,
      saveLabel: "SAVE 25%",
    },
    {
      id: "sub-bulk",
      label: "Bulk subscription",
      sub: "3 pouches every 60 days · best value",
      now: 129,
      was: 195,
      saveLabel: "SAVE 34%",
    },
    {
      id: "onetime",
      label: "One-time purchase",
      sub: "No commitment, no auto-renew",
      now: 65,
      was: null,
      saveLabel: null,
    },
  ],
  thumbs: ["Front", "Back", "Open", "Truffle", "Lifestyle"],
};

function Stars({ value = 4.9, count = 1247 }) {
  const filled = Math.round(value);
  return (
    <div className="stars">
      <span className="stars-mark" aria-label={`${value} out of 5 stars`}>
        {[0,1,2,3,4].map(i => <IconStar key={i} filled={i < filled} size={13} />)}
      </span>
      <u>{count.toLocaleString()} reviews</u>
    </div>
  );
}

function Gallery({ heroLayout }) {
  const [active, setActive] = React.useState(0);
  return (
    <div className="gallery" style={heroLayout === "stacked" ? { gridTemplateColumns: "1fr" } : undefined}>
      {heroLayout !== "stacked" && (
        <div className="gallery-thumbs">
          {PRODUCT.thumbs.map((t, i) => (
            <div key={i}
                 className={`thumb ${i === active ? "active" : ""}`}
                 onClick={() => setActive(i)}
                 aria-label={`View ${t}`}>
              <div className="thumb-inner">{t}</div>
            </div>
          ))}
        </div>
      )}
      <div className="gallery-main" data-comment-anchor="hero-image">
        <div className="badge-stack">
          <div className="badge-medal">
            <b>#1</b>
            Plant-based<br/>sleep aid
          </div>
          <div className="badge-pill">10ct Pouch</div>
        </div>
        <div className="placeholder-img">
          <span style={{
            fontFamily: "var(--font-display)",
            fontSize: "clamp(48px, 6vw, 78px)",
            fontWeight: 600,
            letterSpacing: "-.04em",
            color: "rgba(0,0,0,.08)",
            textAlign: "center",
            lineHeight: .95,
          }}>
            Aulv<br/>
            <span style={{fontSize: ".4em", letterSpacing: ".1em", textTransform: "uppercase", opacity: .9}}>
              Sleep Truffles
            </span>
          </span>
          <span className="ph-label">Product · {PRODUCT.thumbs[active]}</span>
        </div>
      </div>
      {heroLayout === "stacked" && (
        <div className="gallery-thumbs" style={{ flexDirection: "row", gridColumn: "1/-1" }}>
          {PRODUCT.thumbs.map((t, i) => (
            <div key={i}
                 className={`thumb ${i === active ? "active" : ""}`}
                 onClick={() => setActive(i)}
                 style={{ flex: 1 }}
                 aria-label={`View ${t}`}>
              <div className="thumb-inner">{t}</div>
            </div>
          ))}
        </div>
      )}
      <div className="gallery-cred">
        <div className="cred">
          <span className="cred-dot"><IconLeaf size={11} /></span>
          Living-Soil Grown
        </div>
        <div className="cred">
          <span className="cred-dot"><IconShield size={11} /></span>
          Lab Tested · COA available
        </div>
      </div>
    </div>
  );
}

function PlanRow({ plan, selected, onSelect }) {
  return (
    <div className={`plan ${selected ? "on" : ""}`} role="radio" aria-checked={selected}
         tabIndex={0}
         onClick={onSelect}
         onKeyDown={(e) => (e.key === " " || e.key === "Enter") && (e.preventDefault(), onSelect())}>
      <span className="plan-radio" />
      <div className="plan-body">
        <div className="plan-row1">
          {plan.label}
          {plan.saveLabel && <span className="save-tag">{plan.saveLabel}</span>}
        </div>
        <div className="plan-row2">{plan.sub}</div>
      </div>
      <div className="plan-price">
        <div className="price-now">${plan.now}</div>
        {plan.was != null && <div className="price-was">${plan.was}</div>}
      </div>
    </div>
  );
}

function BuyBox({ onAdd, density }) {
  const [planId, setPlanId] = React.useState("sub-bulk");
  const [variantId, setVariantId] = React.useState("original");
  const [qty, setQty] = React.useState(1);
  const [hours, setHours] = React.useState(7);
  const [mins, setMins] = React.useState(42);

  const plan = PRODUCT.plans.find(p => p.id === planId);
  const variant = PRODUCT.variants.find(v => v.id === variantId);

  // ticking countdown
  React.useEffect(() => {
    const t = setInterval(() => {
      setMins(m => {
        if (m === 0) { setHours(h => Math.max(0, h - 1)); return 59; }
        return m - 1;
      });
    }, 60000);
    return () => clearInterval(t);
  }, []);

  const dense = density === "compact";
  const roomy = density === "roomy";
  const buyStyle = {
    "--buy-pad": dense ? "14px" : roomy ? "24px" : "20px",
    "--buy-gap": dense ? "10px" : roomy ? "16px" : "14px",
    gap: dense ? "12px" : roomy ? "22px" : "18px",
  };

  const handleAdd = () => {
    onAdd({
      product: PRODUCT.name,
      pack: PRODUCT.pack,
      variant: variant.label,
      planId: plan.id,
      planLabel: plan.label,
      qty,
      price: plan.now,
    });
  };

  return (
    <div className="buy" style={buyStyle} data-comment-anchor="buy-box">
      <Stars value={4.9} count={1247} />
      <div>
        <h1 className="product-title">Sleep Truffles, 10 Count</h1>
        <div className="sub-line">
          Plant-compound chocolates for your endocannabinoid sleep system.
          {" "}<a href="#science">See the science</a>
        </div>
      </div>

      <div className="variant-row" role="radiogroup" aria-label="Flavor">
        {PRODUCT.variants.map(v => (
          <button key={v.id}
                  className={`variant ${variantId === v.id ? "on" : ""}`}
                  role="radio"
                  aria-checked={variantId === v.id}
                  onClick={() => setVariantId(v.id)}>
            <span className={`dot ${v.dot}`} />
            {v.label}
          </button>
        ))}
      </div>

      <div className="plan-stack" role="radiogroup" aria-label="Purchase plan">
        {PRODUCT.plans.map(p => (
          <PlanRow key={p.id} plan={p} selected={planId === p.id} onSelect={() => setPlanId(p.id)} />
        ))}
      </div>

      <div className="member">
        <div className="member-icon"><IconShield size={16} /></div>
        <div>
          <b>Free Member Gifts</b> · $40 value
          <div style={{ color: "var(--muted)", fontSize: 11.5, marginTop: 2 }}>
            Sleep mask + travel tin with first subscription
          </div>
        </div>
        <a href="#">Learn more</a>
      </div>

      <div className="qty-cta-row">
        <div className="qty" role="group" aria-label="Quantity">
          <button onClick={() => setQty(q => Math.max(1, q - 1))} aria-label="Decrease">−</button>
          <span className="qty-val">{qty}</span>
          <button onClick={() => setQty(q => Math.min(99, q + 1))} aria-label="Increase">+</button>
        </div>
        <button className="cta-add" onClick={handleAdd}>
          Add to Cart
          <span style={{ opacity: .7, fontWeight: 400 }}>· ${plan.now * qty}</span>
        </button>
      </div>

      <div className="countdown">
        Ships in <b>{String(hours).padStart(2,"0")}h {String(mins).padStart(2,"0")}m</b>
        {" "}· Free shipping on orders over $99 · Money-back guarantee
      </div>

      <div className="sub-includes">
        <h4>Your subscription includes</h4>
        <ul>
          <li><IconCheck size={14} /> Free shipping &amp; carbon-neutral delivery</li>
          <li><IconCheck size={14} /> Member rewards &amp; restock reminders</li>
          <li><IconCheck size={14} /> 30-day money-back guarantee</li>
          <li><IconCheck size={14} /> Pause or cancel anytime</li>
        </ul>
      </div>

      <button className="view-supp">View Supplement Facts <IconChevron size={12} /></button>

      <div className="expanders">
        <details className="expander">
          <summary>What is Sleep Truffles?<span className="plus" /></summary>
          <div className="expander-body">
            Sleep Truffles are single-serve chocolates crafted from Ghirardelli cocoa,
            organic coconut oil, and living-soil grown ancient landrace cannabis strains.
            Each truffle delivers a precise blend of plant cannabinoids and terpenes that
            support your body's natural endocannabinoid sleep response — non-habit forming,
            no morning grog.
          </div>
        </details>
        <details className="expander">
          <summary>Who it's for<span className="plus" /></summary>
          <div className="expander-body">
            Adults seeking a plant-based, food-grade alternative to pharmaceutical sleep aids
            or melatonin loops. Especially helpful for travelers, shift-adjacent sleepers,
            and anyone who wants to fall asleep faster and wake clear-headed.
          </div>
        </details>
        <details className="expander">
          <summary>Benefits<span className="plus" /></summary>
          <div className="expander-body">
            Faster onset, deeper sleep architecture, and a calm wind-down without next-morning
            heaviness. Most members report a noticeable shift within 5 nights.
          </div>
        </details>
        <details className="expander">
          <summary>How to use<span className="plus" /></summary>
          <div className="expander-body">
            45 minutes before bed, eat one truffle. Pair with low light and your favorite
            wind-down ritual. Begin with a half truffle if you're new to plant cannabinoids.
          </div>
        </details>
        <details className="expander">
          <summary>Quality &amp; certifications<span className="plus" /></summary>
          <div className="expander-body">
            Third-party lab tested for purity and potency. Certificates of Analysis available
            with every batch. cGMP-compliant facility. Vegan, gluten-free, non-GMO.
          </div>
        </details>
      </div>

      <div className="travel-cta">
        <div>
          <h5>Heading out of town?</h5>
          <p>Try our 3-pack travel tin — TSA-friendly, individually wrapped.</p>
          <button className="pill-btn">Shop travel pack →</button>
        </div>
        <div className="travel-img">Tin · 3ct</div>
      </div>

      <div className="returns-line">
        Not for you? <a href="#">Return any time within 30 days</a>. No questions asked.
      </div>
    </div>
  );
}

function Hero({ onAdd, density, heroLayout }) {
  return (
    <div className="container">
      <div className="hero" style={heroLayout === "narrow" ? { gridTemplateColumns: "1fr 1fr" } : undefined}>
        <Gallery heroLayout={heroLayout} />
        <BuyBox onAdd={onAdd} density={density} />
      </div>
    </div>
  );
}

Object.assign(window, { Hero, PRODUCT });
