const $ = (id) => document.getElementById(id);
const text = {
  ar: {
    pageTitle: "لوحة الاشتراكات", owner: "مالك النظام", title: "لوحة الاشتراكات", subtitle: "إدارة الفنادق، الروابط، الاشتراك، وعدد الغرف من مكان مستقل.",
    loginTitle: "دخول مالك النظام", username: "اسم المستخدم", password: "كلمة المرور", login: "دخول",
    addHotel: "إضافة فندق جديد", nameAr: "اسم الفندق عربي", nameEn: "اسم الفندق إنجليزي", slug: "كود الفندق / الرابط", plan: "الباقة", rooms: "عدد الغرف", status: "حالة الاشتراك", start: "بداية الاشتراك", end: "نهاية الاشتراك", adminUser: "يوزر أدمن الفندق", adminPass: "باسورد أدمن الفندق", addButton: "إضافة الفندق",
    hotels: "الفنادق المشتركة", search: "بحث عن فندق", all: "كل الفنادق", active: "فعالة", paused: "موقوفة", expired: "منتهية", activeStatus: "فعال", pausedStatus: "موقوف", expiredStatus: "منتهي",
    ends: "ينتهي", admin: "أدمن", roomWord: "غرفة", adminLink: "رابط أدمن الفندق", copyAdmin: "نسخ رابط الأدمن", copyGuest: "نسخ رابط النزيل", copyStaff: "نسخ رابط موظف مثال", pause: "إيقاف الاشتراك", activate: "تفعيل الاشتراك", renew: "تمديد 30 يوم", delete: "حذف", noHotels: "لا توجد فنادق بعد",
    copied: "تم نسخ الرابط", copyPrompt: "انسخ الرابط", invalidLogin: "بيانات الدخول غير صحيحة", duplicate: "اسم الفندق مطلوب أو الكود موجود", added: "تمت إضافة الفندق", confirmDelete: "حذف الفندق من الاشتراكات؟",
    phNameAr: "مثال: فندق لافينا", phNameEn: "مثال: Lavina Hotel"
  },
  en: {
    pageTitle: "Subscriptions dashboard", owner: "System owner", title: "Subscriptions dashboard", subtitle: "Manage hotels, links, subscriptions, and room limits from a separate place.",
    loginTitle: "System owner login", username: "Username", password: "Password", login: "Login",
    addHotel: "Add new hotel", nameAr: "Hotel name Arabic", nameEn: "Hotel name English", slug: "Hotel code / link", plan: "Plan", rooms: "Allowed rooms", status: "Subscription status", start: "Subscription start", end: "Subscription end", adminUser: "Hotel admin user", adminPass: "Hotel admin password", addButton: "Add hotel",
    hotels: "Subscribed hotels", search: "Search hotel", all: "All hotels", active: "Active", paused: "Paused", expired: "Expired", activeStatus: "Active", pausedStatus: "Paused", expiredStatus: "Expired",
    ends: "Ends", admin: "Admin", roomWord: "rooms", adminLink: "Hotel admin link", copyAdmin: "Copy admin link", copyGuest: "Copy guest link", copyStaff: "Copy sample staff link", pause: "Pause subscription", activate: "Activate subscription", renew: "Renew 30 days", delete: "Delete", noHotels: "No hotels yet",
    copied: "Link copied", copyPrompt: "Copy link", invalidLogin: "Invalid owner credentials", duplicate: "Hotel name is required or code already exists", added: "Hotel added", confirmDelete: "Delete this hotel from subscriptions?",
    phNameAr: "Example: Arabic hotel name", phNameEn: "Example: Lavina Hotel"
  }
};
const state = { hotels: [], query: "", lang: localStorage.getItem("ownerLang") || "ar" };
const loginForm = $("loginForm"), ownerLock = $("ownerLock"), ownerDashboard = $("ownerDashboard"), hotelForm = $("hotelForm"), hotelList = $("hotelList"), metrics = $("metrics"), search = $("search"), toast = $("toast"), startInput = $("start"), endInput = $("end"), langToggle = $("langToggle");
const fields = { ownerUser: $("ownerUser"), ownerPass: $("ownerPass"), nameAr: $("nameAr"), nameEn: $("nameEn"), slug: $("slug"), plan: $("plan"), rooms: $("rooms"), status: $("status"), adminUser: $("adminUser"), adminPass: $("adminPass") };
function t(key){ return text[state.lang][key] || key; }
function todayIso(){ return new Date().toISOString().slice(0,10); }
function addDays(days){ const d = new Date(); d.setDate(d.getDate()+days); return d.toISOString().slice(0,10); }
function normalizeSlug(value){ return String(value || "").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"") || `hotel-${Date.now()}`; }
function escapeHtml(value){ return String(value ?? "").replace(/[&<>'"]/g, (c) => ({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"}[c])); }
function showToast(message){ toast.textContent = message; toast.classList.add("show"); setTimeout(()=>toast.classList.remove("show"),1800); }
function effectiveStatus(hotel){ if (hotel.status !== "active") return hotel.status || "paused"; return hotel.endDate && hotel.endDate < todayIso() ? "expired" : "active"; }
function statusLabel(status){ if(status === "active") return t("activeStatus"); if(status === "expired") return t("expiredStatus"); return t("pausedStatus"); }
function hotelName(hotel){ return state.lang === "ar" ? (hotel.nameAr || hotel.nameEn || hotel.slug) : (hotel.nameEn || hotel.nameAr || hotel.slug); }
function adminLink(hotel){ return `${location.origin}/hotel/${encodeURIComponent(hotel.slug)}/admin`; }
function guestLink(hotel){ return `${location.origin}/hotel/${encodeURIComponent(hotel.slug)}/guest?room=ROOM_NUMBER`; }
function staffLink(hotel){ return `${location.origin}/hotel/${encodeURIComponent(hotel.slug)}/staff?user=food`; }
async function loadHotels(){ const res = await fetch('/api/super-hotels'); const data = await res.json(); state.hotels = data.superHotels || []; render(); }
async function saveHotels(){ await fetch('/api/super-hotels',{method:'PUT',headers:{'Content-Type':'application/json'},body:JSON.stringify({superHotels:state.hotels})}); }
async function copyText(value){ try{ await navigator.clipboard.writeText(value); showToast(t('copied')); } catch { prompt(t('copyPrompt'), value); } }
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.querySelector(".owner-hero span").textContent = t("owner"); document.querySelector(".owner-hero h1").textContent = t("title"); document.querySelector(".owner-hero p").textContent = t("subtitle"); document.querySelector("#loginForm h2").textContent = t("loginTitle"); document.querySelector("label[for='ownerUser']")?.remove(); loginForm.querySelectorAll("label")[0].childNodes[0].textContent = t("username"); loginForm.querySelectorAll("label")[1].childNodes[0].textContent = t("password"); loginForm.querySelector("button").textContent = t("login"); hotelForm.querySelector("h2").textContent = t("addHotel"); const labels = ["nameAr","nameEn","slug","plan","rooms","status","start","end","adminUser","adminPass"]; hotelForm.querySelectorAll("label").forEach((label,i)=>label.childNodes[0].textContent = t(labels[i])); hotelForm.querySelector("button").textContent = t("addButton"); document.querySelector(".section-head h2").textContent = t("hotels"); search.placeholder = t("search"); fields.nameAr.placeholder = t("phNameAr"); fields.nameEn.placeholder = t("phNameEn"); fields.status.options[0].textContent = t("activeStatus"); fields.status.options[1].textContent = t("pausedStatus"); fields.status.options[2].textContent = t("expiredStatus"); fields.plan.options[0].textContent = state.lang === "ar" ? "ستارتر" : "Starter"; fields.plan.options[1].textContent = state.lang === "ar" ? "بزنس" : "Business"; fields.plan.options[2].textContent = state.lang === "ar" ? "مؤسسات" : "Enterprise"; }
function renderMetrics(){ const totals = state.hotels.reduce((acc,h)=>{ acc.total++; acc[effectiveStatus(h)]++; return acc; },{total:0,active:0,paused:0,expired:0}); metrics.innerHTML = [[t("all"),totals.total],[t("active"),totals.active],[t("paused"),totals.paused],[t("expired"),totals.expired]].map(([label,value])=>`<article class="metric"><span>${label}</span><strong>${value}</strong></article>`).join(''); }
function render(){ applyLanguage(); renderMetrics(); const q = state.query.trim().toLowerCase(); const hotels = q ? state.hotels.filter(h => [h.nameAr,h.nameEn,h.slug,h.plan,h.status].filter(Boolean).join(' ').toLowerCase().includes(q)) : state.hotels; hotelList.innerHTML = hotels.length ? hotels.map(h=>{ const status=effectiveStatus(h); return `<article class="hotel-card"><div><span class="chip ${status}">${escapeHtml(statusLabel(status))}</span><h3>${escapeHtml(hotelName(h))}</h3><p>${escapeHtml(h.slug)} - ${escapeHtml(h.plan || 'starter')} - ${Number(h.allowedRooms)||0} ${t("roomWord")}</p><p>${t("ends")}: <b>${escapeHtml(h.endDate || '-')}</b></p><p>${t("admin")}: <b>${escapeHtml(h.adminUser || 'admin')}</b> / <b>${escapeHtml(h.adminPass || '1234')}</b></p></div><div class="links"><a href="${adminLink(h)}" target="_blank">${t("adminLink")}</a><button type="button" data-copy="${escapeHtml(adminLink(h))}">${t("copyAdmin")}</button><button type="button" data-copy="${escapeHtml(guestLink(h))}">${t("copyGuest")}</button><button type="button" data-copy="${escapeHtml(staffLink(h))}">${t("copyStaff")}</button></div><div class="actions"><button data-toggle="${escapeHtml(h.id)}">${status==='active'?t('pause'):t('activate')}</button><button data-renew="${escapeHtml(h.id)}">${t("renew")}</button><button class="danger" data-delete="${escapeHtml(h.id)}">${t("delete")}</button></div></article>`; }).join('') : `<p>${t("noHotels")}</p>`; }
function unlock(){ ownerLock.hidden = true; ownerDashboard.hidden = false; sessionStorage.setItem('ownerUnlocked','true'); loadHotels(); }
loginForm.addEventListener('submit',(e)=>{ e.preventDefault(); if (fields.ownerUser.value.trim()==='super' && fields.ownerPass.value==='9999') unlock(); else showToast(t('invalidLogin')); });
hotelForm.addEventListener('submit', async (e)=>{ e.preventDefault(); const nameAr=fields.nameAr.value.trim(); const nameEn=fields.nameEn.value.trim() || nameAr; const slug=normalizeSlug(fields.slug.value || nameEn || nameAr); if(!nameAr || state.hotels.some(h=>h.slug===slug)){ showToast(t('duplicate')); return; } state.hotels.unshift({id:crypto.randomUUID(),nameAr,nameEn,slug,plan:fields.plan.value,allowedRooms:Math.max(1,Number(fields.rooms.value)||1),status:fields.status.value,startDate:startInput.value || todayIso(),endDate:endInput.value || addDays(30),adminUser:fields.adminUser.value.trim() || 'admin',adminPass:fields.adminPass.value.trim() || '1234',createdAt:new Date().toISOString()}); await saveHotels(); hotelForm.reset(); startInput.value=todayIso(); endInput.value=addDays(30); fields.adminUser.value='admin'; fields.adminPass.value='1234'; render(); showToast(t('added')); });
hotelList.addEventListener('click', async (e)=>{ const copy=e.target.closest('[data-copy]')?.dataset.copy; if(copy) return copyText(copy); const toggle=e.target.closest('[data-toggle]')?.dataset.toggle; const renew=e.target.closest('[data-renew]')?.dataset.renew; const del=e.target.closest('[data-delete]')?.dataset.delete; if(toggle){ const h=state.hotels.find(x=>x.id===toggle); if(h){ h.status=effectiveStatus(h)==='active'?'paused':'active'; if(h.status==='active' && (!h.endDate || h.endDate<todayIso())) h.endDate=addDays(30); await saveHotels(); render(); } } if(renew){ const h=state.hotels.find(x=>x.id===renew); if(h){ const base=h.endDate && h.endDate>todayIso()?new Date(`${h.endDate}T00:00:00`):new Date(); base.setDate(base.getDate()+30); h.endDate=base.toISOString().slice(0,10); h.status='active'; await saveHotels(); render(); } } if(del && confirm(t('confirmDelete'))){ state.hotels=state.hotels.filter(h=>h.id!==del); await saveHotels(); render(); } });
search.addEventListener('input',()=>{ state.query=search.value; render(); });
langToggle.addEventListener('click',()=>{ state.lang = state.lang === 'ar' ? 'en' : 'ar'; localStorage.setItem('ownerLang', state.lang); render(); });
startInput.value=todayIso(); endInput.value=addDays(30); applyLanguage();
if(sessionStorage.getItem('ownerUnlocked')==='true') unlock();

