/* global React */
const { useState, useEffect } = React;

const fmtTime = (s) => {
  if (!Number.isFinite(s)) return '0:00';
  const m = Math.floor(s / 60);
  const ss = Math.floor(s % 60).toString().padStart(2, '0');
  return `${m}:${ss}`;
};

// ─────────────────────────────────────────────────────────────
// YouTubePlayer — clean iframe embed in a rounded card
// ─────────────────────────────────────────────────────────────
function YouTubePlayer({ t, label, youtubeId }) {
  // Thumbnail + tap-to-open design.
  // Opens the video in a new tab on youtube.com (works regardless of embed settings).
  const thumb = `https://i.ytimg.com/vi/${youtubeId}/maxresdefault.jpg`;
  const fallbackThumb = `https://i.ytimg.com/vi/${youtubeId}/hqdefault.jpg`;
  const watchUrl = `https://www.youtube.com/watch?v=${youtubeId}`;

  return (
    <a
      href={watchUrl}
      target="_blank"
      rel="noopener noreferrer"
      style={{
        position: 'relative', display: 'block', width: '100%',
        aspectRatio: '16 / 9', borderRadius: 20, overflow: 'hidden',
        background: '#000', textDecoration: 'none',
        boxShadow: `0 18px 36px ${t.primary}33`,
        cursor: 'pointer',
      }}
    >
      <img
        src={thumb}
        alt={label}
        onError={(e) => {
          if (e.currentTarget.src !== fallbackThumb) e.currentTarget.src = fallbackThumb;
        }}
        style={{
          position: 'absolute', inset: 0,
          width: '100%', height: '100%', objectFit: 'cover',
          display: 'block',
        }}
      />

      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(180deg, rgba(0,0,0,0.0) 0%, rgba(0,0,0,0.15) 55%, rgba(0,0,0,0.55) 100%), ${t.primary}33`,
        mixBlendMode: 'multiply',
      }} />

      {label && (
        <div style={{
          position: 'absolute', top: 12, left: 12,
          fontFamily: 'Geist Mono, monospace',
          fontSize: 10, fontWeight: 500, letterSpacing: '0.1em',
          color: '#fff', textTransform: 'uppercase',
          padding: '5px 9px', borderRadius: 100,
          background: 'rgba(0,0,0,0.55)',
          backdropFilter: 'blur(20px)',
          WebkitBackdropFilter: 'blur(20px)',
          border: '1px solid rgba(255,255,255,0.18)',
        }}>{label}</div>
      )}

      <div style={{
        position: 'absolute', top: 12, right: 12,
        display: 'flex', alignItems: 'center', gap: 6,
        fontFamily: 'Geist Mono, monospace',
        fontSize: 10, fontWeight: 500, letterSpacing: '0.08em',
        color: '#fff', textTransform: 'uppercase',
        padding: '5px 10px', borderRadius: 100,
        background: 'rgba(0,0,0,0.55)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        border: '1px solid rgba(255,255,255,0.18)',
      }}>
        <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
          <path d="M3 1h6v6M9 1L4 6M3 4v5h5" stroke="#fff" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
        YouTube
      </div>

      <div style={{
        position: 'absolute', top: '50%', left: '50%',
        transform: 'translate(-50%, -50%)',
        width: 64, height: 64, borderRadius: 32,
        background: 'rgba(255,255,255,0.96)', color: t.primary,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 10px 30px rgba(0,0,0,0.4)',
        transition: 'transform 180ms ease',
      }}
      onMouseEnter={(e) => e.currentTarget.style.transform = 'translate(-50%, -50%) scale(1.06)'}
      onMouseLeave={(e) => e.currentTarget.style.transform = 'translate(-50%, -50%) scale(1)'}
      >
        <svg width="22" height="22" viewBox="0 0 22 22"><path d="M7 4.5v13l11-6.5L7 4.5z" fill="currentColor"/></svg>
      </div>

      <div style={{
        position: 'absolute', bottom: 14, left: 0, right: 0,
        textAlign: 'center',
        fontFamily: 'Geist Mono, monospace',
        fontSize: 9.5, letterSpacing: '0.15em', textTransform: 'uppercase',
        color: 'rgba(255,255,255,0.85)',
        textShadow: '0 1px 3px rgba(0,0,0,0.4)',
      }}>
        Tap to watch on YouTube
      </div>
    </a>
  );
}

// ─────────────────────────────────────────────────────────────
// VideoPlayer — wrapper: real YouTube if id given, else simulated
// ─────────────────────────────────────────────────────────────
function VideoPlayer({ t, label, duration = 92, autoStart = false, posterTitle, posterSubtitle, accentLabel, youtubeId }) {
  if (youtubeId) {
    return <YouTubePlayer t={t} label={label} youtubeId={youtubeId} />;
  }

  // ── Simulated fallback (unchanged) ───────────────────────
  const [playing, setPlaying] = useState(autoStart);
  const [progress, setProgress] = useState(0);
  const [muted, setMuted] = useState(false);

  useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setProgress((p) => {
        if (p >= duration) { setPlaying(false); return duration; }
        return p + 0.5;
      });
    }, 250);
    return () => clearInterval(id);
  }, [playing, duration]);

  const pct = (progress / duration) * 100;

  return (
    <div style={{
      position: 'relative', width: '100%', aspectRatio: '9 / 12',
      borderRadius: 24, overflow: 'hidden',
      background: t.primary,
      boxShadow: `0 18px 36px ${t.primary}33`,
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `repeating-linear-gradient(135deg, ${t.primary} 0 24px, ${t.primaryDeep} 24px 48px)`,
        opacity: playing ? 0.5 : 1,
        transition: 'opacity 400ms ease',
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(0,0,0,0) 30%, rgba(0,0,0,0.55) 100%)',
      }} />
      {playing && (
        <div style={{
          position: 'absolute', inset: '-20%',
          background: `radial-gradient(circle at 30% 40%, ${t.accent}66 0%, transparent 40%), radial-gradient(circle at 70% 60%, #4a7ba6aa 0%, transparent 45%)`,
          animation: 'drift 8s ease-in-out infinite alternate',
          mixBlendMode: 'screen',
        }} />
      )}

      <div style={{
        position: 'absolute', top: 16, left: 16, right: 16,
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
      }}>
        <div style={{
          fontFamily: 'Geist Mono, monospace',
          fontSize: 10, fontWeight: 500, letterSpacing: '0.1em',
          color: '#fff', textTransform: 'uppercase',
          padding: '6px 10px', borderRadius: 100,
          background: 'rgba(255,255,255,0.18)',
          backdropFilter: 'blur(20px)',
          WebkitBackdropFilter: 'blur(20px)',
          border: '1px solid rgba(255,255,255,0.22)',
        }}>{label}</div>
        <div style={{
          fontFamily: 'Geist Mono, monospace',
          fontSize: 10, color: 'rgba(255,255,255,0.85)',
          padding: '6px 10px', borderRadius: 100,
          background: 'rgba(0,0,0,0.25)',
          backdropFilter: 'blur(20px)',
        }}>{fmtTime(duration - progress)}</div>
      </div>

      <div style={{
        position: 'absolute', inset: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: 28, textAlign: 'center',
        opacity: playing ? 0 : 1, transition: 'opacity 300ms',
      }}>
        <div style={{
          fontFamily: '"Instrument Serif", Georgia, serif',
          fontSize: 34, lineHeight: 1.05, color: '#fff',
          letterSpacing: '-0.02em', fontWeight: 400,
          textWrap: 'balance',
        }}>{posterTitle}</div>
        {posterSubtitle && (
          <div style={{
            marginTop: 10,
            fontFamily: 'Geist, system-ui, sans-serif',
            fontSize: 13, color: 'rgba(255,255,255,0.78)',
            maxWidth: 240, lineHeight: 1.4,
          }}>{posterSubtitle}</div>
        )}
      </div>

      <button
        onClick={() => setPlaying(!playing)}
        style={{
          position: 'absolute', bottom: 76, left: '50%', transform: 'translateX(-50%)',
          width: 60, height: 60, borderRadius: 30, border: 'none',
          background: '#fff', color: t.primary,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
          boxShadow: '0 6px 20px rgba(0,0,0,0.25)',
        }}
      >
        {playing ? (
          <svg width="18" height="18" viewBox="0 0 20 20"><rect x="5" y="4" width="4" height="12" rx="1" fill="currentColor"/><rect x="11" y="4" width="4" height="12" rx="1" fill="currentColor"/></svg>
        ) : (
          <svg width="20" height="20" viewBox="0 0 22 22"><path d="M7 4.5v13l11-6.5L7 4.5z" fill="currentColor"/></svg>
        )}
      </button>

      <div style={{
        position: 'absolute', bottom: 20, left: 16, right: 16,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{
          flex: 1, height: 3, borderRadius: 2,
          background: 'rgba(255,255,255,0.25)', position: 'relative',
        }}>
          <div style={{
            position: 'absolute', left: 0, top: 0, bottom: 0,
            width: `${pct}%`, background: '#fff', borderRadius: 2,
            transition: playing ? 'width 250ms linear' : 'none',
          }} />
          <div style={{
            position: 'absolute', left: `${pct}%`, top: '50%',
            width: 10, height: 10, borderRadius: 5, background: '#fff',
            transform: 'translate(-50%, -50%)',
            boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
            transition: playing ? 'left 250ms linear' : 'none',
          }} />
        </div>
        <button
          onClick={() => setMuted(!muted)}
          style={{
            width: 28, height: 28, borderRadius: 14, border: 'none',
            background: 'rgba(255,255,255,0.18)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}
        >
          {muted ? (
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 5v4h2l3 3V2L4 5H2z" fill="#fff"/><path d="M11 4l-3 3M8 4l3 3" stroke="#fff" strokeWidth="1.4" strokeLinecap="round"/></svg>
          ) : (
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 5v4h2l3 3V2L4 5H2z" fill="#fff"/><path d="M9 4.5c1 .8 1.5 1.6 1.5 2.5s-.5 1.7-1.5 2.5" stroke="#fff" strokeWidth="1.2" strokeLinecap="round" fill="none"/></svg>
          )}
        </button>
      </div>

      {accentLabel && (
        <div style={{
          position: 'absolute', bottom: 60, right: 16,
          fontFamily: 'Geist Mono, monospace', fontSize: 9,
          letterSpacing: '0.15em', textTransform: 'uppercase',
          color: 'rgba(255,255,255,0.55)',
        }}>{accentLabel}</div>
      )}
    </div>
  );
}

Object.assign(window, { VideoPlayer, YouTubePlayer });
