// anim-prism.jsx — Variation 1: Prisma
// A thin white beam enters from the left, hits a prism point, fans into the
// visible spectrum. The magenta wavelength isolates and 3 beams of magenta
// tones converge into the M. Tagline + breath loop.

const PrismAnim = ({ t, duration }) => {
  // local helpers
  const clamp01 = (v) => Math.max(0, Math.min(1, v));
  const easeOut = (x) => 1 - Math.pow(1 - x, 3);
  const easeIn = (x) => x * x * x;
  const easeIO = (x) => x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
  const lerp = (a, b, x) => a + (b - a) * x;
  const seg = (t0, t1, te = easeIO) => te(clamp01((t - t0) / (t1 - t0)));

  // Phases (5.4s total — last 0.4s blends into loop start for seamless loop)
  const TBeamDraw = seg(0.10, 1.10, easeOut); // beam draws in
  const TPrismHit = seg(1.00, 1.40, easeOut); // prism dot flares
  const TFan = seg(1.20, 2.40, easeOut); // spectrum fans out
  const TIsolate = seg(2.30, 3.10, easeIO); // other colors fade, magenta isolates
  const TConverge = seg(2.80, 3.60, easeIO); // magenta beams converge to M position
  const TReveal = seg(3.40, 4.10, easeOut); // M materializes via wipe
  const TFlash = seg(3.90, 4.30, easeOut); // bright flash on lock
  const TTagline = seg(4.20, 4.80, easeOut); // tagline fades in
  const breath = 0.5 + 0.5 * Math.sin(t / duration * Math.PI * 2 * 1); // 1 cycle/loop
  const subtleBreath = 1 - 0.03 * Math.max(0, Math.sin((t - 4.5) * Math.PI / 0.8));

  // Loop crossfade: last 0.35s fades opacity of whole pulsing piece into start
  const loopFade = clamp01((duration - t) / 0.35);

  // Geometry — centered on canvas
  const CX = 960,CY = 540;
  const M_W = 520, M_H = 283;
  // Use % + translate so centering is bulletproof regardless of parent layout quirks.
  // Vertical offset: pull up so M+tagline group reads as balanced around canvas center.
  const M_TOP_PCT = 38; // y center as % of stage height (38% → above middle)

  // Spectrum band colors (red→violet) with magentas added
  const bands = [
  { h: '#ff2d4a', label: 'R' },
  { h: '#ff7a1a', label: 'O' },
  { h: '#ffd60a', label: 'Y' },
  { h: '#34d399', label: 'G' },
  { h: '#38bdf8', label: 'C' },
  { h: '#6366f1', label: 'B' },
  { h: '#a855f7', label: 'V' }];


  // Beam parameters
  const beamStartX = -100;
  const beamEndX = CX - 6; // stops just before prism point
  const beamY = CY;
  const beamLen = lerp(0, beamEndX - beamStartX, TBeamDraw);
  const beamTipX = beamStartX + beamLen;

  // Prism dot scale / glow
  const prismScale = 0.2 + 1.6 * TPrismHit - 0.4 * TFan; // flares then settles
  const prismOpacity = clamp01(TPrismHit - TFan * 0.6);

  // Spectrum fan: each band is a long thin gradient at an angle
  const fanLen = lerp(0, 1600, TFan);
  const fanOpacity = lerp(0, 1, TFan) * (1 - TIsolate * 0.85);

  // Magenta isolation: 3 beams (the three M tones) converging on M strokes
  const magenta3 = [
  { color: '#7a1b54', angle: -10, label: 'plum' }, // dark plum
  { color: '#c66689', angle: 0, label: 'pink' }, // mid pink
  { color: '#e6217a', angle: 10, label: 'hot' } // hot magenta
  ];

  // M wipe progress — vertical sweep from bottom-up reveal using clip-path
  const wipeAmt = TReveal; // 0..1
  // clip-path inset from top: visible portion grows from bottom up
  const wipeInset = (1 - wipeAmt) * 100;

  // Flash opacity (white fullscreen flash on lock)
  const flashOpacity = TFlash * (1 - TFlash * 0.85);

  // Final logo opacity & glow pulse (after reveal)
  const logoVisible = clamp01((t - 3.4) / 0.35);
  const finalPulse = t > 4.2 ? 0.85 + 0.15 * Math.sin((t - 4.2) * 2 * Math.PI / 1.4) : 0;

  return (
    <div style={{ position: 'absolute', inset: 0, fontSize: "10px" }}>
      {/* Faint stars */}
      <Stars seed={1} count={90} />

      {/* Horizontal guide line (faint) — only during beam phase, fades after fan */}
      <div style={{
        position: 'absolute', left: 0, right: 0, top: beamY, height: 1,
        background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.08), transparent)',
        opacity: lerp(0.6, 0, TFan)
      }} />

      {/* The white beam */}
      <div style={{
        position: 'absolute',
        left: beamStartX, top: beamY - 3, height: 6,
        width: beamLen,
        background: 'linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.0) 5%, rgba(255,255,255,0.9) 60%, #fff 100%)',
        filter: 'blur(0.5px)',
        boxShadow: '0 0 24px rgba(255,255,255,0.6), 0 0 60px rgba(255,255,255,0.25)',
        opacity: 1 - TFan,
        borderRadius: 3
      }} />
      {/* Beam tip highlight */}
      {TBeamDraw > 0 && TFan < 0.5 &&
      <div style={{
        position: 'absolute',
        left: beamTipX - 16, top: beamY - 16,
        width: 32, height: 32, borderRadius: '50%',
        background: 'radial-gradient(circle, #fff 0%, rgba(255,255,255,0.6) 30%, transparent 70%)',
        opacity: (1 - TFan) * (0.6 + 0.4 * Math.sin(t * 30)),
        filter: 'blur(1px)'
      }} />
      }

      {/* The prism (small triangle / point) */}
      <div style={{
        position: 'absolute',
        left: CX - 40, top: CY - 46,
        width: 80, height: 92,
        opacity: clamp01(TPrismHit - TIsolate * 0.5),
        transform: `scale(${0.3 + 0.7 * TPrismHit})`,
        transformOrigin: 'center'
      }}>
        <svg viewBox="0 0 80 92" width="80" height="92" style={{ filter: 'drop-shadow(0 0 24px rgba(255,255,255,0.5))' }}>
          <polygon points="40,4 76,88 4,88"
          fill="none"
          stroke="rgba(255,255,255,0.55)"
          strokeWidth="1.2" />
          <polygon points="40,4 76,88 4,88"
          fill="rgba(255,255,255,0.04)" />
        </svg>
      </div>

      {/* Spectrum fan — each band rotated and translated */}
      <div style={{
        position: 'absolute', left: CX, top: CY, width: 0, height: 0,
        opacity: fanOpacity
      }}>
        {bands.map((b, i) => {
          const angle = -36 + i * 12; // -36° to +36°
          const isMagentaRange = i >= 5; // blue+violet wrap toward magenta
          const fade = TIsolate * (isMagentaRange ? 0.2 : 1.0);
          return (
            <div key={i} style={{
              position: 'absolute', left: 0, top: 0,
              width: fanLen, height: 4,
              transform: `translateY(-2px) rotate(${angle}deg)`,
              transformOrigin: '0 50%',
              background: `linear-gradient(90deg, transparent 0%, ${b.h} 18%, ${b.h} 78%, transparent 100%)`,
              filter: 'blur(0.6px)',
              boxShadow: `0 0 16px ${b.h}`,
              opacity: 1 - fade,
              borderRadius: 2
            }} />);

        })}
      </div>

      {/* Magenta isolation — 3 converging beams of magenta tones */}
      {TIsolate > 0 &&
      <div style={{ position: 'absolute', left: CX, top: CY, width: 0, height: 0, opacity: 1 - TReveal * 0.8 }}>
          {magenta3.map((m, i) => {
          const startAngle = -36 + (i === 0 ? 0 : i === 1 ? 0 : 0); // start from fan angles
          const startA = [-20, 0, 20][i];
          const targetA = [-15, 0, 15][i];
          const angle = lerp(startA, targetA, TConverge);
          const len = lerp(900, 380, TConverge); // beams shorten as they reach the M
          return (
            <div key={i} style={{
              position: 'absolute', left: 0, top: 0,
              width: len, height: 6,
              transform: `translateY(-3px) rotate(${angle}deg)`,
              transformOrigin: '0 50%',
              background: `linear-gradient(90deg, transparent 0%, ${m.color} 30%, ${m.color} 80%, ${m.color} 100%)`,
              boxShadow: `0 0 28px ${m.color}, 0 0 64px ${m.color}`,
              opacity: TIsolate * (1 - TReveal * 0.4),
              filter: 'blur(0.8px)',
              borderRadius: 4
            }} />);

        })}
        </div>
      }

      {/* M Reveal — uses original logo image, wiped from bottom up */}
      <div style={{
        position: 'absolute',
        left: '50%', top: `${M_TOP_PCT}%`,
        width: M_W, height: M_H,
        marginLeft: -M_W / 2, marginTop: -M_H / 2,
        opacity: logoVisible,
        transform: `scale(${lerp(1.04, 1, TReveal) * (t > 4.2 ? lerp(1, 1.015, (finalPulse - 0.85) / 0.15) : 1)})`,
        transformOrigin: 'center',
        clipPath: `inset(${wipeInset}% 0 0 0)`,
        WebkitClipPath: `inset(${wipeInset}% 0 0 0)`
      }}>
        <img src={window.M_SYMBOL_SRC || "m-symbol.png"} alt="M" style={{ width: '100%', height: '100%', display: 'block', objectFit: 'contain' }} />
      </div>

      {/* Bright flash on lock-in */}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(circle at 50% 50%, rgba(255,255,255,0.9), rgba(255,255,255,0) 60%)',
        opacity: flashOpacity,
        mixBlendMode: 'screen',
        pointerEvents: 'none',
        zIndex: 15
      }} />

      {/* Tagline */}
      <Tagline opacity={TTagline} pulse={t > 4.2 ? finalPulse : 0} />

      {/* Loop fade */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 18,
        background: '#050507',
        opacity: 1 - loopFade
      }} />
    </div>);

};

// Shared tagline component used across all variations
// ─────────────────────────────────────────────────────────────────────
// ✏️ EDIT TAGLINE TEXTS HERE (the words that appear under the M):
//    Main line:  ALQUIMIA DE NEGOCIOS  → buscar abajo "ALQUIMIA"
//    Subtitle:   CONSULTORÍA · IA · ESTRATEGIA → buscar abajo "CONSULTORÍA"
// ─────────────────────────────────────────────────────────────────────
const Tagline = ({ opacity = 1, pulse = 0 }) => {
  const ty = (1 - opacity) * 12;
  return (
    <div style={{
      position: 'absolute',
      left: '50%', top: '64%',
      transform: `translate(-50%, ${ty}px)`,
      opacity,
      textAlign: 'center',
      width: 1200
    }}>
      <div style={{
        height: 1, width: 60, margin: '0 auto 22px',
        background: 'linear-gradient(90deg, transparent, #ec4899, transparent)',
        opacity: 0.8
      }} />
      <div style={{
        fontFamily: '"Space Grotesk", system-ui, sans-serif',
        fontWeight: 500,
        fontSize: 56,
        letterSpacing: '0.32em',
        textTransform: 'uppercase',
        color: '#f6f4ef',
        textShadow: `0 0 ${20 + pulse * 18}px rgba(236, 72, 153, ${0.25 + pulse * 0.35})`
      }}>
        ALQUIMIA <span style={{ color: '#ec4899' }}>DE</span> NEGOCIOS
      </div>
      <div style={{
        marginTop: 18,
        fontFamily: '"JetBrains Mono", monospace',
        fontSize: 13,
        letterSpacing: '0.6em',
        textTransform: 'uppercase',
        color: 'rgba(246,244,239,0.45)',
        paddingLeft: '0.6em'
      }}>
        CONSULTORÍA · IA · ESTRATEGIA
      </div>
    </div>);

};

// Faint starfield background, seeded so it doesn't flicker between re-renders
const Stars = React.memo(({ seed = 1, count = 80 }) => {
  const stars = React.useMemo(() => {
    let s = seed * 12345;
    const rand = () => {s = (s * 9301 + 49297) % 233280;return s / 233280;};
    return Array.from({ length: count }, () => ({
      x: rand() * 1920,
      y: rand() * 1080,
      r: 0.5 + rand() * 1.4,
      o: 0.15 + rand() * 0.4,
      d: rand() * 4
    }));
  }, [seed, count]);
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {stars.map((s, i) =>
      <div key={i} style={{
        position: 'absolute', left: s.x, top: s.y,
        width: s.r * 2, height: s.r * 2, borderRadius: '50%',
        background: '#fff', opacity: s.o,
        boxShadow: `0 0 ${s.r * 4}px rgba(255,255,255,${s.o * 0.6})`
      }} />
      )}
    </div>);

});

window.PrismAnim = PrismAnim;
window.Tagline = Tagline;
window.Stars = Stars;