const token = new URLSearchParams(window.location.search).get("token") || "";
const TRANSLATIONS = {
  en: {
    connecting: "Connecting...",
    live: "Live",
    offline: "Offline",
    session: "Session",
    sessionControls: "Session controls",
    quickFunctions: "Quick functions",
    start: "Start",
    pause: "Pause",
    stop: "Stop",
    breathing: "Breath",
    music: "Music",
    previous: "Previous",
    next: "Next",
    masterVolume: "Master volume",
    rgbLeds: "RGB LEDs",
    whiteBar: "White bar",
    on: "On",
    off: "Off",
    playing: "Playing",
    paused: "Paused",
    active: "Active",
    notStarted: "Not started",
    blackout: "Blackout"
  },
  nl: {
    connecting: "Verbinden...",
    live: "Live",
    offline: "Offline",
    session: "Sessie",
    sessionControls: "Sessiebediening",
    quickFunctions: "Snelle functies",
    start: "Start",
    pause: "Pauze",
    stop: "Stop",
    breathing: "Adem",
    music: "Muziek",
    previous: "Vorige",
    next: "Volgende",
    masterVolume: "Mastervolume",
    rgbLeds: "RGB leds",
    whiteBar: "Witte balk",
    on: "Aan",
    off: "Uit",
    playing: "Speelt",
    paused: "Gepauzeerd",
    active: "Actief",
    notStarted: "Niet gestart",
    blackout: "Blackout"
  }
};

let currentLanguage = "en";

const els = {
  shell: document.querySelector(".remote-shell"),
  connectionState: document.querySelector("#connectionState"),
  sessionTitle: document.querySelector("#sessionTitle"),
  sessionTimer: document.querySelector("#sessionTimer"),
  phaseName: document.querySelector("#phaseName"),
  masterVolume: document.querySelector("#masterVolume"),
  masterVolumeValue: document.querySelector("#masterVolumeValue"),
  rgbIntensity: document.querySelector("#rgbIntensity"),
  rgbIntensityValue: document.querySelector("#rgbIntensityValue"),
  whiteIntensity: document.querySelector("#whiteIntensity"),
  whiteIntensityValue: document.querySelector("#whiteIntensityValue"),
  outputStatus: document.querySelector("#outputStatus"),
  audioStatus: document.querySelector("#audioStatus"),
  musicStatus: document.querySelector("#musicStatus"),
  museStatus: document.querySelector("#museStatus"),
  stateButtons: {
    breathing: document.querySelector('[data-state-button="breathing"]'),
    audio: document.querySelector('[data-state-button="audio"]'),
    output: document.querySelector('[data-state-button="output"]'),
    music: document.querySelector('[data-state-button="music"]')
  }
};

let sliderSyncPausedUntil = 0;

function t(key) {
  return TRANSLATIONS[currentLanguage]?.[key] || TRANSLATIONS.en[key] || key;
}

function applyLanguage(language) {
  currentLanguage = language === "nl" ? "nl" : "en";
  document.documentElement.lang = currentLanguage;
  document.querySelectorAll("[data-i18n]").forEach((element) => {
    element.textContent = t(element.dataset.i18n);
  });
  document.querySelectorAll("[data-i18n-aria]").forEach((element) => {
    element.setAttribute("aria-label", t(element.dataset.i18nAria));
  });
}

function endpoint(path) {
  const url = new URL(path, window.location.origin);
  if (token) url.searchParams.set("token", token);
  return url;
}

function setConnected(connected) {
  els.shell.classList.toggle("connected", connected);
  els.connectionState.value = connected ? t("live") : t("offline");
}

async function sendCommand(type, value) {
  try {
    const response = await fetch(endpoint("/remote/command"), {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ type, value })
    });
    setConnected(response.ok);
  } catch {
    setConnected(false);
  }
}

function updateSlider(input, output, value) {
  const normalized = Math.round(Number(value) || 0);
  if (Date.now() > sliderSyncPausedUntil) input.value = String(normalized);
  output.value = `${normalized}%`;
}

function boolText(value) {
  return value ? t("on") : t("off");
}

function setStateButton(button, active, label, warning = false) {
  if (!button) return;
  button.classList.toggle("is-active", Boolean(active) && !warning);
  button.classList.toggle("is-warning", Boolean(warning));
  button.setAttribute("aria-pressed", active ? "true" : "false");
  const badge = button.querySelector("span");
  if (badge) badge.textContent = label;
}

function renderState(state) {
  applyLanguage(state.language);
  const outputEnabled = Boolean(state.output?.enabled);
  const blackoutActive = Boolean(state.output?.blackout);
  const audioEnabled = Boolean(state.audio?.enabled);
  const musicPlaying = Boolean(state.audio?.musicPlaying);
  const breathingActive = Boolean(state.audio?.breathing);

  els.sessionTitle.textContent = state.session?.title || "NeuroSync Pro";
  els.sessionTimer.textContent = state.session?.timer || "--:--";
  els.phaseName.textContent = state.session?.phase || (state.session?.running ? t("active") : t("notStarted"));
  updateSlider(els.masterVolume, els.masterVolumeValue, state.controls?.masterVolume);
  updateSlider(els.rgbIntensity, els.rgbIntensityValue, state.controls?.rgbIntensity);
  updateSlider(els.whiteIntensity, els.whiteIntensityValue, state.controls?.whiteIntensity);
  els.outputStatus.textContent = `${boolText(outputEnabled)}${blackoutActive ? ` · ${t("blackout")}` : ""}`;
  els.audioStatus.textContent = boolText(audioEnabled);
  els.musicStatus.textContent = musicPlaying ? t("playing") : t("paused");
  els.museStatus.textContent = state.muse?.state
    ? `${state.muse.state} · ${state.muse.heartRate || "--"} bpm`
    : "--";
  setStateButton(els.stateButtons.breathing, breathingActive, breathingActive ? t("on") : t("off"));
  setStateButton(els.stateButtons.audio, audioEnabled, audioEnabled ? t("on") : t("off"));
  setStateButton(
    els.stateButtons.output,
    outputEnabled || blackoutActive,
    blackoutActive ? t("blackout") : outputEnabled ? t("on") : t("off"),
    blackoutActive
  );
  setStateButton(els.stateButtons.music, musicPlaying, musicPlaying ? t("playing") : t("off"));
}

async function fetchState() {
  try {
    const response = await fetch(endpoint("/remote/state"), { cache: "no-store" });
    if (!response.ok) throw new Error("state unavailable");
    renderState(await response.json());
    setConnected(true);
  } catch {
    setConnected(false);
  }
}

document.querySelectorAll("[data-command]").forEach((control) => {
  control.addEventListener("click", () => {
    void sendCommand(control.dataset.command);
  });
});

[els.masterVolume, els.rgbIntensity, els.whiteIntensity].forEach((input) => {
  input.addEventListener("input", () => {
    sliderSyncPausedUntil = Date.now() + 900;
    const output = input.id === "masterVolume"
      ? els.masterVolumeValue
      : input.id === "rgbIntensity"
        ? els.rgbIntensityValue
        : els.whiteIntensityValue;
    output.value = `${input.value}%`;
  });
  input.addEventListener("change", () => {
    sliderSyncPausedUntil = Date.now() + 900;
    void sendCommand(input.dataset.command, Number(input.value));
  });
});

void fetchState();
setInterval(fetchState, 750);
applyLanguage(currentLanguage);
