(() => {
  "use strict";

  const VIDEO_ID = "kJQP7kiw5Fk";
  const OFFICIAL_URL = `https://www.youtube.com/watch?v=${VIDEO_ID}`;
  const API_URL = "https://www.youtube.com/iframe_api";
  const PREF_KEY = "apu_despacito_enabled_v5_0";
  const viewer = document.getElementById("projectViewer");
  const MOBILE_QUERY = matchMedia("(max-width: 760px)");
  const buttons = () => [...document.querySelectorAll(".music-toggle")];

  const readPreference = () => { try { return localStorage.getItem(PREF_KEY) !== "false"; } catch (_) { return true; } };
  const savePreference = value => { try { localStorage.setItem(PREF_KEY, String(value)); } catch (_) {} };
  let enabled = readPreference();
  let panel = null;
  let player = null;
  let apiPromise = null;
  let ready = false;
  let playing = false;
  let audible = false;
  let viewerActive = false;
  let retryTimer = 0;
  let verifyTimer = 0;
  let firstGestureHandled = false;
  let pendingReviewSound = false;

  const setEnabled = value => {
    enabled = Boolean(value);
    savePreference(enabled);
  };

  const updateButtons = () => {
    buttons().forEach(button => {
      button.classList.toggle("is-playing", audible);
      button.setAttribute("aria-pressed", String(enabled));
      if (button.id === "viewerMusic") {
        button.textContent = audible ? "♫ Despacito On" : enabled ? "♫ Despacito Auto" : "♫ Music Off";
      } else {
        button.title = audible ? "Pause Despacito" : enabled ? "Despacito automatic playback is enabled" : "Play Despacito";
        button.setAttribute("aria-label", button.title);
      }
    });
  };

  const setStatus = (message, state = "ready") => {
    const status = panel?.querySelector("[data-music-status]");
    if (!status) return;
    status.textContent = message;
    status.dataset.state = state;
  };

  const showManualButton = (message = "Ketuk sekali untuk mengaktifkan suara.") => {
    const button = panel?.querySelector("[data-music-start]");
    if (button) button.hidden = false;
    setStatus(message, "blocked");
  };

  const hideManualButton = () => {
    const button = panel?.querySelector("[data-music-start]");
    if (button) button.hidden = true;
  };

  const showPanel = () => panel?.classList.add("is-visible");
  const hidePanel = () => panel?.classList.remove("is-visible");

  const createPanel = () => {
    if (panel?.isConnected) return panel;
    panel = document.createElement("aside");
    panel.className = "despacito-player";
    panel.setAttribute("aria-label", "Official Despacito YouTube player");
    panel.innerHTML = `
      <div class="despacito-player__head">
        <div><small>AUTO REVIEW MUSIC</small><strong>Despacito — Official Video</strong></div>
        <button class="despacito-player__close" type="button" aria-label="Turn off review music">×</button>
      </div>
      <div class="despacito-player__media">
        <div class="despacito-player__mount" data-youtube-mount></div>
        <button class="despacito-player__start" data-music-start type="button" hidden>▶ Aktifkan suara</button>
      </div>
      <div class="despacito-player__foot">
        <span data-music-status data-state="loading">Menyiapkan pemutaran otomatis…</span>
        <a href="${OFFICIAL_URL}" target="_blank" rel="noopener noreferrer">Video resmi ↗</a>
      </div>`;
    document.body.appendChild(panel);

    const arrangeMobilePanel = () => {
      if (!MOBILE_QUERY.matches || !panel) return;
      const startButton = panel.querySelector("[data-music-start]");
      const foot = panel.querySelector(".despacito-player__foot");
      if (startButton && foot && startButton.parentElement !== foot) foot.appendChild(startButton);
    };
    arrangeMobilePanel();
    MOBILE_QUERY.addEventListener?.("change", arrangeMobilePanel);

    panel.querySelector(".despacito-player__close").addEventListener("click", () => {
      setEnabled(false);
      pause({hide: true});
    });

    panel.querySelector("[data-music-start]").addEventListener("click", () => {
      setEnabled(true);
      activateAudibleFromGesture();
    });

    return panel;
  };

  const loadYouTubeApi = () => {
    if (window.YT?.Player) return Promise.resolve(window.YT);
    if (apiPromise) return apiPromise;

    apiPromise = new Promise((resolve, reject) => {
      const previous = window.onYouTubeIframeAPIReady;
      const timeout = setTimeout(() => reject(new Error("YouTube API timeout")), 15000);

      window.onYouTubeIframeAPIReady = () => {
        clearTimeout(timeout);
        try { previous?.(); } catch (_) {}
        resolve(window.YT);
      };

      if (document.querySelector(`script[src="${API_URL}"]`)) return;
      const script = document.createElement("script");
      script.src = API_URL;
      script.async = true;
      script.onerror = () => {
        clearTimeout(timeout);
        reject(new Error("YouTube API failed to load"));
      };
      document.head.appendChild(script);
    }).catch(error => {
      apiPromise = null;
      throw error;
    });

    return apiPromise;
  };

  const readState = () => {
    if (!player || !ready) return {playing: false, audible: false};
    try {
      const isPlaying = player.getPlayerState?.() === window.YT?.PlayerState?.PLAYING;
      const hasSound = isPlaying && !player.isMuted?.() && (player.getVolume?.() ?? 0) > 0;
      return {playing: isPlaying, audible: hasSound};
    } catch (_) {
      return {playing: false, audible: false};
    }
  };

  const verifyPlayback = (allowFallback = true) => {
    clearTimeout(verifyTimer);
    verifyTimer = setTimeout(() => {
      const state = readState();
      playing = state.playing;
      audible = state.audible;

      if (audible) {
        hideManualButton();
        pendingReviewSound = false;
        setStatus("Suara aktif • volume 100%", "playing");
      } else if (playing) {
        setStatus("Musik berjalan tanpa suara • akan aktif pada interaksi pertama", "loading");
        if (allowFallback) showManualButton("Browser menahan suara otomatis. Ketuk sekali bila diperlukan.");
      } else if (enabled) {
        setStatus("Pemutaran tertunda oleh browser", "blocked");
        if (allowFallback) showManualButton();
      }
      updateButtons();
    }, 850);
  };

  const startMutedAutoplay = () => {
    if (!player || !ready || !enabled) return false;
    try {
      player.setVolume(100);
      player.mute();
      player.playVideo();
      playing = true;
      audible = false;
      setStatus("Musik dimulai • menunggu izin suara browser", "loading");
      updateButtons();
      return true;
    } catch (_) {
      return false;
    }
  };

  const tryAudibleAutoplay = () => {
    if (!player || !ready || !enabled) return false;
    try {
      player.setVolume(100);
      player.unMute();
      player.playVideo();
      setStatus("Mencoba suara otomatis…", "loading");
      verifyPlayback(false);
      return true;
    } catch (_) {
      return false;
    }
  };

  const createPlayer = async () => {
    createPanel();
    const YT = await loadYouTubeApi();
    if (player) return player;

    const mount = panel.querySelector("[data-youtube-mount]");
    const origin = /^https?:$/.test(location.protocol) ? location.origin : undefined;

    player = new YT.Player(mount, {
      width: "100%",
      height: "100%",
      videoId: VIDEO_ID,
      playerVars: {
        autoplay: 1,
        mute: 1,
        controls: 1,
        playsinline: 1,
        rel: 0,
        loop: 1,
        playlist: VIDEO_ID,
        ...(origin ? {origin} : {})
      },
      events: {
        onReady(event) {
          ready = true;
          try {
            event.target.setVolume(100);
            event.target.mute();
            const iframe = event.target.getIframe?.();
            iframe?.setAttribute("allow", "autoplay; encrypted-media; picture-in-picture; fullscreen");
            iframe?.setAttribute("playsinline", "");
          } catch (_) {}

          if (enabled) {
            showPanel();
            startMutedAutoplay();
            if (viewerActive || pendingReviewSound) {
              showManualButton("Ketuk Aktifkan suara jika browser mobile menahan audio.");
            }
            // Some browsers/sites allow audible autoplay. Try it, then fall back
            // to muted playback without interrupting the visitor experience.
            setTimeout(() => {
              if (!enabled || !ready) return;
              tryAudibleAutoplay();
              setTimeout(() => {
                const state = readState();
                if (!state.audible && enabled) startMutedAutoplay();
                verifyPlayback(true);
              }, 650);
            }, 120);
          } else {
            setStatus("Musik dinonaktifkan", "paused");
          }
        },
        onStateChange(event) {
          const isPlaying = event.data === YT.PlayerState.PLAYING;
          if (isPlaying) {
            playing = true;
            audible = !event.target.isMuted?.() && (event.target.getVolume?.() ?? 0) > 0;
            if (audible) {
              hideManualButton();
              setStatus("Suara aktif • volume 100%", "playing");
            } else {
              setStatus("Musik berjalan tanpa suara • menunggu interaksi pertama", "loading");
            }
          } else if (event.data === YT.PlayerState.PAUSED) {
            playing = false;
            audible = false;
            if (enabled) setStatus("Musik dijeda", "paused");
          } else if (event.data === YT.PlayerState.BUFFERING) {
            setStatus("Memuat audio…", "loading");
          } else if (event.data === YT.PlayerState.ENDED && enabled) {
            try { event.target.playVideo(); } catch (_) {}
          }
          updateButtons();
        },
        onAutoplayBlocked() {
          audible = false;
          startMutedAutoplay();
          showPanel();
          showManualButton("Ketuk Aktifkan suara agar Despacito terdengar di perangkat mobile.");
          updateButtons();
        },
        onError(event) {
          playing = false;
          audible = false;
          updateButtons();
          showManualButton(`Pemutar YouTube gagal (${event.data}). Buka video resmi bila diperlukan.`);
        }
      }
    });

    return player;
  };

  const prepare = async () => {
    createPanel();
    if (enabled) showPanel();
    try {
      await createPlayer();
    } catch (error) {
      console.warn("Review music preload failed:", error);
      setStatus("YouTube belum dapat dimuat. Periksa koneksi internet.", "blocked");
      showManualButton("Coba lagi untuk memuat musik");
    }
  };

  const activateAudibleFromGesture = () => {
    if (!enabled) setEnabled(true);
    showPanel();
    viewerActive = Boolean(viewer?.open) || viewerActive;
    pendingReviewSound = true;

    if (!player || !ready) {
      prepare();
      showPanel();
      showManualButton("Musik sedang dimuat. Ketuk Aktifkan suara setelah pemutar siap.");
      return false;
    }

    clearTimeout(retryTimer);
    const attempt = () => {
      try {
        player.setVolume(100);
        player.unMute();
        if (player.getPlayerState?.() !== window.YT?.PlayerState?.PLAYING) player.playVideo();
        audible = true;
        playing = true;
        setStatus("Mengaktifkan suara…", "loading");
        updateButtons();
      } catch (_) {}
    };

    // Execute synchronously inside the trusted event and retry briefly because
    // the YouTube player can still be transitioning from CUED/BUFFERING.
    attempt();
    retryTimer = setTimeout(attempt, 180);
    setTimeout(attempt, 520);
    verifyPlayback(true);
    return true;
  };

  const start = () => {
    viewerActive = true;
    panel?.classList.add("is-reviewing");
    if (!enabled) return false;
    showPanel();
    if (navigator.userActivation?.isActive) return activateAudibleFromGesture();
    prepare();
    if (ready) {
      tryAudibleAutoplay();
      setTimeout(() => {
        const state = readState();
        if (!state.audible && enabled) startMutedAutoplay();
        verifyPlayback(true);
      }, 650);
    }
    return true;
  };

  const pause = ({hide = false} = {}) => {
    playing = false;
    audible = false;
    clearTimeout(retryTimer);
    clearTimeout(verifyTimer);
    try { player?.pauseVideo?.(); } catch (_) {}
    if (hide) hidePanel();
    setStatus(enabled ? "Musik dijeda" : "Musik dinonaktifkan", "paused");
    updateButtons();
  };

  const stop = () => {
    viewerActive = false;
    panel?.classList.remove("is-reviewing");
    // Keep automatic site music running after the project closes. Only pause
    // when the user explicitly turns it off or the tab becomes hidden.
    if (enabled) {
      showPanel();
      if (ready) {
        if (navigator.userActivation?.isActive) activateAudibleFromGesture();
        else startMutedAutoplay();
      }
    }
  };

  const toggle = () => {
    if (enabled) {
      setEnabled(false);
      pause({hide: true});
    } else {
      setEnabled(true);
      activateAudibleFromGesture();
    }
  };

  const handleTrustedGesture = event => {
    if (!event.isTrusted || !enabled) return;
    const target = event.target;
    if (target?.closest?.(".music-toggle,.despacito-player__close,[data-music-start]")) return;
    if (target?.closest?.("input,textarea,select,[contenteditable='true']") && !viewer?.open) return;

    if (!firstGestureHandled || !readState().audible) {
      firstGestureHandled = true;
      activateAudibleFromGesture();
    }
  };

  const handleProjectLaunchGesture = event => {
    if (!event.isTrusted || !enabled) return;
    if (!event.target?.closest?.("[data-launch]")) return;
    viewerActive = true;
    pendingReviewSound = true;
    showPanel();
    activateAudibleFromGesture();
  };

  document.addEventListener("pointerdown", handleProjectLaunchGesture, {capture: true, passive: true});
  document.addEventListener("touchend", handleProjectLaunchGesture, {capture: true, passive: true});
  document.addEventListener("click", handleProjectLaunchGesture, {capture: true});

  document.addEventListener("pointerdown", handleTrustedGesture, {capture: true, passive: true});
  document.addEventListener("touchstart", handleTrustedGesture, {capture: true, passive: true});
  document.addEventListener("keydown", event => {
    if (["Tab", "Shift", "Control", "Alt", "Meta"].includes(event.key)) return;
    handleTrustedGesture(event);
  }, {capture: true});

  document.addEventListener("click", event => {
    if (event.target.closest?.(".music-toggle")) {
      event.preventDefault();
      event.stopPropagation();
      toggle();
    }
  }, {capture: true});

  document.addEventListener("visibilitychange", () => {
    if (document.hidden) {
      try { player?.pauseVideo?.(); } catch (_) {}
      playing = false;
      audible = false;
      updateButtons();
    } else if (enabled) {
      showPanel();
      if (navigator.userActivation?.isActive) activateAudibleFromGesture();
      else if (ready) startMutedAutoplay();
    }
  });

  window.addEventListener("pageshow", () => {
    if (enabled) prepare();
  });

  window.APUReviewMusic = {
    prepare,
    start,
    startFromGesture: activateAudibleFromGesture,
    resumeWithSound: activateAudibleFromGesture,
    stop,
    pauseReview: pause,
    toggle,
    isPlaying: () => playing,
    isAudible: () => audible,
    isReady: () => ready
  };

  const boot = () => {
    updateButtons();
    if (enabled) {
      createPanel();
      showPanel();
      // Start immediately instead of waiting for the visitor to open a project.
      prepare();
    }
  };

  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot, {once: true});
  else boot();
})();
