/*
    "צבע שחור" — חלונית התוסף (עיצוב Material 3).
    מסך יחיד של היסטוריית התרעות + מסך הגדרות פנימי (גלגל שיניים → חזרה).
    עברית בלבד; צליל יחיד (פעמון) — ר' Preferences.js.
*/
var siteLanguage = "HE";
var allCities = [];
var allAreas = [];

City.loadDataSync();

window.addEventListener("load", async () => {
  siteLanguage = await Preferences.getSelectedLanguage(); // תמיד "HE" (מסנכרן City.siteLanguage)
  allCities = await City.getAllCities();
  allAreas = await City.getAllAreas();
  await loadSettings().catch(console.error);
  loadHistory();
});

/* ============ ניווט בין מסכים ============ */
const historyScreen = document.getElementById("historyScreen");
const settingsScreen = document.getElementById("settingsScreen");

document.getElementById("openSettings").onclick = () => {
  historyScreen.hidden = true;
  settingsScreen.hidden = false;
  settingsScreen.querySelector(".screen-body").scrollTop = 0;
};

document.getElementById("backFromSettings").onclick = () => {
  settingsScreen.hidden = true;
  historyScreen.hidden = false;
  loadHistory(); // רענון בחזרה למסך ההיסטוריה
};

/* ============ היסטוריית התרעות ============ */
// סוגי אירוע עם אייקון ייעודי (eventIconSvg ב-Localization.js: 0/2/3/8); אחרת נופלים ל-8.
const ICON_EVENT_TYPES = [0, 2, 3, 8];

async function loadHistory() {
  const homeBody = historyScreen.querySelector(".screen-body");
  let history = document.getElementById("history");
  if (history) history.remove();
  history = document.createElement("div");
  history.id = "history";

  const feed = await fetch(ALERTS_HISTORY_URL)
    .then((r) => r.json())
    .catch(() => []);

  (Array.isArray(feed) ? feed : []).forEach((data) => {
    if (!data || !Array.isArray(data.alerts)) return; // הגנה מפני מבנה ריק/שונה

    const historyItem = new History(data);
    const dateString = historyItem.getDate();
    const citiesNames = historyItem.getCitiesNames();
    const first = data.alerts[0] || {};

    let primaryEvent = historyItem.getThreatsIDs()[0];
    if (!ICON_EVENT_TYPES.includes(primaryEvent)) primaryEvent = 8;

    // מיקום מדויק = "עיר, כתובת" (address משודר מהשרת); הערה (note) נוספת אם קיימת
    const locationText =
      citiesNames.join(", ") + (first.address ? ", " + first.address : "");

    // בנייה עם textContent (לא innerHTML) — קשיחות מפני HTML בשמות/כתובת מהשרת (Stored XSS)
    const item = document.createElement("div");
    item.className = "history_item";

    // אייקון מוביל = SVG outline ייעודי לפי סוג האירוע (eventIconSvg ב-Localization.js)
    const icon = document.createElement("span");
    icon.className = "hi-icon";
    icon.setAttribute("data-event", String(primaryEvent));
    icon.innerHTML = eventIconSvg(primaryEvent, 22); // מקור מהימן (מחרוזת קבועה, ללא קלט משתמש)

    const body = document.createElement("div");
    body.className = "hi-body";

    // כותרת = סוג האירוע (במקום גוש-אזור)
    const title = document.createElement("div");
    title.className = "hi-title";
    title.textContent = City.getLocalizationEventTypeTitle(primaryEvent);

    const time = document.createElement("div");
    time.className = "hi-time";
    time.textContent = dateString;

    const location = document.createElement("div");
    location.className = "hi-cities";
    location.textContent = locationText;

    body.append(title, time, location);

    if (first.note) {
      const note = document.createElement("div");
      note.className = "hi-note";
      note.textContent = first.note;
      body.appendChild(note);
    }

    item.append(icon, body);

    // כל התראה ניתנת ללחיצה → פותחת את חלון ההתראה (alert.html) לאותו אירוע,
    // עם אותה פריסה (מיקום למעלה, הערה, מפה) + כפתור "מרחק מהמיקום שלי".
    item.setAttribute("role", "button");
    item.tabIndex = 0;
    const open = () => openHistoryMap(primaryEvent, citiesNames.join(", "), first);
    item.onclick = open;
    item.onkeydown = (e) => {
      if (e.key === "Enter" || e.key === " ") {
        e.preventDefault();
        open();
      }
    };

    history.appendChild(item);
  });

  if (!history.children.length) {
    const empty = document.createElement("p");
    empty.className = "history_empty";
    empty.textContent = STRINGS.noHistory.he;
    history.appendChild(empty);
  }

  homeBody.appendChild(history);
}

// פתיחת חלון ההתראה (alert.html) במצב "היסטוריה": נתוני האירוע מועברים ב-query params
// (alert.html קורא אותם ב-renderFromParams ואינו נרשם לעדכוני background). אותה פריסה
// בדיוק כמו חלון התראה חי, כולל כפתור "מרחק מהמיקום שלי".
function openHistoryMap(eventType, cityName, alert) {
  const params = new URLSearchParams();
  params.set("history", "1");
  params.set("eventType", String(eventType));
  params.set("city", cityName);
  if (alert.address) params.set("address", alert.address);
  if (alert.note) params.set("note", alert.note);
  if (typeof alert.lat === "number") params.set("lat", String(alert.lat));
  if (typeof alert.lng === "number") params.set("lng", String(alert.lng));

  const W = 420;
  const H = 460;
  chrome.windows.create({
    url: chrome.runtime.getURL("alert.html") + "?" + params.toString(),
    type: "popup",
    width: W,
    height: H,
    focused: true,
    left: 0,
    top: Math.max(0, (screen.height || 800) - H),
  });
}

/* ============ אזורי עניין (חיפוש + בחירה) ============ */
var selectionCitiesIDs = [];
var selectionAreaIDs = [];
var founds = [];
var currentFocusIndex;

const searchInput = document.getElementById("search");
const silentNotSelectedBox = document.getElementById("silentNotSelectedBox");

const normalize = (s) =>
  s.toLowerCase().replace(/[0-9 ~`!@#$%^&*()+={}\[\];\-\:\'\"<>.,\/\\\?-_]/g, "");

searchInput.oninput = function () {
  const searchText = this.value;
  const existing = document.getElementById("autocomplete");
  if (existing) existing.remove();
  if (!searchText) return;

  const q = normalize(searchText);
  founds = [
    ...allAreas.filter((area) => normalize(area.getLocalizationAreaName()).includes(q)),
    ...allCities.filter((city) => normalize(city.getLocalizationCityName()).includes(q)),
  ].slice(0, 50);
  if (!founds.length) return;

  const autocomplete = document.createElement("div");
  autocomplete.id = "autocomplete";

  founds.forEach((found, index) => {
    const option = document.createElement("button");
    option.type = "button";
    option.className = "ac-option";

    if (found instanceof City) {
      const cityEl = document.createElement("span");
      cityEl.className = "ac-city";
      cityEl.textContent = found.getLocalizationCityName();
      const areaEl = document.createElement("span");
      areaEl.className = "ac-area";
      areaEl.textContent = new Area(found.areaID).getLocalizationAreaNamePrefixed();
      option.append(cityEl, areaEl);
    } else {
      const areaEl = document.createElement("span");
      areaEl.className = "ac-area is-area";
      areaEl.textContent = found.getLocalizationAreaNamePrefixed();
      option.appendChild(areaEl);
    }

    option.onclick = function () {
      currentFocusIndex = index;
      onClickOption();
    };
    autocomplete.appendChild(option);
  });

  document.querySelector("#selection .search-row").appendChild(autocomplete);
  currentFocusIndex--;
};

function updateFocus() {
  const options = document.querySelectorAll("#autocomplete button");
  options.forEach((node) => node.classList.remove("focused"));
  if (currentFocusIndex == -1) {
    searchInput.focus();
    return;
  }
  if (!options[currentFocusIndex]) return;
  options[currentFocusIndex].classList.add("focused");
  options[currentFocusIndex].scrollIntoView(false);
}

function onClickOption() {
  const selectedItem = founds[currentFocusIndex];
  if (!selectedItem) return;

  const existing = document.getElementById("autocomplete");
  if (existing) existing.remove();
  searchInput.value = "";

  if (selectedItem instanceof City) {
    if (selectionCitiesIDs.includes(selectedItem.id)) return;
    selectionCitiesIDs.push(selectedItem.id);
    Preferences.saveSelectedCities(selectionCitiesIDs);
  } else {
    if (selectionAreaIDs.includes(selectedItem.id)) return;
    selectionAreaIDs.push(selectedItem.id);
    Preferences.saveSelectedAreas(selectionAreaIDs);
  }
  loadSelectionCitiesUI();
}

searchInput.onkeydown = function (e) {
  if (!document.getElementById("autocomplete")) return;
  switch (e.keyCode) {
    case 40: // Down
      currentFocusIndex == founds.length - 1 ? (currentFocusIndex = 0) : currentFocusIndex++;
      break;
    case 38: // Up
      currentFocusIndex == 0 ? (currentFocusIndex = -1) : currentFocusIndex--;
      break;
    case 13: // Enter
      e.preventDefault();
      return onClickOption();
    default:
      return;
  }
  updateFocus();
};

searchInput.addEventListener("focusout", function () {
  setTimeout(() => {
    const ac = document.getElementById("autocomplete");
    if (ac) ac.remove();
  }, 200);
});

searchInput.onfocus = function () {
  searchInput.dispatchEvent(new Event("input"));
};

document.getElementById("clear").onclick = function () {
  selectionCitiesIDs = [];
  selectionAreaIDs = [];
  Preferences.saveSelectedCities(selectionCitiesIDs);
  Preferences.saveSelectedAreas(selectionAreaIDs);
  loadSelectionCitiesUI();
};

function setSilentBoxEnabled(enabled) {
  silentNotSelectedBox.style.pointerEvents = enabled ? "auto" : "none";
  silentNotSelectedBox.style.opacity = enabled ? "1" : "0.5";
}

function loadSelectionCitiesUI() {
  const container = document.getElementById("selected");
  container.innerHTML = "";

  const hasSelection = selectionCitiesIDs.length > 0 || selectionAreaIDs.length > 0;
  setSilentBoxEnabled(hasSelection);

  allCities
    .filter((city) => selectionCitiesIDs.includes(city.id))
    .forEach((city) => container.appendChild(buildChip(city.getLocalizationCityName(), false, () => {
      selectionCitiesIDs = selectionCitiesIDs.filter((id) => id != city.id);
      Preferences.saveSelectedCities(selectionCitiesIDs, loadSelectionCitiesUI);
    })));

  allAreas
    .filter((area) => selectionAreaIDs.includes(area.id))
    .forEach((area) => container.appendChild(buildChip(area.getLocalizationAreaNamePrefixed(), true, () => {
      selectionAreaIDs = selectionAreaIDs.filter((id) => id != area.id);
      Preferences.saveSelectedAreas(selectionAreaIDs, loadSelectionCitiesUI);
    })));

  if (!container.children.length) {
    const empty = document.createElement("p");
    empty.className = "empty";
    empty.textContent = "לא נבחרו אזורים — יתקבלו התרעות בכל הארץ.";
    container.appendChild(empty);
  }
}

function buildChip(name, isArea, onRemove) {
  const chip = document.createElement("span");
  chip.className = "chip" + (isArea ? " is-area" : "");
  const x = document.createElement("button");
  x.type = "button";
  x.className = "chip-x";
  x.textContent = "×";
  x.onclick = onRemove;
  const label = document.createElement("span");
  label.textContent = name;
  chip.append(x, label);
  return chip;
}

/* ============ בורר צלילים ============ */
const soundSelect = document.getElementById("soundSelect");
const previewSound = document.getElementById("previewSound");
let previewAudio = null;

soundSelect.onchange = () => {
  Preferences.saveSelectedSound(soundSelect.value);
};

previewSound.onclick = () => {
  if (previewAudio) { previewAudio.pause(); previewAudio = null; }
  previewAudio = new Audio(chrome.runtime.getURL("sounds/" + soundSelect.value + ".mp3"));
  previewAudio.play().catch(() => {});
};

/* ============ switches + סוג אירוע + בדיקה ============ */
const desktopNotifications = document.getElementById("desktopNotifications");
const backgroundHidePopup = document.getElementById("backgroundHidePopup");
const preventFrequentPopupFocus = document.getElementById("preventFrequentPopupFocus");
const silentNotSelected = document.getElementById("silentNotSelected");
const quietHoursEnabled = document.getElementById("quietHoursEnabled");
const quietHoursFrom = document.getElementById("quietHoursFrom");
const quietHoursTo = document.getElementById("quietHoursTo");
const quietHoursRange = document.getElementById("quietHoursRange");
const testAlert = document.getElementById("testAlert");
const eventTypeChips = document.getElementById("eventTypeChips");

const EVENT_TYPE_IDS = [3, 0, 2]; // 3 נסיון הסגרה, 0 נסיון מעצר מ.צ., 2 התרעת מחסומים
var selectedEventTypes = [];

desktopNotifications.onchange = () => Preferences.saveSelectedDesktop(desktopNotifications.checked);
backgroundHidePopup.onchange = () =>
  Preferences.saveSelectedBackgroundHidePopup(backgroundHidePopup.checked);
preventFrequentPopupFocus.onchange = () =>
  Preferences.savePreventFrequentPopupFocus(preventFrequentPopupFocus.checked);
silentNotSelected.onchange = () => Preferences.saveSilentNotSelected(silentNotSelected.checked);
testAlert.onclick = () => chrome.runtime.sendMessage("testAlert");

/* ============ השתקת צליל בטווח שעות (quiet hours) ============ */
function setQuietRangeEnabled(enabled) {
  quietHoursRange.style.pointerEvents = enabled ? "auto" : "none";
  quietHoursRange.style.opacity = enabled ? "1" : "0.5";
}

function saveQuietHours() {
  Preferences.saveQuietHours({
    enabled: quietHoursEnabled.checked,
    from: quietHoursFrom.value || "22:00",
    to: quietHoursTo.value || "07:00",
  });
}

quietHoursEnabled.onchange = () => {
  setQuietRangeEnabled(quietHoursEnabled.checked);
  saveQuietHours();
};
quietHoursFrom.onchange = saveQuietHours;
quietHoursTo.onchange = saveQuietHours;

function renderEventChips() {
  eventTypeChips.querySelectorAll(".filter-chip").forEach((chip) => {
    const id = Number(chip.dataset.event);
    chip.classList.toggle("selected", selectedEventTypes.includes(id));
  });
}

eventTypeChips.querySelectorAll(".filter-chip").forEach((chip) => {
  chip.onclick = () => {
    const id = Number(chip.dataset.event);
    const isSel = selectedEventTypes.includes(id);
    if (isSel && selectedEventTypes.length == 1) return; // לא מאפשרים לבטל את האחרון
    selectedEventTypes = isSel
      ? selectedEventTypes.filter((x) => x != id)
      : [...selectedEventTypes, id];
    renderEventChips();
    // ריק = כל הסוגים (זהה ל"כל הסוגים נבחרו")
    Preferences.setSelectedEventTypes(
      selectedEventTypes.length == EVENT_TYPE_IDS.length ? [] : selectedEventTypes
    );
  };
});

/* ============ מחוון חיבור לשרת ============ */
const connBtn = document.getElementById("connBtn");
const connDot = document.getElementById("connDot");
const connPopover = document.getElementById("connPopover");

function setConnUI(connected) {
  const text = connected ? "מחובר לשרת" : "מנותק מהשרת";
  connDot.classList.toggle("ok", connected);
  connDot.classList.toggle("down", !connected);
  connBtn.title = text;
  // טקסט הפופאפ + נקודה צבעונית תואמת
  const cls = connected ? "ok" : "down";
  const color = connected ? "var(--ok)" : "var(--danger)";
  connPopover.innerHTML =
    `<span class="dot" style="background:${color}"></span>` + text; // מחרוזת קבועה, ללא קלט משתמש
  connPopover.dataset.state = cls;
}

const checkServerConnection = () => {
  chrome.runtime.sendMessage("isConnectedToServer", (connected) => {
    if (chrome.runtime.lastError) return;
    setConnUI(!!connected);
  });
};

// קליק על המחוון → בדיקת חיבור מיידית + פתיחה/סגירה של הפופאפ; קליק בחוץ סוגר
connBtn.onclick = (e) => {
  e.stopPropagation();
  checkServerConnection();
  connPopover.hidden = !connPopover.hidden;
};
document.addEventListener("click", (e) => {
  if (!connPopover.hidden && !connPopover.contains(e.target) && e.target !== connBtn) {
    connPopover.hidden = true;
  }
});

/* ============ טעינת הגדרות מ-storage ============ */
async function loadSettings() {
  checkServerConnection();
  setInterval(checkServerConnection, 5000);

  selectionCitiesIDs = await Preferences.getSelectedCities();
  selectionAreaIDs = await Preferences.getSelectedAreas();
  loadSelectionCitiesUI();

  silentNotSelected.checked = await Preferences.getSilentNotSelected();
  desktopNotifications.checked = await Preferences.getSelectedDesktop();
  backgroundHidePopup.checked = await Preferences.getSelectedBackgroundHidePopup();
  preventFrequentPopupFocus.checked = await Preferences.getPreventFrequentPopupFocus();

  const quietHours = await Preferences.getQuietHours();
  quietHoursEnabled.checked = !!quietHours.enabled;
  quietHoursFrom.value = quietHours.from || "22:00";
  quietHoursTo.value = quietHours.to || "07:00";
  setQuietRangeEnabled(quietHoursEnabled.checked);

  selectedEventTypes = await Preferences.getSelectedEventTypes();
  if (selectedEventTypes.length == 0) selectedEventTypes = [...EVENT_TYPE_IDS];
  renderEventChips();

  soundSelect.value = await Preferences.getSelectedSound();
}
