/* global React */
// Animated yoga figure — 3 variants
// Each pose is a stick figure drawn with strokes on a 200x200 viewBox.

const { useState, useEffect, useRef } = React;

/* ============================================================
   POSE LIBRARY
   Each pose returns an array of <path>/<circle> elements.
   Coords are designed for a 200x200 viewBox centered at (100, 100).
   Stroke width 2.5, line-cap round.
   ============================================================ */

const POSES = {
  // Tadasana — mountain pose
  tadasana: {
    name: "Tadasana",
    es: "Montaña",
    en: "Mountain",
    paths: [
      { type: 'circle', cx: 100, cy: 38, r: 10 },        // head
      { type: 'path', d: "M100 48 L100 120" },           // torso
      { type: 'path', d: "M100 60 L80 100" },            // left arm
      { type: 'path', d: "M100 60 L120 100" },           // right arm
      { type: 'path', d: "M100 120 L88 175" },           // left leg
      { type: 'path', d: "M100 120 L112 175" },          // right leg
    ],
  },
  // Vrksasana — tree pose (right foot on left thigh, hands at heart)
  vrksasana: {
    name: "Vrksasana",
    es: "Árbol",
    en: "Tree",
    paths: [
      { type: 'circle', cx: 100, cy: 36, r: 10 },
      { type: 'path', d: "M100 46 L100 118" },
      { type: 'path', d: "M100 58 L90 78 L100 88" },     // left arm to heart
      { type: 'path', d: "M100 58 L110 78 L100 88" },    // right arm to heart
      { type: 'path', d: "M100 118 L96 175" },           // standing left leg
      { type: 'path', d: "M100 118 L78 140 L96 150" },   // bent right leg (foot on thigh)
    ],
  },
  // Virabhadrasana II — warrior II
  warrior: {
    name: "Virabhadrasana II",
    es: "Guerrero II",
    en: "Warrior II",
    paths: [
      { type: 'circle', cx: 100, cy: 50, r: 10 },
      { type: 'path', d: "M100 60 L100 118" },
      { type: 'path', d: "M100 72 L50 72" },             // arm left
      { type: 'path', d: "M100 72 L150 72" },            // arm right
      { type: 'path', d: "M100 118 L60 175" },           // front leg (bent)
      { type: 'path', d: "M100 118 L150 175" },          // back leg straight
    ],
  },
  // Trikonasana — triangle pose
  triangle: {
    name: "Trikonasana",
    es: "Triángulo",
    en: "Triangle",
    paths: [
      { type: 'circle', cx: 70, cy: 90, r: 10 },         // head tilted left
      { type: 'path', d: "M70 100 L120 130" },           // torso
      { type: 'path', d: "M82 102 L60 160" },            // bottom arm down
      { type: 'path', d: "M108 122 L130 60" },           // top arm up
      { type: 'path', d: "M120 130 L70 175" },           // back leg
      { type: 'path', d: "M120 130 L170 175" },          // front leg
    ],
  },
  // Urdhva Hastasana — arms up (sun salute)
  urdhva: {
    name: "Urdhva Hastasana",
    es: "Manos al cielo",
    en: "Hands to the sky",
    paths: [
      { type: 'circle', cx: 100, cy: 50, r: 10 },
      { type: 'path', d: "M100 60 L100 128" },
      { type: 'path', d: "M100 70 L80 20" },             // left arm up
      { type: 'path', d: "M100 70 L120 20" },            // right arm up
      { type: 'path', d: "M100 128 L86 178" },
      { type: 'path', d: "M100 128 L114 178" },
    ],
  },
  // Adho mukha svanasana — downward dog
  downdog: {
    name: "Adho Mukha Svanasana",
    es: "Perro boca abajo",
    en: "Downward dog",
    paths: [
      { type: 'path', d: "M75 128 L135 60" },            // torso (shoulders → hips, inverted V apex)
      { type: 'circle', cx: 62, cy: 142, r: 9 },         // head hanging between arms
      { type: 'path', d: "M75 128 L48 178" },            // arm (shoulder → hand on ground)
      { type: 'path', d: "M75 128 L62 178" },            // arm (slight fan for 3/4 view)
      { type: 'path', d: "M135 60 L158 178" },           // leg
      { type: 'path', d: "M135 60 L175 178" },           // leg
    ],
  },
  // Padmasana — seated lotus
  lotus: {
    name: "Padmasana",
    es: "Loto",
    en: "Lotus",
    paths: [
      { type: 'circle', cx: 100, cy: 60, r: 10 },
      { type: 'path', d: "M100 70 L100 130" },
      { type: 'path', d: "M100 85 L70 130" },            // arm on knee
      { type: 'path', d: "M100 85 L130 130" },           // arm on knee
      { type: 'path', d: "M100 130 L55 150 L100 145 L145 150 L100 130" }, // crossed legs
    ],
  },
};

const SEQUENCE = ['tadasana','urdhva','warrior','triangle','vrksasana','downdog','lotus'];

// Pick the pose's translated label based on the page language
const FIG_LANG = (document.documentElement.lang || 'es').slice(0, 2);
function localName(pose) { return FIG_LANG === 'en' ? (pose.en || pose.es) : pose.es; }

/* ============================================================
   Variant 1 — Cycling silhouette
   Cross-fades through SEQUENCE
   ============================================================ */
function YogaCycle({ interval = 2800 }) {
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setIdx(i => (i + 1) % SEQUENCE.length), interval);
    return () => clearInterval(t);
  }, [interval]);

  const current = POSES[SEQUENCE[idx]];

  return (
    <div className="yoga-figure" style={{position:'relative', width:'100%', height:'100%'}}>
      {SEQUENCE.map((key, i) => {
        const pose = POSES[key];
        const active = i === idx;
        return (
          <svg
            key={key}
            viewBox="0 25 200 200"
            style={{
              position: 'absolute',
              inset: 0,
              width: '100%',
              height: '100%',
              opacity: active ? 1 : 0,
              transition: 'opacity 1.2s cubic-bezier(.4,.0,.2,1)',
            }}
          >
            {pose.paths.map((p, j) =>
              p.type === 'circle' ? (
                <circle key={j} cx={p.cx} cy={p.cy} r={p.r}
                  fill="none" stroke="currentColor" strokeWidth="2.5" />
              ) : (
                <path key={j} d={p.d}
                  fill="none" stroke="currentColor" strokeWidth="2.5"
                  strokeLinecap="round" strokeLinejoin="round" />
              )
            )}
          </svg>
        );
      })}
      <PoseLabel name={current.name} es={localName(current)} idx={idx} total={SEQUENCE.length} />
    </div>
  );
}

/* ============================================================
   Variant 2 — Line draw / undraw
   One pose at a time, animated stroke (dash) draw-on then draw-off
   ============================================================ */
function YogaLine({ interval = 3600 }) {
  const [idx, setIdx] = useState(0);
  const [phase, setPhase] = useState('drawing'); // drawing | erasing
  const pathsRef = useRef([]);

  useEffect(() => {
    let t1, t2;
    const loop = () => {
      setPhase('drawing');
      t1 = setTimeout(() => setPhase('erasing'), interval / 2);
      t2 = setTimeout(() => {
        setIdx(i => (i + 1) % SEQUENCE.length);
        loop();
      }, interval);
    };
    loop();
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [interval]);

  // Compute total length on mount
  useEffect(() => {
    pathsRef.current.forEach(el => {
      if (!el) return;
      try {
        const len = el.getTotalLength ? el.getTotalLength() : 200;
        el.style.strokeDasharray = `${len}`;
        el.style.strokeDashoffset = phase === 'drawing' ? `${len}` : '0';
        // trigger reflow then animate
        requestAnimationFrame(() => {
          el.style.transition = `stroke-dashoffset ${interval/2 - 100}ms ease-in-out`;
          el.style.strokeDashoffset = phase === 'drawing' ? '0' : `${len}`;
        });
      } catch (e) {}
    });
  }, [idx, phase, interval]);

  const pose = POSES[SEQUENCE[idx]];

  return (
    <div className="yoga-figure" style={{position:'relative', width:'100%', height:'100%'}}>
      <svg viewBox="0 25 200 200" style={{ width: '100%', height: '100%' }}>
        {pose.paths.map((p, j) =>
          p.type === 'circle' ? (
            <circle key={`${idx}-${j}`}
              ref={el => pathsRef.current[j] = el}
              cx={p.cx} cy={p.cy} r={p.r}
              fill="none" stroke="currentColor" strokeWidth="2"
              pathLength="100"
              style={{strokeDasharray: 100}} />
          ) : (
            <path key={`${idx}-${j}`}
              ref={el => pathsRef.current[j] = el}
              d={p.d}
              fill="none" stroke="currentColor" strokeWidth="2"
              strokeLinecap="round" strokeLinejoin="round" />
          )
        )}
      </svg>
      <PoseLabel name={pose.name} es={localName(pose)} idx={idx} total={SEQUENCE.length} />
    </div>
  );
}

/* ============================================================
   Variant 3 — Single asana with breath
   Lotus pose, subtle scale on a 5s breath cycle
   ============================================================ */
function YogaBreath() {
  const [breathPct, setBreathPct] = useState(0);
  useEffect(() => {
    let raf;
    const start = performance.now();
    const cycle = 6000; // 6s breath cycle
    const tick = (t) => {
      const elapsed = (t - start) % cycle;
      const pct = elapsed / cycle; // 0..1
      setBreathPct(pct);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Sine wave 0..1..0
  const wave = (Math.sin(breathPct * Math.PI * 2 - Math.PI/2) + 1) / 2;
  const scale = 1 + wave * 0.04;
  const opacity = 0.85 + wave * 0.15;
  const inhale = wave > 0.5;
  const pose = POSES.lotus;

  return (
    <div className="yoga-figure" style={{position:'relative', width:'100%', height:'100%'}}>
      <svg viewBox="0 25 200 200"
        style={{ width: '100%', height: '100%', opacity, transform: `scale(${scale})`, transformOrigin: 'center' }}>
        {/* Breath circles */}
        <circle cx="100" cy="100" r={60 + wave * 18} fill="none" stroke="currentColor" strokeWidth="0.5" opacity={0.3 + wave * 0.3} />
        <circle cx="100" cy="100" r={48 + wave * 12} fill="none" stroke="currentColor" strokeWidth="0.5" opacity={0.2 + wave * 0.2} />
        {pose.paths.map((p, j) =>
          p.type === 'circle' ? (
            <circle key={j} cx={p.cx} cy={p.cy} r={p.r}
              fill="none" stroke="currentColor" strokeWidth="2.5" />
          ) : (
            <path key={j} d={p.d}
              fill="none" stroke="currentColor" strokeWidth="2.5"
              strokeLinecap="round" strokeLinejoin="round" />
          )
        )}
      </svg>
      <div style={{
        position: 'absolute',
        bottom: '6%',
        left: '50%',
        transform: 'translateX(-50%)',
        fontFamily: 'var(--mono)',
        fontSize: '11px',
        letterSpacing: '0.18em',
        textTransform: 'uppercase',
        color: 'var(--mute)',
        display: 'flex',
        gap: '12px',
        alignItems: 'center',
      }}>
        <span style={{ opacity: inhale ? 1 : 0.3 }}>{FIG_LANG === 'en' ? 'inhale' : 'inhala'}</span>
        <span style={{ width: 24, height: 1, background: 'currentColor', opacity: 0.4 }}></span>
        <span style={{ opacity: inhale ? 0.3 : 1 }}>{FIG_LANG === 'en' ? 'exhale' : 'exhala'}</span>
      </div>
    </div>
  );
}

/* ============================================================
   Pose label (shared)
   ============================================================ */
function PoseLabel({ name, es, idx, total }) {
  return (
    <div style={{
      position: 'absolute',
      bottom: '4%',
      left: '50%',
      transform: 'translateX(-50%)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      textAlign: 'center',
      gap: 4,
      fontFamily: 'var(--mono)',
      fontSize: 11,
      letterSpacing: '0.16em',
      textTransform: 'uppercase',
      color: 'var(--mute)',
      whiteSpace: 'nowrap',
    }}>
      <span style={{ color: 'var(--ink)' }}>{name}</span>
      <span>{es}</span>
    </div>
  );
}

/* ============================================================
   Master export
   ============================================================ */
function YogaFigure({ variant = 'cycle' }) {
  if (variant === 'line')   return <YogaLine />;
  if (variant === 'breath') return <YogaBreath />;
  return <YogaCycle />;
}

window.YogaFigure = YogaFigure;
window.POSES = POSES;
