const copy = {
  en: {
    pageTitle: "Staff Reports",
    kicker: "Staff Reports",
    title: "Report an issue inside the hotel and track the fix",
    subtitle: "Choose the responsible department, add the location and photo, and the report will go directly to the right team with a clear resolution time.",
    staffDashboard: "Staff dashboard",
    detailsTitle: "Report Details",
    departmentLabel: "Responsible department",
    locationTypeLabel: "Location type",
    locationLabel: "Room number or place name",
    locationPlaceholder: "Example: 305 or main lobby",
    issueTypeLabel: "Issue type",
    issuePlaceholder: "Example: broken light, broken chair, water leak",
    descriptionLabel: "Issue description",
    descriptionPlaceholder: "Write the details that help the department solve the issue quickly",
    priorityTitle: "Priority And Photo",
    priorityLabel: "Priority",
    reporterLabel: "Reporter name or department",
    reporterPlaceholder: "Example: Front desk employee",
    photoLabel: "Issue photo",
    choosePhoto: "Choose photo",
    changePhoto: "Change photo",
    noPhoto: "No photo selected",
    sendButton: "Send report",
    noDepartment: "No department is available to receive the report",
    sendError: "Could not send the report. Please try again",
    sendSuccess: "Report sent. It will now appear for the responsible department",
    loadError: "Could not load departments",
    photoAlt: "Report photo",
    normal: "Normal",
    important: "Important",
    urgent: "Urgent",
    minutes120: "120 minutes",
    minutes45: "45 minutes",
    minutes15: "15 minutes"
  },
  ar: {
    pageTitle: "بلاغات الموظفين",
    kicker: "بلاغات الموظفين",
    title: "سجّل مشكلة داخل الفندق وتابع حلها من النظام",
    subtitle: "اختر القسم المسؤول، أضف المكان والصورة، وسيظهر البلاغ مباشرة للفريق المختص مع وقت حل واضح.",
    staffDashboard: "لوحة الموظفين",
    detailsTitle: "تفاصيل البلاغ",
    departmentLabel: "القسم المسؤول",
    locationTypeLabel: "المكان",
    locationLabel: "رقم الغرفة أو اسم المكان",
    locationPlaceholder: "مثال: 305 أو اللوبي الرئيسي",
    issueTypeLabel: "نوع المشكلة",
    issuePlaceholder: "مثال: ضوء خربان، كرسي مكسور، تسريب ماء",
    descriptionLabel: "وصف المشكلة",
    descriptionPlaceholder: "اكتب التفاصيل التي تساعد القسم يحل المشكلة بسرعة",
    priorityTitle: "الأولوية والصورة",
    priorityLabel: "درجة الأهمية",
    reporterLabel: "اسم الموظف أو القسم المبلّغ",
    reporterPlaceholder: "مثال: موظف الاستقبال",
    photoLabel: "صورة المشكلة",
    noPhoto: "لم يتم اختيار صورة",
    sendButton: "إرسال البلاغ",
    noDepartment: "لا يوجد قسم متاح لاستقبال البلاغ",
    sendError: "تعذر إرسال البلاغ، حاول مرة ثانية",
    sendSuccess: "تم إرسال البلاغ وسيظهر الآن عند القسم المسؤول",
    loadError: "تعذر تحميل الأقسام",
    photoAlt: "صورة البلاغ",
    normal: "عادي",
    important: "مهم",
    urgent: "طارئ",
    minutes120: "120 دقيقة",
    minutes45: "45 دقيقة",
    minutes15: "15 دقيقة"
  }
};

const locationOptions = {
  en: ["Room", "Lobby", "Restaurant", "Pool", "Hall", "Corridor", "Office", "Other"],
  ar: ["غرفة", "لوبي", "مطعم", "مسبح", "قاعة", "ممر", "مكتب", "أخرى"]
};

const priorityOptions = [
  { id: "normal", minutes: 120, label: "normal", duration: "minutes120" },
  { id: "important", minutes: 45, label: "important", duration: "minutes45" },
  { id: "urgent", minutes: 15, label: "urgent", duration: "minutes15" }
];

const state = {
  lang: localStorage.getItem("reportLang") || "en",
  departments: [],
  services: [],
  selectedImage: ""
};

const form = document.querySelector("#reportForm");
const departmentSelect = document.querySelector("#reportDepartment");
const locationType = document.querySelector("#reportLocationType");
const locationInput = document.querySelector("#reportLocation");
const titleInput = document.querySelector("#reportTitle");
const detailsInput = document.querySelector("#reportDetails");
const prioritySelect = document.querySelector("#reportPriority");
const reporterInput = document.querySelector("#reporterName");
const imageInput = document.querySelector("#reportImage");
const chooseImageButton = document.querySelector("#chooseReportImage");
const imagePreview = document.querySelector("#imagePreview");
const formNote = document.querySelector("#formNote");
const staffLink = document.querySelector("#staffLink");
const langToggle = document.querySelector("#langToggleReport");

function t(key) {
  return copy[state.lang][key] || copy.en[key] || key;
}

function hotelSlug() {
  const match = window.location.pathname.match(/^\/hotel\/([^/]+)/);
  return match ? decodeURIComponent(match[1]) : "default";
}

function apiPath(path) {
  const url = new URL(path, window.location.origin);
  url.searchParams.set("hotel", hotelSlug());
  return url.toString();
}

function departmentName(department) {
  return state.lang === "ar" ? (department.ar || department.en || department.id) : (department.en || department.ar || department.id);
}

function priorityMinutes(priority) {
  const option = priorityOptions.find((item) => item.id === priority) || priorityOptions[0];
  return option.minutes;
}

function priorityLabel(priority) {
  const option = priorityOptions.find((item) => item.id === priority) || priorityOptions[0];
  return t(option.label);
}

function serviceForDepartment(departmentId) {
  return state.services.find((service) => service.department === departmentId) || state.services.find((service) => service.department === "maintenance") || state.services[0];
}

function showNote(text, type = "success") {
  formNote.textContent = text;
  formNote.className = `form-note ${type}`;
}

function readImage(file) {
  return new Promise((resolve) => {
    if (!file) return resolve("");
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result || ""));
    reader.onerror = () => resolve("");
    reader.readAsDataURL(file);
  });
}

function renderOptions() {
  const selectedDepartment = departmentSelect.value;
  departmentSelect.innerHTML = state.departments.map((department) => `<option value="${department.id}">${departmentName(department)}</option>`).join("");
  if (selectedDepartment) departmentSelect.value = selectedDepartment;

  const selectedLocation = locationType.value;
  locationType.innerHTML = locationOptions[state.lang].map((value) => `<option value="${value}">${value}</option>`).join("");
  if (selectedLocation && locationOptions[state.lang].includes(selectedLocation)) locationType.value = selectedLocation;

  const selectedPriority = prioritySelect.value || "normal";
  prioritySelect.innerHTML = priorityOptions.map((option) => `<option value="${option.id}">${t(option.label)} - ${t(option.duration)}</option>`).join("");
  prioritySelect.value = selectedPriority;
}

function applyLanguage() {
  document.documentElement.lang = state.lang;
  document.documentElement.dir = state.lang === "ar" ? "rtl" : "ltr";
  document.title = t("pageTitle");
  langToggle.textContent = state.lang === "ar" ? "EN" : "AR";
  document.querySelectorAll("[data-i18n]").forEach((el) => {
    el.textContent = t(el.dataset.i18n);
  });
  document.querySelectorAll("[data-i18n-placeholder]").forEach((el) => {
    el.placeholder = t(el.dataset.i18nPlaceholder);
  });
  if (chooseImageButton) chooseImageButton.textContent = state.selectedImage ? t("changePhoto") : t("choosePhoto");
  if (!state.selectedImage) imagePreview.textContent = t("noPhoto");
  renderOptions();
}

async function loadBootstrap() {
  const response = await fetch(apiPath("/api/bootstrap"));
  const data = await response.json();
  state.departments = (data.departments || []).filter((department) => department.id !== "all");
  state.services = data.config?.services || [];
  staffLink.href = `/hotel/${encodeURIComponent(hotelSlug())}/staff`;
  applyLanguage();
}

langToggle.addEventListener("click", () => {
  state.lang = state.lang === "ar" ? "en" : "ar";
  localStorage.setItem("reportLang", state.lang);
  applyLanguage();
});

imageInput.addEventListener("change", async () => {
  state.selectedImage = await readImage(imageInput.files?.[0]);
  imagePreview.innerHTML = state.selectedImage ? `<img src="${state.selectedImage}" alt="${t("photoAlt")}">` : t("noPhoto");
  if (chooseImageButton) chooseImageButton.textContent = state.selectedImage ? t("changePhoto") : t("choosePhoto");
});

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  const departmentId = departmentSelect.value;
  const service = serviceForDepartment(departmentId);
  if (!service) {
    showNote(t("noDepartment"), "error");
    return;
  }
  const locationText = `${locationType.value}: ${locationInput.value.trim()}`;
  const priority = prioritySelect.value;
  const now = new Date().toISOString();
  const title = titleInput.value.trim();
  const description = detailsInput.value.trim();
  const order = {
    id: crypto.randomUUID(),
    hotel: hotelSlug(),
    serviceId: service.id,
    room: locationInput.value.trim() || locationType.value,
    status: "new",
    details: `${title} - ${description}`,
    items: [{ id: "internal_report", ar: title, en: title, price: 0, quantity: 1 }],
    total: 0,
    chargeTo: "room",
    estimateMinutes: priorityMinutes(priority),
    internalReport: true,
    reportPriority: priority,
    reportPriorityLabel: priorityLabel(priority),
    reportLocation: locationText,
    reporterName: reporterInput.value.trim(),
    reportImage: state.selectedImage,
    messages: [],
    createdAt: now,
    updatedAt: now
  };
  const response = await fetch(apiPath("/api/orders"), {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify([order])
  });
  if (!response.ok) {
    showNote(t("sendError"), "error");
    return;
  }
  form.reset();
  state.selectedImage = "";
  applyLanguage();
  showNote(t("sendSuccess"), "success");
});

applyLanguage();
loadBootstrap().catch(() => showNote(t("loadError"), "error"));
