import { listThemes, getThemeCss } from '../services/themes.js';

const CSS_TABS = ['general', 'police', 'contenu', 'avance'];
let activeTab = CSS_TABS[0];

const QUICK_THEME_KEY = 'pena_quick_theme';
const themeCssCache = new Map();

function cssKey(tab) { return `pena_css_${tab}`; }

function loadTabCss(tab) { return localStorage.getItem(cssKey(tab)) ?? ''; }

function saveTabCss(tab, css) {
  if (css.trim()) localStorage.setItem(cssKey(tab), css);
  else localStorage.removeItem(cssKey(tab));
}

function applyCustomCss() {
  let styleEl = document.getElementById('pena-custom-style');
  if (!styleEl) {
    styleEl = document.createElement('style');
    styleEl.id = 'pena-custom-style';
    document.head.appendChild(styleEl);
  }
  const tabCss = CSS_TABS.map(t => loadTabCss(t)).filter(Boolean).join('\n');
  const activeTheme = localStorage.getItem(QUICK_THEME_KEY);
  const themeCss = activeTheme ? (themeCssCache.get(activeTheme) ?? '') : '';
  styleEl.textContent = [tabCss, themeCss].filter(Boolean).join('\n');
}

function syncThemeBadges() {
  const activeTheme = localStorage.getItem(QUICK_THEME_KEY);
  document.querySelectorAll('.css-modal__theme-badge').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.theme === activeTheme);
  });
}

function buildThemeBadges(themes) {
  const list = document.getElementById('quick-themes-list');
  list.innerHTML = '';
  for (const { id, label } of themes) {
    const btn = document.createElement('button');
    btn.className = 'css-modal__theme-badge';
    btn.dataset.theme = id;
    btn.textContent = label;
    btn.addEventListener('click', async () => {
      const current = localStorage.getItem(QUICK_THEME_KEY);
      if (current === id) {
        localStorage.removeItem(QUICK_THEME_KEY);
      } else {
        if (!themeCssCache.has(id)) {
          const css = await getThemeCss(id);
          if (css) themeCssCache.set(id, css);
        }
        localStorage.setItem(QUICK_THEME_KEY, id);
      }
      applyCustomCss();
      syncThemeBadges();
    });
    list.appendChild(btn);
  }
}

async function preloadActiveThemeCss() {
  const activeTheme = localStorage.getItem(QUICK_THEME_KEY);
  if (activeTheme && !themeCssCache.has(activeTheme)) {
    const css = await getThemeCss(activeTheme);
    if (css) themeCssCache.set(activeTheme, css);
  }
}

export async function initCssModal() {
  const themes = await listThemes();
  buildThemeBadges(themes);
  await preloadActiveThemeCss();
  applyCustomCss();
  syncThemeBadges();

  const cssModalOverlay = document.getElementById('css-modal-overlay');
  const cssEditor = document.getElementById('css-editor');

  function openCssModal() {
    cssEditor.value = loadTabCss(activeTab);
    cssModalOverlay.classList.remove('hidden');
  }

  function closeCssModal() {
    cssModalOverlay.classList.add('hidden');
  }

  document.getElementById('btn-customize-css').addEventListener('click', openCssModal);
  document.getElementById('btn-css-close').addEventListener('click', closeCssModal);
  document.getElementById('btn-css-cancel').addEventListener('click', closeCssModal);

  cssModalOverlay.addEventListener('click', (e) => {
    if (e.target === cssModalOverlay) closeCssModal();
  });

  document.getElementById('css-tabs').addEventListener('click', (e) => {
    const tab = e.target.closest('.css-modal__tab');
    if (!tab) return;
    saveTabCss(activeTab, cssEditor.value);
    activeTab = tab.dataset.tab;
    document.querySelectorAll('.css-modal__tab').forEach(t => t.classList.toggle('active', t === tab));
    cssEditor.value = loadTabCss(activeTab);
  });

  document.getElementById('btn-css-apply').addEventListener('click', () => {
    saveTabCss(activeTab, cssEditor.value);
    applyCustomCss();
    closeCssModal();
  });

  document.getElementById('btn-css-reset').addEventListener('click', () => {
    CSS_TABS.forEach(t => localStorage.removeItem(cssKey(t)));
    localStorage.removeItem(QUICK_THEME_KEY);
    cssEditor.value = '';
    applyCustomCss();
    syncThemeBadges();
  });
}
