const FAVORITES_KEY = "favorites";
const SETTINGS_KEY = "settings";
const LAST_SEARCH_KEY = "lastSearch";
const OFFLINE_DATA_KEY = "offlineData";
const USER_ITEMS_KEY = "userItems";
function getFromStorage(keys) {
 return chrome.storage.local.get(keys);
}
function setInStorage(payload) {
 return chrome.storage.local.set(payload);
}
export async function getFavorites() {
 const data = await getFromStorage([FAVORITES_KEY]);
 return data[FAVORITES_KEY] || [];
}
export async function saveFavorites(items) {
 await setInStorage({ [FAVORITES_KEY]: items });
}
export async function toggleFavorite(item) {
 const favorites = await getFavorites();
 const exists = favorites.some((entry) => entry.id === item.id);
 const next = exists
 ? favorites.filter((entry) => entry.id !== item.id)
 : [item, ...favorites].slice(0, 80);
 await saveFavorites(next);
 return next;
}
export async function clearFavorites() {
 await setInStorage({ [FAVORITES_KEY]: [] });
}
export async function getSettings() {
 const data = await getFromStorage([SETTINGS_KEY]);
 return data[SETTINGS_KEY] || {
 notifications: {
 enabled: false,
 intervalHours: 6,
 type: "all",
 module: "",
 unit: ""
 }
 };
}
export async function saveSettings(settings) {
 await setInStorage({ [SETTINGS_KEY]: settings });
}
export async function getLastSearch() {
 const data = await getFromStorage([LAST_SEARCH_KEY]);
 return data[LAST_SEARCH_KEY] || {
 q: "",
 type: "all",
 module: "",
 unit: ""
 };
}
export async function saveLastSearch(filters) {
 await setInStorage({ [LAST_SEARCH_KEY]: filters });
}
export async function clearLastSearch() {
 await setInStorage({
 [LAST_SEARCH_KEY]: {
 q: "",
 type: "all",
 module: "",
 unit: ""
 }
 });
}
export async function getOfflineData() {
 const data = await getFromStorage([OFFLINE_DATA_KEY]);
 return data[OFFLINE_DATA_KEY] || null;
}
export async function saveOfflineData(offlineData) {
 await setInStorage({ [OFFLINE_DATA_KEY]: offlineData });
}
export async function getUserItems() {
 const data = await getFromStorage([USER_ITEMS_KEY]);
 return data[USER_ITEMS_KEY] || [];
}
export async function saveUserItems(items) {
 await setInStorage({ [USER_ITEMS_KEY]: items });
}
export async function addUserItem(item) {
 const items = await getUserItems();
 const next = [{ ...item, isUserItem: true }, ...items].slice(0, 200);
 await saveUserItems(next);
 return next;
}
export async function deleteUserItem(itemId) {
 const items = await getUserItems();
 const next = items.filter((item) => item.id !== itemId);
 await saveUserItems(next);
 return next;
}