import { loadOfflineData } from "./data.js";
import { buildSubjectsTaxonomy, buildTaxonomy, filterSubjects, pickDailyItems, searchOffline } from "./search.js";
import {
 addUserItem,
 clearFavorites,
 deleteUserItem,
 getFavorites,
 getLastSearch,
 getUserItems,
 saveLastSearch,
 toggleFavorite
} from "./storage.js";
const query = new URLSearchParams(window.location.search);
const elements = {
 tabButtons: Array.from(document.querySelectorAll(".tab-btn")),
 tabPanels: Array.from(document.querySelectorAll(".tab-panel")),
 openOptionsBtn: document.getElementById("openOptionsBtn"),
 dataVersionBadge: document.getElementById("dataVersionBadge"),
 lastUpdatedBadge: document.getElementById("lastUpdatedBadge"),
 toast: document.getElementById("toast"),
 subjectBranchSelect: document.getElementById("subjectBranchSelect"),
 subjectModuleSelect: document.getElementById("subjectModuleSelect"),
 subjectYearSelect: document.getElementById("subjectYearSelect"),
 openSubjectsInternalTabBtn: document.getElementById("openSubjectsInternalTabBtn"),
 resetSubjectsFiltersBtn: document.getElementById("resetSubjectsFiltersBtn"),
 subjectsMeta: document.getElementById("subjectsMeta"),
 subjectsContainer: document.getElementById("subjectsContainer"),
 queryInput: document.getElementById("queryInput"),
 typeSelect: document.getElementById("typeSelect"),
 moduleSelect: document.getElementById("moduleSelect"),
 unitSelect: document.getElementById("unitSelect"),
 searchBtn: document.getElementById("searchBtn"),
 resetBtn: document.getElementById("resetBtn"),
 resultsMeta: document.getElementById("resultsMeta"),
 dailyReview: document.getElementById("dailyReview"),
 resultsContainer: document.getElementById("resultsContainer"),
 customKindSelect: document.getElementById("customKindSelect"),
 customModuleInput: document.getElementById("customModuleInput"),
 customUnitInput: document.getElementById("customUnitInput"),
 customTitleInput: document.getElementById("customTitleInput"),
 customBodyInput: document.getElementById("customBodyInput"),
 saveCustomItemBtn: document.getElementById("saveCustomItemBtn"),
 customItemsMeta: document.getElementById("customItemsMeta"),
 customItemsContainer: document.getElementById("customItemsContainer"),
 favoritesContainer: document.getElementById("favoritesContainer"),
 subjectFavoritesContainer: document.getElementById("subjectFavoritesContainer"),
 clearFavoritesBtn: document.getElementById("clearFavoritesBtn")
};
let offlineData = null;
let subjectTaxonomy = null;
let toastTimer = null;
function bind(node, eventName, handler) {
 if (!node) return;
 node.addEventListener(eventName, handler);
}
function el(tag, className, text) {
 const node = document.createElement(tag);
 if (className) node.className = className;
 if (typeof text === "string") node.textContent = text;
 return node;
}
function showMessage(container, message) {
 if (!container) return;
 container.innerHTML = "";
 container.appendChild(el("div", "empty-box", message));
}
function showToast(message, kind = "info") {
 if (!elements.toast) return;
 elements.toast.textContent = message;
 elements.toast.dataset.kind = kind;
 elements.toast.classList.add("show");
 if (toastTimer) clearTimeout(toastTimer);
 toastTimer = setTimeout(() => {
 elements.toast.classList.remove("show");
 }, 1900);
}
function populateSelect(select, values, placeholder) {
 if (!select) return;
 select.innerHTML = "";
 const empty = document.createElement("option");
 empty.value = "";
 empty.textContent = placeholder;
 select.appendChild(empty);
 values.forEach((value) => {
 const option = document.createElement("option");
 option.value = value;
 option.textContent = value;
 select.appendChild(option);
 });
}
function setActiveTab(tabId) {
 elements.tabButtons.forEach((button) => {
 button.classList.toggle("active", button.dataset.tab === tabId);
 });
 elements.tabPanels.forEach((panel) => {
 panel.classList.toggle("active", panel.id === `tab-${tabId}`);
 });
}
async function copyText(text) {
 try {
 await navigator.clipboard.writeText(text);
 showToast("تم النسخ");
 } catch (_error) {
 showToast("فشل النسخ", "error");
 }
}
function serializeItem(item) {
 return [item.title, item.body, item.module, item.unit].filter(Boolean).join("\n");
}
function createBadge(text) {
 return el("span", "badge", text);
}
function createIconButton(icon, label) {
 const button = el("button", "icon-action-btn");
 button.type = "button";
 button.setAttribute("aria-label", label);
 button.innerHTML = icon;
 return button;
}
function titlePrefix(kind) {
 if (kind === "person") return "👤";
 if (kind === "date") return "🗓️";
 if (kind === "subject") return "📘";
 return "📗";
}
async function handleFavoriteToggle(item, removeMessage = "تمت الإزالة من المفضلة") {
 const previous = await getFavorites();
 const wasFavorite = previous.some((entry) => entry.id === item.id);
 await toggleFavorite(item);
 await renderFavorites();
 showToast(wasFavorite ? removeMessage : "تم الحفظ في المفضلة", wasFavorite ? "warn" : "success");
}
function createSubjectCard(item, favoriteView = false) {
 const card = el("article", "result-card subject-card");
 const head = el("div", "result-card-head");
 const titleWrap = el("div", "title-stack");
 const title = el("h3", "result-title", `${titlePrefix("subject")} ${item.title}`);
 const actions = el("div", "card-actions");
 const copyBtn = createIconButton('<svg viewBox="0 0 24 24"><path fill="currentColor" d="M16 1H4a2 2 0 0 0-2 2v12h2V3h12zm3 4H8a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2m0 16H8V7h11z"/></svg>', "نسخ");
 const favoriteBtn = createIconButton(
 favoriteView
 ? '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>'
 : '<svg viewBox="0 0 24 24"><path fill="currentColor" d="m22 9.24-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03z"/></svg>',
 favoriteView ? "إزالة من المفضلة" : "حفظ في المفضلة"
 );
 bind(copyBtn, "click", () => copyText(serializeItem(item)));
 bind(favoriteBtn, "click", () => handleFavoriteToggle(item));
 titleWrap.appendChild(title);
 actions.appendChild(copyBtn);
 actions.appendChild(favoriteBtn);
 head.appendChild(titleWrap);
 head.appendChild(actions);
 const badgeRow = el("div", "badge-row");
 [item.branch, item.module, item.bacYear].filter(Boolean).forEach((badge) => {
 badgeRow.appendChild(createBadge(badge));
 });
 const content = el("div", "subject-content");
 content.dir = item.module === "english" || item.module === "french" ? "ltr" : "rtl";
 content.innerHTML = item.contentHtml || `<p>${item.body || ""}</p>`;
 card.appendChild(head);
 card.appendChild(badgeRow);
 card.appendChild(content);
 return card;
}
function createKnowledgeCard(item, options = {}) {
 const { favoriteView = false, customView = false } = options;
 const card = el("article", "result-card");
 const head = el("div", "result-card-head");
 const titleWrap = el("div", "title-stack");
 const title = el("h3", "result-title", `${titlePrefix(item.kind)} ${item.title}`);
 const actions = el("div", "card-actions");
 const copyBtn = createIconButton('<svg viewBox="0 0 24 24"><path fill="currentColor" d="M16 1H4a2 2 0 0 0-2 2v12h2V3h12zm3 4H8a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2m0 16H8V7h11z"/></svg>', "نسخ");
 bind(copyBtn, "click", () => copyText(serializeItem(item)));
 actions.appendChild(copyBtn);
 if (customView) {
 const deleteBtn = createIconButton('<svg viewBox="0 0 24 24"><path fill="currentColor" d="M6 19a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7H6zm3.46-7.12 1.41-1.41L12 11.59l1.12-1.12 1.41 1.41L13.41 13l1.12 1.12-1.41 1.41L12 14.41l-1.12 1.12-1.41-1.41L10.59 13zM15.5 4l-1-1h-5l-1 1H5v2h14V4z"/></svg>', "حذف");
 bind(deleteBtn, "click", async () => {
 await deleteUserItem(item.id);
 await refreshData();
 await renderCustomItems();
 await hydrateSearchFilters();
 await runSearch();
 showToast("تم حذف العنصر الخاص", "warn");
 });
 actions.appendChild(deleteBtn);
 } else {
 const favoriteBtn = createIconButton(
 favoriteView
 ? '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg>'
 : '<svg viewBox="0 0 24 24"><path fill="currentColor" d="m22 9.24-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03z"/></svg>',
 favoriteView ? "إزالة من المفضلة" : "حفظ في المفضلة"
 );
 bind(favoriteBtn, "click", () => handleFavoriteToggle(item));
 actions.appendChild(favoriteBtn);
 }
 const body = el("p", "result-body", item.body || "");
 const badgeRow = el("div", "badge-row");
 [item.module, item.unit, item.isUserItem ? "خاص بي" : ""].filter(Boolean).forEach((badge) => {
 badgeRow.appendChild(createBadge(badge));
 });
 titleWrap.appendChild(title);
 head.appendChild(titleWrap);
 head.appendChild(actions);
 card.appendChild(head);
 card.appendChild(badgeRow);
 card.appendChild(body);
 return card;
}
async function renderFavorites() {
 const favorites = await getFavorites();
 const knowledgeFavorites = favorites.filter((item) => item.kind !== "subject");
 const subjectFavorites = favorites.filter((item) => item.kind === "subject");
 if (elements.favoritesContainer) elements.favoritesContainer.innerHTML = "";
 if (elements.subjectFavoritesContainer) elements.subjectFavoritesContainer.innerHTML = "";
 if (!knowledgeFavorites.length) {
 showMessage(elements.favoritesContainer, "لا توجد عناصر محفوظة بعد.");
 } else {
 knowledgeFavorites.forEach((item) => {
 elements.favoritesContainer?.appendChild(createKnowledgeCard(item, { favoriteView: true }));
 });
 }
 if (!subjectFavorites.length) {
 showMessage(elements.subjectFavoritesContainer, "لا توجد مواضيع محفوظة بعد.");
 } else {
 subjectFavorites.forEach((item) => {
 elements.subjectFavoritesContainer?.appendChild(createSubjectCard(item, true));
 });
 }
}
async function renderCustomItems() {
 const items = await getUserItems();
 if (!elements.customItemsContainer || !elements.customItemsMeta) return;
 elements.customItemsContainer.innerHTML = "";
 elements.customItemsMeta.textContent = `${items.length} عنصر خاص`;
 if (!items.length) {
 showMessage(elements.customItemsContainer, "لم تضف عناصر خاصة بعد.");
 return;
 }
 items.forEach((item) => {
 elements.customItemsContainer.appendChild(createKnowledgeCard(item, { customView: true }));
 });
}
function renderSubjects() {
 if (!elements.subjectsContainer || !elements.subjectsMeta) return;
 const result = filterSubjects(offlineData, {
 branch: elements.subjectBranchSelect?.value || "",
 module: elements.subjectModuleSelect?.value || "",
 year: elements.subjectYearSelect?.value || ""
 });
 elements.subjectsContainer.innerHTML = "";
 elements.subjectsMeta.textContent = `${result.length} موضوع`;
 if (!result.length) {
 showMessage(elements.subjectsContainer, "لا توجد مواضيع مطابقة للفلاتر الحالية.");
 return;
 }
 result.forEach((item) => {
 elements.subjectsContainer.appendChild(createSubjectCard(item));
 });
}
function renderResults(result) {
 if (!elements.resultsContainer || !elements.resultsMeta) return;
 elements.resultsContainer.innerHTML = "";
 elements.resultsMeta.textContent = `${result.total} نتيجة`;
 if (!result.items.length) {
 showMessage(elements.resultsContainer, "لا توجد نتائج مطابقة.");
 return;
 }
 result.items.forEach((item) => {
 elements.resultsContainer.appendChild(createKnowledgeCard(item));
 });
}
function renderDailyReview() {
 if (!elements.dailyReview) return;
 const daily = pickDailyItems(offlineData);
 elements.dailyReview.innerHTML = "";
 if (daily.term) {
 const termBox = el("div", "daily-box");
 termBox.appendChild(el("p", "daily-label", "مصطلح اليوم"));
 termBox.appendChild(el("h3", "daily-title", `${titlePrefix(daily.term.kind)} ${daily.term.title}`));
 termBox.appendChild(el("p", "daily-body", daily.term.body));
 elements.dailyReview.appendChild(termBox);
 }
 if (daily.date) {
 const dateBox = el("div", "daily-box");
 dateBox.appendChild(el("p", "daily-label", "تاريخ اليوم"));
 dateBox.appendChild(el("h3", "daily-title", `${titlePrefix(daily.date.kind)} ${daily.date.title}`));
 dateBox.appendChild(el("p", "daily-body", daily.date.body));
 elements.dailyReview.appendChild(dateBox);
 }
}
function getSearchFilters() {
 return {
 q: elements.queryInput?.value.trim() || "",
 type: elements.typeSelect?.value || "all",
 module: elements.moduleSelect?.value || "",
 unit: elements.unitSelect?.value || ""
 };
}
async function runSearch() {
 const filters = getSearchFilters();
 await saveLastSearch(filters);
 renderResults(searchOffline(offlineData, filters));
}
function hydrateSubjectsFilters() {
 populateSelect(elements.subjectBranchSelect, subjectTaxonomy.branches, "اختر الشعبة");
 populateSelect(elements.subjectModuleSelect, [], "اختر المادة");
 populateSelect(elements.subjectYearSelect, [], "كل السنوات");
}
function onSubjectBranchChange() {
 const branch = elements.subjectBranchSelect?.value || "";
 const modules = branch ? (subjectTaxonomy.modulesByBranch[branch] || []) : [];
 populateSelect(elements.subjectModuleSelect, modules, "اختر المادة");
 populateSelect(elements.subjectYearSelect, [], "كل السنوات");
 renderSubjects();
}
function onSubjectModuleChange() {
 const key = `${elements.subjectBranchSelect?.value || ""}::${elements.subjectModuleSelect?.value || ""}`;
 const years = subjectTaxonomy.yearsByBranchModule[key] || [];
 populateSelect(elements.subjectYearSelect, years, "كل السنوات");
 renderSubjects();
}
function openInternalSubjectsTab() {
 const url = new URL(chrome.runtime.getURL("app.html"));
 url.searchParams.set("tab", "subjects");
 if (elements.subjectBranchSelect?.value) url.searchParams.set("branch", elements.subjectBranchSelect.value);
 if (elements.subjectModuleSelect?.value) url.searchParams.set("module", elements.subjectModuleSelect.value);
 if (elements.subjectYearSelect?.value) url.searchParams.set("year", elements.subjectYearSelect.value);
 chrome.tabs.create({ url: url.toString() });
}
async function hydrateSearchFilters() {
 const taxonomy = buildTaxonomy(offlineData);
 const lastSearch = await getLastSearch();
 populateSelect(elements.moduleSelect, taxonomy.modules, "كل المواد");
 populateSelect(elements.unitSelect, taxonomy.units, "كل الوحدات");
 if (elements.queryInput) elements.queryInput.value = lastSearch.q || "";
 if (elements.typeSelect) elements.typeSelect.value = lastSearch.type || "all";
 if (elements.moduleSelect) elements.moduleSelect.value = lastSearch.module || "";
 if (elements.unitSelect) elements.unitSelect.value = lastSearch.unit || "";
}
function formatLastUpdated(version) {
 const date = new Date(version);
 if (Number.isNaN(date.getTime())) return version || "-";
 return date.toLocaleString("ar-DZ", {
 year: "numeric",
 month: "2-digit",
 day: "2-digit",
 hour: "2-digit",
 minute: "2-digit"
 });
}
async function refreshData() {
 offlineData = await loadOfflineData();
 subjectTaxonomy = buildSubjectsTaxonomy(offlineData);
}
async function saveCustomItem() {
 const title = elements.customTitleInput?.value.trim() || "";
 const body = elements.customBodyInput?.value.trim() || "";
 if (!title || !body) return;
 await addUserItem({
 id: `user-${Date.now()}`,
 kind: elements.customKindSelect?.value || "term",
 title,
 body,
 module: elements.customModuleInput?.value.trim() || "",
 unit: elements.customUnitInput?.value.trim() || ""
 });
 if (elements.customTitleInput) elements.customTitleInput.value = "";
 if (elements.customBodyInput) elements.customBodyInput.value = "";
 await refreshData();
 await hydrateSearchFilters();
 await renderCustomItems();
 await runSearch();
 showToast("تم حفظ العنصر الخاص", "success");
}
function applyQueryState() {
 const requestedTab = query.get("tab");
 if (requestedTab) setActiveTab(requestedTab);
 if (query.get("branch") && elements.subjectBranchSelect) {
 elements.subjectBranchSelect.value = query.get("branch");
 }
 onSubjectBranchChange();
 if (query.get("module") && elements.subjectModuleSelect) {
 elements.subjectModuleSelect.value = query.get("module");
 }
 onSubjectModuleChange();
 if (query.get("year") && elements.subjectYearSelect) {
 elements.subjectYearSelect.value = query.get("year");
 }
}
async function init() {
 await refreshData();
 if (elements.dataVersionBadge) {
 elements.dataVersionBadge.textContent = `نسخة البيانات ${offlineData.version.slice(0, 10)}`;
 }
 if (elements.lastUpdatedBadge) {
 elements.lastUpdatedBadge.textContent = `آخر تحديث: ${formatLastUpdated(offlineData.version)}`;
 }
 hydrateSubjectsFilters();
 await hydrateSearchFilters();
 applyQueryState();
 renderSubjects();
 renderDailyReview();
 await renderFavorites();
 await renderCustomItems();
 await runSearch();
}
elements.tabButtons.forEach((button) => {
 bind(button, "click", () => setActiveTab(button.dataset.tab));
});
bind(elements.openOptionsBtn, "click", () => chrome.runtime.openOptionsPage());
bind(elements.subjectBranchSelect, "change", onSubjectBranchChange);
bind(elements.subjectModuleSelect, "change", onSubjectModuleChange);
bind(elements.subjectYearSelect, "change", () => renderSubjects());
bind(elements.openSubjectsInternalTabBtn, "click", () => openInternalSubjectsTab());
bind(elements.resetSubjectsFiltersBtn, "click", () => {
 if (elements.subjectBranchSelect) elements.subjectBranchSelect.value = "";
 hydrateSubjectsFilters();
 renderSubjects();
});
bind(elements.searchBtn, "click", () => runSearch());
bind(elements.resetBtn, "click", async () => {
 if (elements.queryInput) elements.queryInput.value = "";
 if (elements.typeSelect) elements.typeSelect.value = "all";
 if (elements.moduleSelect) elements.moduleSelect.value = "";
 if (elements.unitSelect) elements.unitSelect.value = "";
 await runSearch();
});
bind(elements.queryInput, "keydown", (event) => {
 if (event.key === "Enter") runSearch();
});
bind(elements.typeSelect, "change", () => runSearch());
bind(elements.moduleSelect, "change", () => runSearch());
bind(elements.unitSelect, "change", () => runSearch());
bind(elements.clearFavoritesBtn, "click", async () => {
 await clearFavorites();
 await renderFavorites();
 showToast("تم مسح المفضلة", "warn");
});
bind(elements.saveCustomItemBtn, "click", () => saveCustomItem());
init().catch((error) => {
 console.error(error);
 showMessage(elements.resultsContainer, "تعذر تحميل الإضافة.");
});