// Shared video-player component (teaser mode + full player with controls)
// Exports: VideoPlayer

function VideoPlayer({
  variant = "full",        // "teaser" | "full"
  duration = 847,          // seconds
  posterSubtitle = "And finally, I realized\u2026",
  onProgressChange,        // (percent 0-100) callback
  autoHideControls = true,
  freeBadge = "Free video",
  gate = null,             // required % to unlock
  onPlay = null,           // callback when teaser play is clicked
  poster = null,           // background image URL
  showSubtitle: showSubtitleProp = true,
  showFigure = true,
}) {
  const [playing, setPlaying] = React.useState(false);
  const [current, setCurrent] = React.useState(0); // seconds
  const [buffered, setBuffered] = React.useState(0.18);
  const [muted, setMuted] = React.useState(false);
  const intervalRef = React.useRef(null);

  const fmt = (s) => {
    s = Math.max(0, Math.floor(s));
    const m = Math.floor(s / 60);
    const ss = s % 60;
    return `${m}:${ss.toString().padStart(2,"0")}`;
  };

  React.useEffect(() => {
    if (playing) {
      intervalRef.current = setInterval(() => {
        setCurrent((c) => {
          const next = Math.min(duration, c + 1);
          if (next >= duration) { clearInterval(intervalRef.current); setPlaying(false); }
          return next;
        });
        setBuffered((b) => Math.min(1, b + 0.005));
      }, 1000);
    }
    return () => clearInterval(intervalRef.current);
  }, [playing, duration]);

  React.useEffect(() => {
    if (onProgressChange) onProgressChange((current / duration) * 100);
  }, [current, duration, onProgressChange]);

  const pct = (current / duration) * 100;

  const togglePlay = (e) => {
    e && e.stopPropagation();
    if (variant === "teaser" && onPlay) {
      onPlay();
      return;
    }
    setPlaying((p) => !p);
  };

  const seek = (e) => {
    e.stopPropagation();
    const rect = e.currentTarget.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const newPct = Math.max(0, Math.min(1, x / rect.width));
    setCurrent(newPct * duration);
  };

  // Always show subtitle until playing starts moving
  const showSubtitle = showSubtitleProp && (!playing || current < 3);

  return (
    <div
      className={`vp ${variant === "full" ? "vp--large" : ""} ${playing ? "is-playing" : ""}`}
      onClick={togglePlay}
      role="button"
      aria-label={playing ? "Pause video" : "Play video"}
    >
      {poster ? (
        <div className="vp-poster" style={{ backgroundImage: `url(${poster})` }}></div>
      ) : (
        <>
          <div className="vp-bg"></div>
          {showFigure && (
            <div className="vp-figure">
              <div className="silhouette"></div>
            </div>
          )}
          {showFigure && <div className="vp-mic"></div>}
        </>
      )}

      {variant === "teaser" && (
        <div className="vp-freebadge">{freeBadge}</div>
      )}

      <div className="vp-duration">{fmt(duration - current)}</div>

      {showSubtitle && (
        <div className="vp-subtitle">{posterSubtitle}</div>
      )}

      {!playing && (
        <div className="vp-play">
          <svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
        </div>
      )}

      {variant === "full" && (
        <div className="vp-controls" onClick={(e) => e.stopPropagation()}>
          <div className="vp-progress" onClick={seek}>
            <div className="vp-progress-buffered" style={{width: `${buffered*100}%`}}></div>
            <div className="vp-progress-fill" style={{width: `${pct}%`}}></div>
            <div className="vp-progress-thumb" style={{left: `${pct}%`}}></div>
          </div>
          <div className="vp-ctrls-row">
            <button className="vp-icon-btn" onClick={togglePlay} aria-label="Play/Pause">
              {playing ? (
                <svg viewBox="0 0 24 24"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>
              ) : (
                <svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
              )}
            </button>
            <button className="vp-icon-btn" onClick={(e) => { e.stopPropagation(); setMuted(m => !m); }} aria-label="Mute">
              {muted ? (
                <svg viewBox="0 0 24 24"><path d="M7 9v6h4l5 5V4l-5 5H7zm9.5 3l2.5-2.5-1.4-1.4L15 10.6l-2.6-2.6-1.4 1.4L13.6 12l-2.6 2.6 1.4 1.4L15 13.4l2.6 2.6 1.4-1.4L16.5 12z"/></svg>
              ) : (
                <svg viewBox="0 0 24 24"><path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3a4.5 4.5 0 00-2.5-4v8a4.5 4.5 0 002.5-4zM14 3.23v2.06A7 7 0 0119 12a7 7 0 01-5 6.71v2.06a9 9 0 000-17.54z"/></svg>
              )}
            </button>
            <span className="vp-time">{fmt(current)} / {fmt(duration)}</span>
            <span className="spacer"></span>
            <span className="vp-brand">CASHY.ONE</span>
            <button className="vp-icon-btn" aria-label="Fullscreen" onClick={(e)=>e.stopPropagation()}>
              <svg viewBox="0 0 24 24"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

window.VideoPlayer = VideoPlayer;
