/* global React, videojs */
const { useEffect, useRef } = React;

function HyttenVideo({ url, posterUrl }) {
  const wrapRef = useRef(null);
  const playerRef = useRef(null);

  useEffect(() => {
    const u = url && String(url).trim();
    const wrap = wrapRef.current;
    if (!u || !wrap) return;

    const isHls = /\.m3u8(\?|$)/i.test(u) || /\/index\.m3u8/i.test(u);
    if (isHls && typeof videojs === 'function') {
      const videoEl = document.createElement('video');
      videoEl.className = 'video-js vjs-default-skin';
      videoEl.setAttribute('playsinline', '');
      videoEl.setAttribute('controls', '');
      videoEl.setAttribute('preload', 'metadata');
      // clear anything inside
      while (wrap.firstChild) wrap.removeChild(wrap.firstChild);
      wrap.appendChild(videoEl);
      const player = videojs(videoEl, {
        fluid: false, fill: true,
        ...(posterUrl ? { poster: posterUrl } : {}),
        html5: { vhs: { overrideNative: false } },
      });
      playerRef.current = player;
      player.src({ type: 'application/x-mpegURL', src: u });
      return () => { try { player.dispose(); } catch (e) {} playerRef.current = null; };
    } else if (!isHls) {
      // iframe fallback
      const iframe = document.createElement('iframe');
      iframe.src = u;
      iframe.allow = 'fullscreen';
      iframe.style.cssText = 'width:100%;height:100%;border:0;';
      while (wrap.firstChild) wrap.removeChild(wrap.firstChild);
      wrap.appendChild(iframe);
    }
  }, [url, posterUrl]);

  const u = url && String(url).trim();
  return (
    <div className="video-wrap">
      <div className="video-corner">
        <span className="video-corner-dot" />
        <span>Live · Hytten</span>
      </div>
      <div className="video-corner-tr" id="video-clock">
        {new Date().toLocaleTimeString('nb-NO', { hour: '2-digit', minute: '2-digit' })}
      </div>
      <div ref={wrapRef} style={{ position: 'absolute', inset: 0 }} />
      {!u && (
        <div className="video-overlay">
          <div style={{ fontSize: '0.9rem', letterSpacing: '0.18em' }}>Ingen videostrøm</div>
          <div style={{ color: 'oklch(60% 0.02 80)' }}>VIDEO_EMBED_URL ikke satt</div>
        </div>
      )}
    </div>
  );
}

window.HyttenVideo = HyttenVideo;
