import Alpine from 'alpinejs';
import collapse from '@alpinejs/collapse';
import { initTheme, setTheme, getStoredTheme, syncThemeFromServer } from './theme';
import { initSidebar, initCounters, showToast } from './sidebar';

Alpine.plugin(collapse);

window.Alpine = Alpine;

Alpine.data('themeToggle', () => ({
  preference: getStoredTheme(),
  init() {
    this.preference = getStoredTheme();
  },
  set(mode) {
    this.preference = mode;
    setTheme(mode);
    document.documentElement.classList.add('theme-transition');
    setTimeout(() => document.documentElement.classList.remove('theme-transition'), 250);
  },
  isActive(mode) {
    return this.preference === mode;
  },
}));

Alpine.data('navGroup', (defaultOpen = false) => ({
  open: defaultOpen,
  toggle() {
    this.open = !this.open;
  },
}));

Alpine.start();

initTheme();
syncThemeFromServer();
initSidebar();
initCounters();

document.addEventListener('DOMContentLoaded', () => {
  const flash = document.querySelector('[data-flash-message]');
  if (flash) {
    showToast(flash.dataset.flashMessage, flash.dataset.flashType || 'success');
  }
});

window.SouthendUI = { showToast, setTheme, getStoredTheme };
