// CircadianClock — interactive 24h MTC clock with real-time needle
// Same logic as WuClock Landing.html clock, restyled with liquid-glass.

const { useEffect: clkUseEffect, useRef: clkUseRef, useState: clkUseState } = React;
const { motion: clkMotion } = window.Motion;

// MTC organs assigned to even-hour 2-hour blocks, starting at midnight (top), clockwise.
const MTC_DATA = [
  { start: 0,  organ: 'Hígado',             element: 'Madera', color: '#4CAF50',
    body: 'El hígado detoxifica la sangre — momento más crítico del día.',
    todo: 'Dormí. Despertarse con tensión a esta hora sugiere hígado sobrecargado.' },
  { start: 2,  organ: 'Pulmón',             element: 'Metal',  color: '#9E9E9E',
    body: 'El pulmón reparte oxígeno y energía a todo el cuerpo.',
    todo: 'Sueño profundo. Si te despertás triste a esta hora, tu pulmón pide aire.' },
  { start: 4,  organ: 'Intestino Grueso',   element: 'Metal',  color: '#9E9E9E',
    body: 'Eliminás lo que tu cuerpo ya no necesita.',
    todo: 'Vaso de agua tibia al levantarte. Ir al baño tranquilo.' },
  { start: 6,  organ: 'Estómago',           element: 'Tierra', color: '#FF9800',
    body: 'Tu estómago está en pico de energía digestiva.',
    todo: 'Desayuno tibio y nutritivo. La comida más importante de tu día.' },
  { start: 8,  organ: 'Bazo',               element: 'Tierra', color: '#FF9800',
    body: 'El bazo transforma lo que comiste en energía utilizable.',
    todo: 'Trabajo concentrado. Tu mente está afilada para tareas complejas.' },
  { start: 10, organ: 'Corazón',            element: 'Fuego',  color: '#F44336',
    body: 'Tu corazón irriga al máximo — pico de claridad mental.',
    todo: 'Decisiones importantes, conversaciones difíciles, movimiento social.' },
  { start: 12, organ: 'Intestino Delgado',  element: 'Fuego',  color: '#F44336',
    body: 'Separás lo nutritivo de lo que va a descartarse.',
    todo: 'Almuerzo principal. Después, evitá decisiones grandes — bajada natural.' },
  { start: 14, organ: 'Vejiga',             element: 'Agua',   color: '#2196F3',
    body: 'Tu cuerpo procesa líquidos y elimina toxinas residuales.',
    todo: 'Hidratarte bien. Buen momento para movimiento moderado o estudio.' },
  { start: 16, organ: 'Riñón',              element: 'Agua',   color: '#2196F3',
    body: 'El riñón restaura tu reserva energética profunda.',
    todo: 'Bajar el ritmo. Cena temprana, conversación tranquila.' },
  { start: 18, organ: 'Pericardio',         element: 'Fuego',  color: '#F44336',
    body: 'Protege tu corazón — energía emocional al frente.',
    todo: 'Tiempo con personas que querés. Intimidad. Sin pantallas si podés.' },
  { start: 20, organ: 'Triple Calentador',  element: 'Fuego',  color: '#F44336',
    body: 'Tu cuerpo regula temperatura y se prepara para dormir.',
    todo: 'Bajá la luz, té tibio, respiración. Estás cerrando el día.' },
  { start: 22, organ: 'Vesícula Biliar',    element: 'Madera', color: '#4CAF50',
    body: 'Tu cuerpo descompone grasas y procesa decisiones del día.',
    todo: 'Dormí profundo. Cenar temprano y luz tenue ayudan a regenerar.' },
];

function polar(angDeg, r) {
  const a = (angDeg - 90) * Math.PI / 180;
  return { x: r * Math.cos(a), y: r * Math.sin(a) };
}
function arcPath(startDeg, endDeg, rIn, rOut) {
  const p1 = polar(startDeg, rOut);
  const p2 = polar(endDeg,   rOut);
  const p3 = polar(endDeg,   rIn);
  const p4 = polar(startDeg, rIn);
  const large = (endDeg - startDeg) > 180 ? 1 : 0;
  return [
    `M ${p1.x} ${p1.y}`,
    `A ${rOut} ${rOut} 0 ${large} 1 ${p2.x} ${p2.y}`,
    `L ${p3.x} ${p3.y}`,
    `A ${rIn} ${rIn} 0 ${large} 0 ${p4.x} ${p4.y}`,
    'Z',
  ].join(' ');
}
function getCurrentIdx(now = new Date()) {
  const h = now.getHours();
  for (let i = 0; i < MTC_DATA.length; i++) {
    const s = MTC_DATA[i].start;
    const e = (s + 2) % 24;
    if (s > e) {
      if (h >= s || h < e) return i;
    } else {
      if (h >= s && h < e) return i;
    }
  }
  return 0;
}
function fmtTime(d) {
  return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
}

const R_OUTER = 180;
const R_INNER = 115;

function CircadianClock() {
  const [now, setNow] = clkUseState(() => new Date());
  const [hoverIdx, setHoverIdx] = clkUseState(null);

  clkUseEffect(() => {
    const tick = () => setNow(new Date());
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);

  const currentIdx = getCurrentIdx(now);
  const shownIdx = hoverIdx !== null ? hoverIdx : currentIdx;
  const shown = MTC_DATA[shownIdx];

  // User's exact formula: angle measured with 0° = east (3 o'clock),
  // -90° puts midnight at the top. Drive the needle endpoint via cos/sin
  // so the math matches the formula 1-to-1 (no SVG rotate offset).
  const totalHoras = now.getHours() + now.getMinutes() / 60 + now.getSeconds() / 3600;
  const angulo = (totalHoras / 24) * 360 - 90;
  const aRad = angulo * Math.PI / 180;
  const needleLen = R_OUTER - 32;
  const needleX = needleLen * Math.cos(aRad);
  const needleY = needleLen * Math.sin(aRad);
  // Tail (opposite side, very short) for the back of the needle
  const tailLen = 6;
  const tailX = -tailLen * Math.cos(aRad);
  const tailY = -tailLen * Math.sin(aRad);

  const [secRef, secShown] = useInViewOnce(0.15);

  // Build hour ticks
  const hourTicks = [];
  for (let h = 0; h < 24; h++) {
    const deg = h * 15;
    const major = h % 6 === 0;
    const p1 = polar(deg, R_INNER - 4);
    const p2 = polar(deg, R_INNER - (major ? 14 : 8));
    hourTicks.push(
      <line key={`t-${h}`}
        x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y}
        stroke={major ? '#D4A852' : 'rgba(255,255,255,0.20)'}
        strokeWidth={major ? 1.5 : 1}
      />
    );
    if (major) {
      const tp = polar(deg, R_INNER - 28);
      hourTicks.push(
        <text key={`h-${h}`}
          x={tp.x} y={tp.y}
          textAnchor="middle" dominantBaseline="middle"
          fill="#D4A852" fontFamily="Barlow" fontSize="10"
          letterSpacing="1.5">
          {String(h).padStart(2, '0')}
        </text>
      );
    }
  }

  return (
    <section ref={secRef} id="metodo" className="relative w-full min-h-screen overflow-hidden bg-black scroll-mt-24">
      {/* Cosmic background — same vocabulary as the FinalCTA section so they blend continuously */}
      <div className="absolute inset-0 z-0" style={{
        background:
          'radial-gradient(60% 60% at 50% 50%, rgba(212,168,82,0.18) 0%, rgba(212,168,82,0.04) 40%, transparent 70%),' +
          'radial-gradient(80% 60% at 50% 100%, rgba(45,27,78,0.55) 0%, transparent 60%),' +
          'linear-gradient(180deg, transparent 0%, transparent 70%, #000 100%),' +
          '#000',
      }} />
      <Starfield />

      <div className="relative z-10 px-8 md:px-16 lg:px-20 pt-24 pb-24 flex flex-col min-h-screen">
        {/* Header */}
        <clkMotion.div
          {...fadeUp(0, secShown)}
        >
          <p className="text-sm font-body text-white/80 mb-6">// Reloj circadiano</p>
        </clkMotion.div>

        <clkMotion.h2
          {...fadeUp(0.1, secShown)}
          className="font-heading italic text-white text-5xl md:text-6xl lg:text-[5.5rem]"
          style={{ lineHeight: 0.95, letterSpacing: '-3px', maxWidth: '18ch' }}
        >
          Tu cuerpo tiene un reloj.<br />WuClock lo traduce.
        </clkMotion.h2>

        <clkMotion.p
          {...fadeUp(0.2, secShown)}
          className="mt-6 text-base text-white/80 font-body font-light max-w-2xl leading-snug"
        >
          Cada 2 horas, un órgano distinto entra en su pico de actividad.
          Pasá el cursor por cualquier franja — vas a ver qué está haciendo tu cuerpo y qué hacer al respecto.
        </clkMotion.p>

        {/* Clock + info grid */}
        <div className="mt-14 grid grid-cols-1 lg:grid-cols-[1.05fr_0.95fr] gap-10 lg:gap-14 items-center">
          {/* Clock SVG */}
          <clkMotion.div
            {...fadeUp(0.3, secShown)}
            className="relative w-full max-w-[560px] aspect-square justify-self-center"
          >
            <svg viewBox="-200 -200 400 400" style={{ width: '100%', height: '100%', overflow: 'visible' }}>
              {/* Segments */}
              <g>
                {MTC_DATA.map((seg, i) => {
                  const startDeg = seg.start * 15;
                  const endDeg = startDeg + 30;
                  const isActive = i === currentIdx;
                  const isHover = i === hoverIdx;
                  const opacity = isHover ? 0.55 : (isActive ? 0.42 : 0.18);
                  return (
                    <path
                      key={i}
                      d={arcPath(startDeg + 0.6, endDeg - 0.6, R_INNER, R_OUTER)}
                      fill={seg.color}
                      fillOpacity={opacity}
                      stroke={seg.color}
                      strokeOpacity={isHover ? 0.95 : (isActive ? 0.75 : 0.55)}
                      strokeWidth={1}
                      style={{
                        cursor: 'pointer',
                        transition: 'fill-opacity 220ms ease, stroke-opacity 220ms ease, filter 220ms ease',
                        filter: (isHover || isActive) ? `drop-shadow(0 0 14px ${seg.color})` : 'none',
                      }}
                      onMouseEnter={() => setHoverIdx(i)}
                      onMouseLeave={() => setHoverIdx(null)}
                    />
                  );
                })}
              </g>

              {/* Outer hour labels */}
              <g>
                {MTC_DATA.map((seg, i) => {
                  const mid = seg.start * 15 + 15;
                  const lp = polar(mid, R_OUTER + 22);
                  const h1 = seg.start % 24;
                  const h2 = (seg.start + 2) % 24;
                  const label = (h1 % 12 === 0 ? 12 : h1 % 12) + '–' + (h2 % 12 === 0 ? 12 : h2 % 12);
                  return (
                    <text key={`hl-${i}`} x={lp.x} y={lp.y}
                      textAnchor="middle" dominantBaseline="middle"
                      fill="rgba(255,255,255,0.55)" fontFamily="Barlow" fontSize="9"
                      letterSpacing="1.5"
                      style={{ pointerEvents: 'none' }}>
                      {label}
                    </text>
                  );
                })}
              </g>

              {/* Hour ticks */}
              <g style={{ pointerEvents: 'none' }}>{hourTicks}</g>

              {/* Center hub */}
              <circle cx="0" cy="0" r={R_INNER - 5} fill="rgba(0,0,0,0.55)" stroke="rgba(212,168,82,0.25)" strokeWidth="1" />
              <circle cx="0" cy="0" r={R_INNER - 10} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="1" />

              {/* Needle — endpoint computed from user's exact formula */}
              <g style={{ pointerEvents: 'none' }}>
                <line
                  x1={tailX} y1={tailY} x2={needleX} y2={needleY}
                  stroke="#E4BE6A" strokeWidth="2" strokeLinecap="round"
                />
                <circle cx={needleX} cy={needleY} r="4" fill="#E4BE6A" />
                <circle cx="0" cy="0" r="6" fill="#1A051F" stroke="#D4A852" strokeWidth="1.5" />
              </g>
            </svg>

            {/* Center labels overlay */}
            <div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
              <div className="text-[10px] font-body uppercase text-white/60" style={{ letterSpacing: '0.22em' }}>
                Ahora son
              </div>
              <div
                className="font-heading italic text-white mt-1"
                style={{ fontSize: 'clamp(36px, 4.2vw, 52px)', letterSpacing: '-1.5px', lineHeight: 1 }}
              >
                {fmtTime(now)}
              </div>
              <div className="text-[10px] font-body uppercase text-[#D4A852] mt-2" style={{ letterSpacing: '0.22em' }}>
                Hora · {MTC_DATA[currentIdx].organ}
              </div>
            </div>
          </clkMotion.div>

          {/* Info panel */}
          <clkMotion.aside
            {...fadeUp(0.4, secShown)}
            className="liquid-glass p-7 md:p-9 flex flex-col"
            style={{ borderRadius: '1.75rem', minHeight: 380 }}
            key={shownIdx /* re-mount on segment change for crisp updates */}
          >
            <div className="text-xs font-body uppercase text-white/60" style={{ letterSpacing: '0.22em' }}>
              {hoverIdx !== null ? 'Vista previa' : 'Ahora · ' + fmtTime(now)}
            </div>
            <div className="mt-3 text-sm font-body text-white/70" style={{ letterSpacing: '0.12em' }}>
              {String(shown.start).padStart(2, '0') + ':00'}
              {'  —  '}
              {String((shown.start + 2) % 24).padStart(2, '0') + ':00'}
            </div>
            <h3
              className="font-heading italic text-white mt-3 leading-none"
              style={{ fontSize: 'clamp(40px, 4.5vw, 60px)', letterSpacing: '-1.5px' }}
            >
              {shown.organ}
            </h3>
            <div
              className="inline-flex items-center gap-2 mt-4 self-start rounded-full px-3 py-1 text-xs font-medium"
              style={{
                color: shown.color,
                border: `1px solid ${shown.color}`,
                background: 'rgba(255,255,255,0.02)',
              }}
            >
              <span style={{
                width: 8, height: 8, borderRadius: 999, background: shown.color,
                boxShadow: `0 0 10px ${shown.color}`,
              }} />
              {shown.element}
            </div>

            <div className="mt-7">
              <div className="text-[10px] font-body uppercase text-white/55" style={{ letterSpacing: '0.22em' }}>
                Qué hace tu cuerpo
              </div>
              <p className="mt-2 text-[15px] text-white/90 font-body font-light leading-relaxed">
                {shown.body}
              </p>
            </div>
            <div className="mt-5">
              <div className="text-[10px] font-body uppercase text-[#D4A852]" style={{ letterSpacing: '0.22em' }}>
                Qué hacer ahora
              </div>
              <p className="mt-2 text-[15px] text-white/90 font-body font-light leading-relaxed">
                {shown.todo}
              </p>
            </div>
          </clkMotion.aside>
        </div>
      </div>
    </section>
  );
}

// Subtle starfield background (CSS only)
function Starfield() {
  return (
    <div className="absolute inset-0 z-0 pointer-events-none" style={{
      background:
        'radial-gradient(1px 1px at 12% 18%, rgba(255,255,255,0.55), transparent 60%),' +
        'radial-gradient(1px 1px at 27% 72%, rgba(255,255,255,0.40), transparent 60%),' +
        'radial-gradient(1.5px 1.5px at 48% 30%, rgba(228,190,106,0.55), transparent 60%),' +
        'radial-gradient(1px 1px at 64% 84%, rgba(255,255,255,0.45), transparent 60%),' +
        'radial-gradient(1px 1px at 78% 22%, rgba(255,255,255,0.55), transparent 60%),' +
        'radial-gradient(1px 1px at 88% 60%, rgba(228,190,106,0.40), transparent 60%),' +
        'radial-gradient(1px 1px at 8% 52%, rgba(255,255,255,0.35), transparent 60%),' +
        'radial-gradient(1px 1px at 35% 10%, rgba(255,255,255,0.30), transparent 60%),' +
        'radial-gradient(1.2px 1.2px at 58% 65%, rgba(255,255,255,0.45), transparent 60%)',
      opacity: 0.9,
    }} />
  );
}

Object.assign(window, { CircadianClock, Starfield });
