/* global React */
// IntroSplash — fullscreen brand video intro that plays on every page load.
// Mobile-first: object-fit cover, muted autoplay, playsinline.
// Skippable via tap/click or a "skip" button (visible after 800ms).

const { useState: useStateIntro, useEffect: useEffectIntro, useRef: useRefIntro } = React;

function IntroSplash({ src = '/landing-original/assets/intro.mp4', maxDuration = 30000 }) {
  const [visible, setVisible] = useStateIntro(true);
  const [closing, setClosing] = useStateIntro(false);
  const [showSkip, setShowSkip] = useStateIntro(true);
  const [videoReady, setVideoReady] = useStateIntro(false);
  const [muted, setMuted] = useStateIntro(true);
  const videoRef = useRefIntro(null);
  const closeTimerRef = useRefIntro(null);
  const closedRef = useRefIntro(false);

  // Lock body scroll while visible
  useEffectIntro(() => {
    if (!visible) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prevOverflow; };
  }, [visible]);

  // Show skip button after 800ms
  useEffectIntro(() => {
    const t = setTimeout(() => setShowSkip(true), 800);
    return () => clearTimeout(t);
  }, []);

  // Safety-net timer — set to maxDuration initially, replaced once metadata loads
  useEffectIntro(() => {
    closeTimerRef.current = setTimeout(() => handleClose(), maxDuration);
    return () => clearTimeout(closeTimerRef.current);
    // eslint-disable-next-line
  }, []);

  // Try to play video on mount
  useEffectIntro(() => {
    const v = videoRef.current;
    if (!v) return;
    const tryPlay = async () => {
      try {
        await v.play();
      } catch (e) {
        // autoplay blocked → keep splash visible briefly then close
        setTimeout(handleClose, 1800);
      }
    };
    tryPlay();
    // eslint-disable-next-line
  }, []);

  const handleClose = () => {
    if (closedRef.current) return;
    closedRef.current = true;
    setClosing(true);
    setTimeout(() => setVisible(false), 600);
  };

  const closeWhenVideoIsDone = () => {
    const v = videoRef.current;
    if (!v || !v.duration || !isFinite(v.duration)) return;
    if (v.ended || v.currentTime >= v.duration - 0.18) handleClose();
  };

  const handleLoadedMetadata = (e) => {
    setVideoReady(true);
    const v = e.currentTarget;
    if (v.duration && isFinite(v.duration)) {
      // Replace safety-net timer with one based on actual duration + small buffer
      clearTimeout(closeTimerRef.current);
      closeTimerRef.current = setTimeout(handleClose, v.duration * 1000 + 800);
    }
  };

  const toggleMute = (e) => {
    e.stopPropagation();
    const v = videoRef.current;
    if (!v) return;
    v.muted = !v.muted;
    setMuted(v.muted);
  };

  if (!visible) return null;

  return (
    <div
      className={"intro " + (closing ? "intro-closing" : "")}
      onClick={handleClose}
      role="dialog"
      aria-label="Apresentação Gorilla Barber"
    >
      <div className="intro-video-wrap">
        <video
          ref={videoRef}
          className={"intro-video " + (videoReady ? "intro-video-ready" : "")}
          src={src}
          autoPlay
          muted
          playsInline
          preload="auto"
          onLoadedMetadata={handleLoadedMetadata}
          onCanPlay={() => setVideoReady(true)}
          onTimeUpdate={closeWhenVideoIsDone}
          onEnded={handleClose}
          onPause={closeWhenVideoIsDone}
        />
        {/* Static fallback while video loads or if it fails */}
        <div className={"intro-fallback " + (videoReady ? "intro-fallback-hidden" : "")}>
          <img src="/landing-original/assets/brand-head-transparent.png" alt="" className="intro-fallback-head" />
          <div className="intro-fallback-text">
            <span className="intro-fallback-l">GORILLA</span>
            <span className="intro-fallback-r">BARBER APP</span>
          </div>
        </div>

        {/* Vignette */}
        <div className="intro-vignette" />
      </div>

      {/* Brand watermark */}
      <div className="intro-brand">
        <span className="intro-brand-text">
          <span>GORILLA</span><span style={{color:'var(--accent-soft)'}}>BARBER APP</span>
        </span>
      </div>

      {/* Audio toggle */}
      <button
        className={"intro-mute " + (showSkip ? "intro-mute-in" : "")}
        onClick={toggleMute}
        aria-label={muted ? "Ativar som" : "Desativar som"}
      >
        {muted ? (
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>
            <line x1="22" y1="9" x2="16" y2="15"/>
            <line x1="16" y1="9" x2="22" y2="15"/>
          </svg>
        ) : (
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/>
            <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>
            <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>
          </svg>
        )}
        <span>{muted ? "Ativar som" : "Som ligado"}</span>
      </button>

      {/* Skip button */}
      <button
        className={"intro-skip " + (showSkip ? "intro-skip-in" : "")}
        onClick={(e) => { e.stopPropagation(); handleClose(); }}
        aria-label="Pular introdução"
      >
        <span>Pular</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="5" y1="12" x2="19" y2="12"/>
          <polyline points="12 5 19 12 12 19"/>
        </svg>
      </button>

      {/* Loading hint at start */}
      <div className={"intro-hint " + (videoReady ? "intro-hint-out" : "")}>
        <span className="intro-hint-dot" />
        <span className="intro-hint-dot" style={{animationDelay:'.18s'}} />
        <span className="intro-hint-dot" style={{animationDelay:'.36s'}} />
      </div>

      <style>{`
        .intro {
          position: fixed;
          inset: 0;
          z-index: 999999;
          background: #000;
          display: flex; align-items: center; justify-content: center;
          cursor: pointer;
          opacity: 1;
          transition: opacity .55s cubic-bezier(.4,0,.2,1);
        }
        .intro-closing {
          opacity: 0;
          pointer-events: none;
        }
        .intro-video-wrap {
          position: absolute; inset: 0;
          overflow: hidden;
        }
        .intro-video {
          width: 100%;
          height: 100%;
          object-fit: cover;
          opacity: 0;
          transition: opacity .5s ease;
          background: #000;
        }
        .intro-video-ready { opacity: 1; }

        .intro-fallback {
          position: absolute; inset: 0;
          display: flex; flex-direction: column; align-items: center; justify-content: center;
          gap: 28px;
          background: radial-gradient(closest-side, rgba(255,65,3,.18), transparent 70%), #0F1115;
          transition: opacity .6s ease;
        }
        .intro-fallback-hidden { opacity: 0; pointer-events: none; }
        .intro-fallback-head {
          width: min(48vw, 380px);
          filter: drop-shadow(0 30px 80px rgba(255,65,3,.45));
          animation: introBreath 2.4s ease-in-out infinite alternate;
        }
        @keyframes introBreath {
          from { transform: scale(.96); filter: drop-shadow(0 30px 80px rgba(255,65,3,.3)); }
          to   { transform: scale(1.02); filter: drop-shadow(0 40px 110px rgba(255,65,3,.55)); }
        }
        .intro-fallback-text {
          display: flex; gap: 12px;
          font-family: var(--font-display);
          font-size: clamp(24px, 4vw, 44px);
          letter-spacing: .04em;
          color: var(--ink);
        }

        .intro-vignette {
          position: absolute; inset: 0;
          pointer-events: none;
          background: radial-gradient(closest-side at 50% 60%, transparent 40%, rgba(0,0,0,.55) 100%);
        }

        .intro-brand {
          position: absolute;
          top: clamp(24px, 4vh, 48px);
          left: 50%;
          transform: translateX(-50%);
          opacity: 0;
          animation: introBrandIn 1s ease .3s forwards;
        }
        @keyframes introBrandIn {
          from { opacity: 0; transform: translate(-50%, -12px); }
          to   { opacity: 1; transform: translate(-50%, 0); }
        }
        .intro-brand-text {
          font-family: var(--font-display);
          font-size: clamp(18px, 2.5vw, 28px);
          letter-spacing: .12em;
          color: var(--ink);
          display: inline-flex; gap: 6px;
          text-shadow: 0 2px 24px rgba(0,0,0,.6);
        }

        .intro-skip {
          position: absolute;
          bottom: clamp(20px, 4vh, 40px);
          right: clamp(20px, 4vw, 40px);
          padding: 10px 18px;
          background: rgba(255,255,255,.08);
          -webkit-backdrop-filter: blur(12px);
          backdrop-filter: blur(12px);
          border: 1px solid rgba(255,255,255,.15);
          color: var(--ink);
          border-radius: 999px;
          font-family: var(--font-body);
          font-size: 13px;
          font-weight: 500;
          letter-spacing: .04em;
          cursor: pointer;
          display: inline-flex; align-items: center; gap: 8px;
          opacity: 0;
          transform: translateY(8px);
          transition: opacity .4s ease, transform .4s ease, background .15s ease;
        }
        .intro-skip-in { opacity: 1; transform: none; }
        .intro-skip:hover { background: rgba(255,65,3,.3); border-color: rgba(255,65,3,.6); }

        .intro-mute {
          position: absolute;
          bottom: clamp(20px, 4vh, 40px);
          left: clamp(20px, 4vw, 40px);
          padding: 10px 16px;
          background: rgba(255,255,255,.08);
          -webkit-backdrop-filter: blur(12px);
          backdrop-filter: blur(12px);
          border: 1px solid rgba(255,255,255,.15);
          color: var(--ink);
          border-radius: 999px;
          font-family: var(--font-body);
          font-size: 13px;
          font-weight: 500;
          letter-spacing: .04em;
          cursor: pointer;
          display: inline-flex; align-items: center; gap: 8px;
          opacity: 0;
          transform: translateY(8px);
          transition: opacity .4s ease, transform .4s ease, background .15s ease;
        }
        .intro-mute-in { opacity: 1; transform: none; }
        .intro-mute:hover { background: rgba(255,65,3,.3); border-color: rgba(255,65,3,.6); }
        @media (max-width: 600px) {
          .intro-mute { padding: 8px 12px; font-size: 12px; }
          .intro-mute span { display: none; }
        }

        .intro-hint {
          position: absolute;
          bottom: clamp(24px, 6vh, 64px);
          left: 50%;
          transform: translateX(-50%);
          display: inline-flex; gap: 6px;
          transition: opacity .35s ease;
        }
        .intro-hint-out { opacity: 0; }
        .intro-hint-dot {
          width: 6px; height: 6px;
          border-radius: 50%;
          background: var(--accent);
          animation: introDot 1.2s ease-in-out infinite;
        }
        @keyframes introDot {
          0%, 80%, 100% { opacity: .25; transform: scale(.8); }
          40%           { opacity: 1;   transform: scale(1.2); }
        }

        @media (max-width: 600px) {
          .intro-skip { padding: 8px 14px; font-size: 12px; }
        }
      `}</style>
    </div>
  );
}

window.IntroSplash = IntroSplash;
