/* Good Haveit — Coming Soon (single-file React) */
const { useEffect, useRef, useState, useMemo } = React;

// ─── Particle field ─────────────────────────────────────────
function ParticleField() {
  const canvasRef = useRef(null);
  const rafRef = useRef(0);
  const mouseRef = useRef({ x: -9999, y: -9999 });

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d");
    let dpr = Math.min(window.devicePixelRatio || 1, 2);
    let w = 0, h = 0, particles = [];

    const resize = () => {
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      const count = Math.max(40, Math.floor((w * h) / 28000));
      particles = Array.from({ length: count }, () => spawn());
    };

    const spawn = () => {
      const kind = Math.random();
      // 70% tiny dot, 20% small ring, 10% terracotta speck
      let type = "dot";
      if (kind > 0.7 && kind < 0.9) type = "ring";
      else if (kind >= 0.9) type = "speck";
      return {
        x: Math.random() * w,
        y: Math.random() * h,
        vx: (Math.random() - 0.5) * 0.12,
        vy: -0.08 - Math.random() * 0.18,
        r: type === "ring" ? 3 + Math.random() * 3 : 0.6 + Math.random() * 1.6,
        a: 0.15 + Math.random() * 0.35,
        type,
        rot: Math.random() * Math.PI,
        rotV: (Math.random() - 0.5) * 0.005,
      };
    };

    const tick = () => {
      ctx.clearRect(0, 0, w, h);
      const mx = mouseRef.current.x;
      const my = mouseRef.current.y;

      for (const p of particles) {
        // gentle repulsion from cursor
        const dx = p.x - mx;
        const dy = p.y - my;
        const d2 = dx * dx + dy * dy;
        if (d2 < 14000) {
          const f = (1 - d2 / 14000) * 0.6;
          const inv = 1 / Math.max(1, Math.sqrt(d2));
          p.vx += dx * inv * f * 0.05;
          p.vy += dy * inv * f * 0.05;
        }
        p.vx *= 0.985;
        p.vy = p.vy * 0.99 - 0.0008; // slight upward drift
        p.x += p.vx;
        p.y += p.vy;
        p.rot += p.rotV;

        if (p.y < -10) { p.y = h + 10; p.x = Math.random() * w; }
        if (p.y > h + 10) { p.y = -10; }
        if (p.x < -10) p.x = w + 10;
        if (p.x > w + 10) p.x = -10;

        ctx.save();
        ctx.translate(p.x, p.y);
        if (p.type === "dot") {
          ctx.fillStyle = `rgba(58, 42, 26, ${p.a})`;
          ctx.beginPath(); ctx.arc(0, 0, p.r, 0, Math.PI * 2); ctx.fill();
        } else if (p.type === "ring") {
          ctx.strokeStyle = `rgba(42, 74, 58, ${p.a * 0.8})`;
          ctx.lineWidth = 0.8;
          ctx.beginPath(); ctx.arc(0, 0, p.r, 0, Math.PI * 2); ctx.stroke();
        } else {
          ctx.rotate(p.rot);
          ctx.fillStyle = `rgba(212, 130, 58, ${p.a + 0.15})`;
          ctx.fillRect(-p.r, -p.r * 0.35, p.r * 2, p.r * 0.7);
        }
        ctx.restore();
      }
      rafRef.current = requestAnimationFrame(tick);
    };

    const onMove = (e) => {
      mouseRef.current.x = e.clientX;
      mouseRef.current.y = e.clientY;
    };
    const onLeave = () => { mouseRef.current.x = -9999; mouseRef.current.y = -9999; };

    resize();
    tick();
    window.addEventListener("resize", resize);
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseleave", onLeave);
    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener("resize", resize);
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseleave", onLeave);
    };
  }, []);

  return <canvas id="particles" ref={canvasRef} />;
}

// ─── Countdown ──────────────────────────────────────────────
function useCountdown(target) {
  const [now, setNow] = useState(() => Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  const diff = Math.max(0, target - now);
  const s = Math.floor(diff / 1000);
  return {
    days: Math.floor(s / 86400),
    hrs: Math.floor((s % 86400) / 3600),
    mins: Math.floor((s % 3600) / 60),
    secs: s % 60,
  };
}

function Countdown({ target }) {
  const { days, hrs, mins, secs } = useCountdown(target);
  const seg = (n, l) => (
    <div className="seg">
      <div className="num">{String(n).padStart(2, "0")}</div>
      <div className="lbl">{l}</div>
    </div>
  );
  return (
    <div className="countdown">
      {seg(days, "Days")}
      {seg(hrs, "Hours")}
      {seg(mins, "Minutes")}
      {seg(secs, "Seconds")}
    </div>
  );
}

// ─── Magnetic button ────────────────────────────────────────
function MagneticCTA({ children, onClick }) {
  const wrapRef = useRef(null);
  useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    const STRENGTH = 0.35;
    const RADIUS = 140;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = e.clientX - cx;
      const dy = e.clientY - cy;
      const d = Math.hypot(dx, dy);
      if (d < RADIUS) {
        const k = (1 - d / RADIUS) * STRENGTH;
        el.style.transform = `translate(${dx * k}px, ${dy * k}px)`;
      } else {
        el.style.transform = "translate(0, 0)";
      }
    };
    const onLeave = () => { el.style.transform = "translate(0, 0)"; };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseleave", onLeave);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseleave", onLeave);
    };
  }, []);
  return (
    <div className="magnet-wrap" ref={wrapRef}>
      <button className="cta" onClick={onClick}>
        {children}
        <svg className="arrow" viewBox="0 0 14 14" fill="none">
          <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>
    </div>
  );
}

// ─── Reveal-on-scroll wrapper ───────────────────────────────
function Reveal({ children, delay = 0, as: Tag = "div", className = "", ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          setTimeout(() => setShown(true), delay);
          obs.disconnect();
        }
      });
    }, { threshold: 0.15 });
    obs.observe(el);
    return () => obs.disconnect();
  }, [delay]);
  return (
    <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} {...rest}>
      {children}
    </Tag>
  );
}

// ─── Laddu cross-section illustration ───────────────────────
function LadduArt() {
  const wrapRef = useRef(null);
  const innerRef = useRef(null);
  const outerRef = useRef(null);

  // gentle cursor-driven parallax on the laddu
  useEffect(() => {
    const wrap = wrapRef.current;
    const inner = innerRef.current;
    const outer = outerRef.current;
    if (!wrap || !inner || !outer) return;
    let raf = 0;
    let tx = 0, ty = 0, cx = 0, cy = 0;
    const onMove = (e) => {
      const r = wrap.getBoundingClientRect();
      const x = (e.clientX - (r.left + r.width / 2)) / r.width;
      const y = (e.clientY - (r.top + r.height / 2)) / r.height;
      tx = x; ty = y;
    };
    const tick = () => {
      cx += (tx - cx) * 0.06;
      cy += (ty - cy) * 0.06;
      outer.style.transform = `translate(${cx * 14}px, ${cy * 14}px)`;
      inner.style.transform = `translate(${cx * 28}px, ${cy * 28}px)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    window.addEventListener("mousemove", onMove);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("mousemove", onMove);
    };
  }, []);

  // deterministic speckle positions
  const outerSpecks = useMemo(() => {
    const arr = [];
    const seed = (n) => Math.sin(n * 9301 + 49297) * 233280;
    for (let i = 0; i < 90; i++) {
      const a = (seed(i) % 1) * Math.PI * 2;
      const rr = 165 + ((seed(i + 1) % 1) * 60);
      arr.push({
        x: 250 + Math.cos(a) * rr,
        y: 250 + Math.sin(a) * rr,
        r: 1 + ((seed(i + 2) % 1) * 2.4),
        c: i % 5 === 0 ? "#3a2a18" : i % 7 === 0 ? "#7a3f1f" : "#5a3a1f",
        o: 0.5 + ((seed(i + 3) % 1) * 0.4),
      });
    }
    return arr;
  }, []);
  const innerSpecks = useMemo(() => {
    const arr = [];
    const seed = (n) => Math.sin(n * 7919 + 113) * 100000;
    for (let i = 0; i < 28; i++) {
      const a = (seed(i) % 1) * Math.PI * 2;
      const rr = ((seed(i + 1) % 1) * 70);
      arr.push({
        x: 250 + Math.cos(a) * rr,
        y: 250 + Math.sin(a) * rr,
        r: 1 + ((seed(i + 2) % 1) * 2),
      });
    }
    return arr;
  }, []);

  // ingredient orbit ─ small icons floating around the laddu
  const ingredients = [
    { lbl: "Almond",  a: -90 },
    { lbl: "Cashew",  a: -45 },
    { lbl: "Makhana", a: 0 },
    { lbl: "Dates",   a: 45 },
    { lbl: "Sesame",  a: 90 },
    { lbl: "Coconut", a: 135 },
    { lbl: "Honey",   a: 180 },
    { lbl: "Bengal Gram", a: 225 },
  ];

  return (
    <div className="product-art" ref={wrapRef}>
      <svg viewBox="0 0 500 500" style={{ width: "100%", height: "100%", position: "relative", zIndex: 2 }}>
        {/* shadow */}
        <ellipse cx="250" cy="430" rx="160" ry="14" fill="#1a1410" opacity="0.08" />

        {/* OUTER laddu */}
        <g ref={outerRef} style={{ transformOrigin: "250px 250px" }}>
          <defs>
            <radialGradient id="outerGrad" cx="42%" cy="38%" r="62%">
              <stop offset="0%" stopColor="#e6a368" />
              <stop offset="55%" stopColor="#c47535" />
              <stop offset="100%" stopColor="#7a3f1f" />
            </radialGradient>
            <radialGradient id="innerGrad" cx="40%" cy="36%" r="62%">
              <stop offset="0%" stopColor="#5b3a26" />
              <stop offset="60%" stopColor="#2e1a10" />
              <stop offset="100%" stopColor="#160c08" />
            </radialGradient>
            <radialGradient id="highlight" cx="50%" cy="50%" r="50%">
              <stop offset="0%" stopColor="white" stopOpacity="0.45" />
              <stop offset="100%" stopColor="white" stopOpacity="0" />
            </radialGradient>
          </defs>

          <circle cx="250" cy="250" r="200" fill="url(#outerGrad)" />
          <circle cx="250" cy="250" r="200" fill="url(#highlight)" opacity="0.55" style={{ mixBlendMode: "screen" }} />
          {/* subtle rim */}
          <circle cx="250" cy="250" r="200" fill="none" stroke="#3a1f10" strokeWidth="1" opacity="0.3" />
          {/* outer specks (nuts/seeds texture) */}
          {outerSpecks.map((s, i) => (
            <circle key={i} cx={s.x} cy={s.y} r={s.r} fill={s.c} opacity={s.o} />
          ))}
        </g>

        {/* INNER core (cross-section reveal) */}
        <g ref={innerRef} style={{ transformOrigin: "250px 250px" }}>
          <circle cx="250" cy="250" r="92" fill="url(#innerGrad)" />
          {/* gloss for chocolate */}
          <ellipse cx="222" cy="222" rx="42" ry="22" fill="white" opacity="0.18" />
          {innerSpecks.map((s, i) => (
            <circle key={i} cx={s.x} cy={s.y} r={s.r} fill="#a85f23" opacity="0.55" />
          ))}
          {/* inner ring */}
          <circle cx="250" cy="250" r="92" fill="none" stroke="#0a0604" strokeWidth="1" opacity="0.6" />
        </g>

        {/* cross-section pointer */}
        <g opacity="0.85">
          <line x1="338" y1="186" x2="402" y2="118" stroke="#1a1a1a" strokeWidth="1" />
          <circle cx="338" cy="186" r="2.5" fill="#1a1a1a" />
          <text x="408" y="116" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#1a1a1a" letterSpacing="2">
            OUTER LAYER
          </text>
          <line x1="402" y1="122" x2="478" y2="122" stroke="#1a1a1a" strokeWidth="0.6" />

          <line x1="200" y1="260" x2="98" y2="338" stroke="#1a1a1a" strokeWidth="1" />
          <circle cx="200" cy="260" r="2.5" fill="#1a1a1a" />
          <text x="22" y="356" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#1a1a1a" letterSpacing="2">
            INNER CORE
          </text>
          <line x1="22" y1="362" x2="98" y2="362" stroke="#1a1a1a" strokeWidth="0.6" />
        </g>
      </svg>

      {/* orbital ingredient labels */}
      <svg viewBox="0 0 500 500" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 1 }} aria-hidden="true">
        <circle cx="250" cy="250" r="240" fill="none" stroke="#2a4a3a" strokeOpacity="0.18" strokeDasharray="2 6" />
      </svg>
    </div>
  );
}

// ─── Main app ───────────────────────────────────────────────
function App() {
  // Aug 15, 2026 IST (00:00)
  const target = useMemo(() => new Date("2026-08-15T00:00:00+05:30").getTime(), []);

  return (
    <div className="app">
      <ParticleField />

      {/* top chrome */}
      <header className="top-bar">
        <div className="brand-mark">
          <div className="seal">G</div>
          <span>Good Haveit</span>
        </div>
        <div className="top-meta">
          <span className="hide-sm">Est. 2026 · Made in India</span>
          <span className="pulse">Launching Aug 15</span>
        </div>
      </header>

      {/* Hero */}
      <section className="hero">
        {/* decorative orbits */}
        <div className="orbit" style={{ width: 720, height: 720, left: "calc(50% - 360px)", top: "calc(50% - 360px)" }} />
        <div className="orbit" style={{ width: 1100, height: 1100, left: "calc(50% - 550px)", top: "calc(50% - 550px)", opacity: 0.5 }} />

        <div>
          <div className="hero-eyebrow">
            <span className="rule"></span>
            Premium · Healthy · Coming Soon
            <span className="rule"></span>
          </div>
          <h1 className="wordmark">Good <em>Haveit</em></h1>
          <div className="tagline">
            Good habit<span className="dot"></span>healthy future.
          </div>

          <Countdown target={target} />

          <div className="cta-row">
            <MagneticCTA onClick={() => {
              document.getElementById("product").scrollIntoView({ behavior: "smooth", block: "start" });
            }}>
              Meet the Laddu
            </MagneticCTA>
            <div className="cta-note">Our first taste — drops August 15</div>
          </div>
        </div>

        <div className="scroll-hint">
          <span>Scroll</span>
          <span className="line"></span>
        </div>
      </section>

      {/* Philosophy */}
      <section className="philosophy" id="philosophy">
        <div className="philosophy-inner">
          <Reveal>
            <div className="section-label">
              <span className="num">01</span>
              <span>Our Philosophy</span>
              <span className="rule"></span>
            </div>
          </Reveal>
          <div>
            <Reveal>
              <h2>
                Snacking, but <em>made the way</em> your grandmother would&nbsp;approve.
              </h2>
            </Reveal>
            <Reveal delay={120}>
              <p>
                Good Haveit was born from a simple frustration — every &ldquo;healthy&rdquo; bar on the shelf reads
                like a chemistry experiment. We make food the way it was meant to be made: a short list of real
                ingredients you can pronounce, prepared without shortcuts.
              </p>
              <p>
                No refined sugar. No seed oils. No preservatives. Just slow craft, honest sourcing, and recipes
                rooted in Indian tradition — re-engineered for the lives we actually live.
              </p>
            </Reveal>

            <div className="principle-row">
              <Reveal delay={60} className="principle a">
                <div className="glyph"></div>
                <h4>Real Ingredients</h4>
                <p>Whole foods only. If it isn&rsquo;t in your kitchen, it isn&rsquo;t in our recipe.</p>
              </Reveal>
              <Reveal delay={140} className="principle b">
                <div className="glyph"></div>
                <h4>Slow Made</h4>
                <p>Hand-rolled in small batches. No factory shortcuts, no compromises on craft.</p>
              </Reveal>
              <Reveal delay={220} className="principle c">
                <div className="glyph"></div>
                <h4>Quietly Indulgent</h4>
                <p>Healthy that tastes like a treat. Not a punishment, not a chore.</p>
              </Reveal>
            </div>
          </div>
        </div>
      </section>

      {/* Product */}
      <section className="product" id="product">
        <div className="product-inner">
          <Reveal>
            <LadduArt />
          </Reveal>
          <div className="product-copy">
            <Reveal>
              <div className="section-label">
                <span className="num">02</span>
                <span>The First Drop</span>
                <span className="rule"></span>
              </div>
            </Reveal>
            <Reveal delay={100}>
              <h3>The <em>Two-Layer</em> Laddu.</h3>
              <p className="lede">
                A laddu within a laddu. A molten dark-chocolate core wrapped in a stone-ground roast of
                seeds, nuts and dates — bound with raw honey and a touch of cold-pressed coconut oil.
              </p>
            </Reveal>

            <div className="layers">
              <Reveal delay={160} className="layer inner">
                <div className="layer-head">
                  <span className="layer-tag"><span className="swatch"></span>Layer 01 · The Core</span>
                  <span className="layer-tag" style={{ color: "#2a4a3a" }}>99% cacao</span>
                </div>
                <h5>Dark chocolate, dates &amp; peanut butter.</h5>
                <div className="layer-ings">
                  <span className="chip accent">99% Dark Chocolate</span>
                  <span className="chip">Medjool Dates</span>
                  <span className="chip">Homemade Peanut Butter</span>
                </div>
              </Reveal>

              <Reveal delay={240} className="layer outer">
                <div className="layer-head">
                  <span className="layer-tag"><span className="swatch"></span>Layer 02 · The Shell</span>
                  <span className="layer-tag" style={{ color: "#a85f23" }}>9 whole foods</span>
                </div>
                <h5>Roasted nuts, seeds &amp; superfoods.</h5>
                <div className="layer-ings">
                  <span className="chip accent">Bengal Gram</span>
                  <span className="chip">Almond</span>
                  <span className="chip">Cashew</span>
                  <span className="chip">Makhana</span>
                  <span className="chip">Sesame</span>
                  <span className="chip">Dates</span>
                  <span className="chip">Peanut Butter</span>
                  <span className="chip">Honey</span>
                  <span className="chip">Coconut Oil</span>
                </div>
              </Reveal>
            </div>
          </div>
        </div>
      </section>

      {/* Footer */}
      <footer className="foot">
        <div className="foot-inner">
          <div className="foot-mark">Good <em>Haveit</em>.</div>
          <div className="foot-meta">
            <span>© 2026</span>
            <span>Made in India</span>
            <a href="#">hello@goodhaveit.com</a>
          </div>
        </div>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
