// Solstice components — all global
const { useState, useEffect, useRef } = React;

/* ---------- Custom cursor ---------- */
function Cursor() {
  const ringRef = useRef(null);
  const dotRef = useRef(null);
  const [big, setBig] = useState(false);
  useEffect(() => {
    const move = (e) => {
      if (ringRef.current) {
        ringRef.current.style.left = e.clientX + 'px';
        ringRef.current.style.top = e.clientY + 'px';
      }
      if (dotRef.current) {
        dotRef.current.style.left = e.clientX + 'px';
        dotRef.current.style.top = e.clientY + 'px';
      }
    };
    window.addEventListener('mousemove', move);
    const onOver = (e) => {
      if (e.target.closest('a, button, .pkg, .product, .event, .cal-day, .g-item, .tweak-swatch, .tweak-chip')) setBig(true);
      else setBig(false);
    };
    window.addEventListener('mouseover', onOver);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseover', onOver); };
  }, []);
  return (
    <>
      <div ref={ringRef} className={`cursor ${big ? 'big' : ''}`}></div>
      <div ref={dotRef} className="cursor-dot"></div>
    </>
  );
}

/* ---------- Nav ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <a href="#hero" className="nav-logo">
        <span>Solstice</span>
      </a>
      <div className="nav-links">
        <a href="#clases">Clases</a>
        <a href="parejas.html">Parejas</a>
        <a href="fechas/index.html">Fechas</a>
        <a href="#galeria">Galería</a>
        <a href="#eventos">Eventos</a>
        <a href="blog/index.html">Blog</a>
        <a href="#contacto">Contacto</a>
      </div>
      <a href="#contacto" className="nav-cta">Reservar</a>
    </nav>
  );
}

/* ---------- Hero ---------- */
function Hero({ layout }) {
  const [mouse, setMouse] = useState({ x: 0, y: 0 });
  useEffect(() => {
    const onMove = (e) => {
      const x = (e.clientX / window.innerWidth - 0.5) * 2;
      const y = (e.clientY / window.innerHeight - 0.5) * 2;
      setMouse({ x, y });
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);

  return (
    <section id="hero" className="hero" data-screen-label="Hero">
      <div className="noise"></div>
      <div className="wrap hero-grid" style={{ flex: 1 }}>
        <div>
          <div className="mono" style={{ opacity: 0.7, marginBottom: 32, color: 'var(--cream)' }}>
            — Clases de cerámica en Arequipa · Desde 2024
          </div>
          <h1 className="hero-title display">
            <span className="word"><span className="word-inner">Crea,</span></span>
            <span className="word"><span className="word-inner"><em>relájate</em></span></span>
            <span className="word"><span className="word-inner">y comparte.</span></span>
          </h1>
          <p className="hero-sub" style={{ marginTop: 40 }}>
            Clases de cerámica en Arequipa con materiales, bebidas y comida ligera incluidos.
            Reserva una experiencia de fin de semana, un ritmo mensual o una inmersión intensiva.
          </p>
          <div style={{ display: 'flex', gap: 16, marginTop: 40, opacity: 0, animation: 'fade-up 1s var(--ease-out) 1.1s forwards' }}>
            <a href="#clases" className="nav-cta" style={{ padding: '14px 28px', fontSize: 13, color: 'var(--clay)', borderColor: 'var(--clay)' }}>
              Ver clases →
            </a>
            <a href="#eventos" className="nav-cta" style={{ padding: '14px 28px', fontSize: 13, color: 'var(--clay)', borderColor: 'var(--clay)' }}>
              Reservar evento
            </a>
          </div>
        </div>

        <div className="hero-right" style={{
          transform: `translate(${mouse.x * 20}px, ${mouse.y * 20}px)`,
          transition: 'transform 0.4s var(--ease-out)'
        }}>
          <div className="vessel">
            <div className="vessel-orb">
              <PotteryWheel />
            </div>
          </div>
        </div>
      </div>

      <div className="wrap hero-footer">
        <div></div>
        <div className="hero-scroll">
          <span>Desliza</span>
          <span className="hero-scroll-line"></span>
        </div>
      </div>
    </section>
  );
}

/* ---------- Animated counter ---------- */
function Counter({ to, duration = 1800 }) {
  const [val, setVal] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    let started = false;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          const start = performance.now();
          const animate = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(Math.round(to * eased));
            if (p < 1) requestAnimationFrame(animate);
          };
          requestAnimationFrame(animate);
        }
      });
    }, { threshold: 0.3 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{val.toLocaleString('es-PE')}</span>;
}

/* ---------- Marquee ---------- */
function Marquee() {
  const items = [
    { t: 'Torno', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><ellipse cx="12" cy="18" rx="9" ry="2"/><path d="M7 18V12a5 5 0 0110 0v6"/><circle cx="12" cy="10" r="1.5" fill="currentColor"/></svg> },
    { t: 'Pintura', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 20 L12 4 L20 20Z"/><circle cx="12" cy="14" r="2" fill="currentColor"/></svg> },
    { t: 'Vino', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M7 3h10v3a5 5 0 01-10 0V3z" fill="currentColor" fillOpacity="0.3"/><path d="M7 3h10v3a5 5 0 01-10 0V3z"/><path d="M12 11v8M8 21h8"/></svg> },
    { t: 'Arcilla', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 10 Q4 16 8 20 Q12 22 16 20 Q20 16 18 10 Q15 6 12 6 Q9 6 6 10Z"/></svg> },
    { t: 'Esmalte', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M8 4 L16 4 L15 9 Q20 11 20 16 Q20 21 12 21 Q4 21 4 16 Q4 11 9 9 Z"/></svg> },
    { t: 'Comunidad', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="8" cy="8" r="3"/><circle cx="16" cy="8" r="3"/><path d="M3 20c0-3 3-5 5-5M21 20c0-3-3-5-5-5M10 20c0-2 1-3 2-3s2 1 2 3"/></svg> },
    { t: 'Arequipa', i: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 20L12 6 L21 20Z"/><circle cx="18" cy="6" r="2" fill="currentColor"/></svg> }
  ];
  return (
    <div className="marquee">
      <div className="marquee-track">
        <span>
          {[...items, ...items, ...items].map((it, i) => (
            <React.Fragment key={i}>
              <span style={{display:'inline-flex', alignItems:'center', gap:20}}>
                <span style={{width:36, height:36, display:'inline-block'}}>{it.i}</span>
                <span>{it.t}</span>
              </span>
              <span className="dot"></span>
            </React.Fragment>
          ))}
        </span>
      </div>
    </div>
  );
}

function ClayFloats() {
  const floats = Array.from({length: 8}, (_, i) => ({
    id: i,
    left: Math.random() * 100,
    delay: Math.random() * -18,
    duration: 14 + Math.random() * 10,
    size: 6 + Math.random() * 10
  }));
  return (
    <>
      {floats.map(f => (
        <div key={f.id} className="clay-float" style={{
          left: `${f.left}vw`,
          width: f.size, height: f.size * 1.2,
          animationDelay: `${f.delay}s`,
          animationDuration: `${f.duration}s`
        }}/>
      ))}
    </>
  );
}

/* ---------- Pottery Wheel (animated) ---------- */
function PotteryWheel() {
  const [t, setT] = useState(0.35);
  useEffect(() => {
    const DUR = 8000;
    const start = performance.now() - 0.35 * DUR;
    let raf;
    const tick = () => {
      const elapsed = (performance.now() - start) % DUR;
      setT(elapsed / DUR);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    const iv = setInterval(() => {
      const elapsed = (performance.now() - start) % DUR;
      setT(elapsed / DUR);
    }, 80);
    return () => { cancelAnimationFrame(raf); clearInterval(iv); };
  }, []);

  const ease = (x) => 1 - Math.pow(1 - x, 3);
  const phase = t < 0.7 ? ease(t / 0.7) : 1;
  const release = t < 0.9 ? 0 : (t - 0.9) / 0.1;

  const height = 10 + phase * 60 - release * 60;
  const bellyW = 18 + phase * 22 - release * 22;
  const neckW = 18 + phase * 6 - release * 6;
  const lipW = 18 + phase * 14 - release * 14;
  const baseY = 100;
  const topY = baseY - height;
  const neckY = baseY - height * 0.82;
  const bellyY = baseY - height * 0.45;
  const wobble = Math.sin(t * Math.PI * 12) * 0.6 * phase;
  const ridgeCount = 6;

  return (
    <div className="wheel-scene">
      <div className="wheel-spot"></div>
      <div className="wheel-head">
        <div className="wheel-head-top"></div>
        <div className="wheel-head-side"></div>
      </div>

      <svg className="wheel-vessel" viewBox="0 0 100 110" preserveAspectRatio="xMidYMax meet">
        <defs>
          <linearGradient id="clayG" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="#7a3418" stopOpacity="0"/>
            <stop offset="8%" stopColor="#7a3418"/>
            <stop offset="28%" stopColor="#a85030"/>
            <stop offset="48%" stopColor="#d07a42"/>
            <stop offset="64%" stopColor="#b05a28"/>
            <stop offset="92%" stopColor="#7a3418"/>
            <stop offset="100%" stopColor="#7a3418" stopOpacity="0"/>
          </linearGradient>
          <linearGradient id="clayShine" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor="rgba(255,220,170,0)"/>
            <stop offset="35%" stopColor="rgba(255,230,180,0.35)"/>
            <stop offset="45%" stopColor="rgba(255,240,200,0.55)"/>
            <stop offset="55%" stopColor="rgba(255,230,180,0.25)"/>
            <stop offset="100%" stopColor="rgba(0,0,0,0)"/>
          </linearGradient>
          <radialGradient id="openingG" cx="0.5" cy="0.5" r="0.5">
            <stop offset="0%" stopColor="#0a0402"/>
            <stop offset="70%" stopColor="#2a1208"/>
            <stop offset="100%" stopColor="#5a2810"/>
          </radialGradient>
        </defs>

        <path
          d={`
            M ${50 - lipW + wobble} ${topY}
            Q ${50 - neckW - 1 + wobble} ${neckY} ${50 - bellyW + wobble} ${bellyY}
            Q ${50 - bellyW - 1 + wobble} ${baseY - 8} ${50 - bellyW * 0.6 + wobble} ${baseY - 2}
            L ${50 + bellyW * 0.6 + wobble} ${baseY - 2}
            Q ${50 + bellyW + 1 + wobble} ${baseY - 8} ${50 + bellyW + wobble} ${bellyY}
            Q ${50 + neckW + 1 + wobble} ${neckY} ${50 + lipW + wobble} ${topY}
            Z
          `}
          fill="url(#clayG)"
        />

        <path
          d={`
            M ${50 - lipW + wobble} ${topY}
            Q ${50 - neckW - 1 + wobble} ${neckY} ${50 - bellyW + wobble} ${bellyY}
            Q ${50 - bellyW - 1 + wobble} ${baseY - 8} ${50 - bellyW * 0.6 + wobble} ${baseY - 2}
            L ${50 + bellyW * 0.6 + wobble} ${baseY - 2}
            Q ${50 + bellyW + 1 + wobble} ${baseY - 8} ${50 + bellyW + wobble} ${bellyY}
            Q ${50 + neckW + 1 + wobble} ${neckY} ${50 + lipW + wobble} ${topY}
            Z
          `}
          fill="url(#clayShine)"
          style={{ mixBlendMode: 'screen', opacity: 0.9 }}
        />

        {Array.from({ length: ridgeCount }).map((_, i) => {
          const p = ((t * 2 + i / ridgeCount) % 1);
          const y = baseY - 4 - p * (height - 8);
          const yN = (baseY - y) / height;
          const w = (() => {
            if (yN < 0.45) return bellyW * (0.6 + yN * 0.89);
            if (yN < 0.82) {
              const k = (yN - 0.45) / 0.37;
              return bellyW - (bellyW - neckW) * k;
            }
            const k = (yN - 0.82) / 0.18;
            return neckW + (lipW - neckW) * k;
          })();
          if (height < 14) return null;
          return (
            <ellipse
              key={i}
              cx={50 + wobble}
              cy={y}
              rx={w}
              ry={0.6}
              fill="none"
              stroke="rgba(40, 15, 5, 0.35)"
              strokeWidth="0.4"
              opacity={Math.min(1, p * 3) * (1 - p) * 1.6}
            />
          );
        })}

        {height > 12 && (
          <>
            <ellipse
              cx={50 + wobble}
              cy={topY + 0.3}
              rx={lipW * 0.92}
              ry={Math.max(1.2, lipW * 0.22)}
              fill="url(#openingG)"
            />
            <ellipse
              cx={50 + wobble}
              cy={topY - 0.2}
              rx={lipW * 0.92}
              ry={Math.max(1.2, lipW * 0.22)}
              fill="none"
              stroke="rgba(255, 220, 170, 0.35)"
              strokeWidth="0.5"
            />
          </>
        )}

        {height > 20 && (
          <ellipse
            cx={50 - bellyW * 0.55 + wobble}
            cy={bellyY - height * 0.05}
            rx={2.5}
            ry={height * 0.18}
            fill="rgba(255, 240, 210, 0.25)"
            style={{ filter: 'blur(1.2px)' }}
          />
        )}
      </svg>

      <div className="wheel-drip" style={{ animationDelay: `${(t * 8) % 3}s` }}></div>
      <div className="wheel-specks">
        {[0,1,2,3,4].map(i => (
          <span key={i} className={`wspeck ws${i}`} style={{ animationDelay: `${i * 0.45}s` }}></span>
        ))}
      </div>
      <div className="wheel-hand left" style={{ top: `${42 + phase * 5}%` }}></div>
      <div className="wheel-hand right" style={{ top: `${42 + phase * 5}%` }}></div>
    </div>
  );
}

Object.assign(window, { Cursor, Nav, Hero, Counter, Marquee, ClayFloats, PotteryWheel });
