/**
 * Theme management - frontend only, no backend.
 * Stores and applies theme via localStorage and CSS custom properties.
 * Supports separate full themes for Light mode and Dark (night) mode.
 */

const THEME_STORAGE_KEY = 'sat_portal_theme';
const APP_THEME_KEY = 'sat-theme'; // light | night

const defaultLightTheme = () => ({
  // Header (navbar)
  headerBg: 'rgba(0, 0, 0, 0.92)',
  headerText: '#ffffff',
  headerBrandColor: '#f21b23',
  // Sidebar
  sidebarBg: 'rgba(0, 0, 0, 0.95)',
  sidebarText: '#ffffff',
  sidebarActiveBg: '#e5e5e5',
  sidebarActiveText: '#f21b23',
  sidebarHoverBg: '#e5e5e5',
  sidebarWidth: '260px',
  // Main content
  contentBg: '#e5e5e5',
  cardBg: 'rgba(255, 255, 255, 0.9)',
  // Global text
  textPrimary: '#4d4d4f',
  textSecondary: '#4d4d4f',
  textMuted: '#4d4d4f',
  // Base typography
  fontSize: '100',
  fontSizeBody: '1rem',
  fontSizeH1: '1.75rem',
  fontSizeH2: '1.5rem',
  fontSizeH3: '1.25rem',
  fontFamily: "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
  fontWeightHeading: '700',
  fontWeightBody: '400',
  letterSpacing: 'normal',
  lineHeight: '1.5',
  // Accent
  primaryColor: '#f21b23',
  primaryDark: '#d91820',
  // Buttons
  buttonPrimaryText: '#ffffff',
  buttonSecondaryText: '#4d4d4f',
  // Misc
  borderRadius: '0.5rem',
  borderColor: '#e5e5e5',
  borderWidth: '1px',
  inputBg: '#ffffff',
  bodyBg: 'linear-gradient(135deg, #e5e5e5 0%, #e5e5e5 50%, #e5e5e5 100%)',
  // Feedback
  successColor: '#4caf50',
  errorColor: '#f44336',
  warningColor: '#ff9800',
  infoColor: '#2196f3',
  linkColor: '#1976d2',
  // Focus & tables
  focusRingColor: 'rgba(242, 27, 35, 0.35)',
  tableHeaderBg: 'rgba(0, 0, 0, 0.04)',
  // Shadows
  shadowSm: '0 1px 3px rgba(0, 0, 0, 0.12)',
  shadowMd: '0 2px 6px rgba(0, 0, 0, 0.15)',
  shadowLg: '0 3px 12px rgba(0, 0, 0, 0.18)',
  // Transitions
  transitionFast: '0.2s ease',
  transitionNormal: '0.3s ease',
  transitionSlow: '0.5s ease',
});

/** Default dark (night) theme */
const defaultDarkTheme = () => ({
  ...defaultLightTheme(),
  headerBg: 'rgba(28, 28, 30, 0.92)',
  headerText: '#f2f2f7',
  headerBrandColor: '#bb86fc',
  sidebarBg: 'rgba(22, 22, 24, 0.98)',
  sidebarText: '#aeaeb2',
  sidebarActiveBg: 'rgba(187, 134, 252, 0.18)',
  sidebarActiveText: '#bb86fc',
  sidebarHoverBg: 'rgba(255, 255, 255, 0.06)',
  contentBg: '#0d0d0f',
  cardBg: 'rgba(58, 56, 56, 0.95)',
  textPrimary: '#f2f2f7',
  textSecondary: '#aeaeb2',
  textMuted: '#636366',
  primaryColor: '#bb86fc',
  primaryDark: '#9d6de8',
  borderColor: 'rgba(255, 255, 255, 0.1)',
  inputBg: 'rgba(255, 255, 255, 0.08)',
  bodyBg: 'linear-gradient(165deg, #1c1c1e 0%, #0d0d0f 45%, #0a0a0c 100%)',
  buttonPrimaryText: '#ffffff',
  buttonSecondaryText: '#aeaeb2',
  focusRingColor: 'rgba(187, 134, 252, 0.35)',
  tableHeaderBg: 'rgba(255, 255, 255, 0.06)',
  shadowSm: '0 1px 3px rgba(0, 0, 0, 0.4)',
  shadowMd: '0 2px 6px rgba(0, 0, 0, 0.45)',
  shadowLg: '0 3px 12px rgba(0, 0, 0, 0.5)',
});

/** Single default theme (same as light) – for backward compatibility */
export const getDefaultTheme = () => defaultLightTheme();

export const getDefaultLightTheme = () => defaultLightTheme();
export const getDefaultDarkTheme = () => defaultDarkTheme();

/**
 * Preset themes as primary options.
 * Each preset has light and dark theme objects plus id, name, and accent for preview.
 */
export const getPresetThemes = () => [
  {
    id: 'default',
    name: 'Default',
    accent: '#f21b23',
    light: getDefaultLightTheme(),
    dark: getDefaultDarkTheme(),
  },
  {
    id: 'ocean',
    name: 'Ocean',
    accent: '#0288d1',
    light: (() => {
      const t = getDefaultLightTheme();
      return {
        ...t,
        headerBg: 'rgba(255, 255, 255, 0.95)',
        headerText: '#01579b',
        headerBrandColor: '#0288d1',
        sidebarBg: 'rgba(240, 248, 255, 0.98)',
        sidebarText: '#0277bd',
        sidebarActiveBg: 'rgba(2, 136, 209, 0.15)',
        sidebarActiveText: '#01579b',
        sidebarHoverBg: 'rgba(2, 136, 209, 0.08)',
        contentBg: '#e3f2fd',
        cardBg: 'rgba(255, 255, 255, 0.95)',
        textPrimary: '#01579b',
        textSecondary: '#0277bd',
        textMuted: '#0288d1',
        primaryColor: '#0288d1',
        primaryDark: '#01579b',
        borderColor: 'rgba(2, 136, 209, 0.25)',
        bodyBg: 'linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 50%, #e1f5fe 100%)',
      };
    })(),
    dark: (() => {
      const t = getDefaultDarkTheme();
      return {
        ...t,
        primaryColor: '#0288d1',
        primaryDark: '#01579b',
        headerBrandColor: '#0288d1',
        sidebarActiveBg: 'rgba(2, 136, 209, 0.2)',
        sidebarActiveText: '#4fc3f7',
      };
    })(),
  },
  {
    id: 'forest',
    name: 'Forest',
    accent: '#2e7d32',
    light: (() => {
      const t = getDefaultLightTheme();
      return {
        ...t,
        headerBg: 'rgba(255, 255, 255, 0.95)',
        headerText: '#1b5e20',
        headerBrandColor: '#2e7d32',
        sidebarBg: 'rgba(232, 245, 233, 0.98)',
        sidebarText: '#388e3c',
        sidebarActiveBg: 'rgba(46, 125, 50, 0.18)',
        sidebarActiveText: '#1b5e20',
        sidebarHoverBg: 'rgba(46, 125, 50, 0.08)',
        contentBg: '#e8f5e9',
        cardBg: 'rgba(255, 255, 255, 0.95)',
        textPrimary: '#1b5e20',
        textSecondary: '#388e3c',
        textMuted: '#43a047',
        primaryColor: '#2e7d32',
        primaryDark: '#1b5e20',
        borderColor: 'rgba(46, 125, 50, 0.3)',
        bodyBg: 'linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 50%, #e8f5e9 100%)',
      };
    })(),
    dark: (() => {
      const t = getDefaultDarkTheme();
      return { ...t, primaryColor: '#66bb6a', primaryDark: '#43a047', headerBrandColor: '#66bb6a', sidebarActiveText: '#81c784' };
    })(),
  },
  {
    id: 'sunset',
    name: 'Sunset',
    accent: '#e65100',
    light: (() => {
      const t = getDefaultLightTheme();
      return {
        ...t,
        headerBg: 'rgba(255, 243, 224, 0.95)',
        headerText: '#bf360c',
        headerBrandColor: '#e65100',
        sidebarBg: 'rgba(255, 235, 238, 0.98)',
        sidebarText: '#d84315',
        sidebarActiveBg: 'rgba(230, 81, 0, 0.2)',
        sidebarActiveText: '#bf360c',
        sidebarHoverBg: 'rgba(230, 81, 0, 0.08)',
        contentBg: '#fff3e0',
        cardBg: 'rgba(255, 255, 255, 0.9)',
        textPrimary: '#bf360c',
        textSecondary: '#d84315',
        textMuted: '#e65100',
        primaryColor: '#e65100',
        primaryDark: '#bf360c',
        borderColor: 'rgba(191, 54, 12, 0.25)',
        bodyBg: 'linear-gradient(135deg, #ffe0b2 0%, #ffccbc 50%, #ffe0b2 100%)',
      };
    })(),
    dark: (() => {
      const t = getDefaultDarkTheme();
      return { ...t, primaryColor: '#ff9800', primaryDark: '#f57c00', headerBrandColor: '#ff9800', sidebarActiveText: '#ffb74d' };
    })(),
  },
  {
    id: 'slate',
    name: 'Slate',
    accent: '#455a64',
    light: (() => {
      const t = getDefaultLightTheme();
      return {
        ...t,
        headerBg: 'rgba(250, 250, 250, 0.95)',
        headerText: '#37474f',
        headerBrandColor: '#455a64',
        sidebarBg: 'rgba(236, 239, 241, 0.98)',
        sidebarText: '#546e7a',
        sidebarActiveBg: 'rgba(69, 90, 100, 0.15)',
        sidebarActiveText: '#37474f',
        sidebarHoverBg: 'rgba(69, 90, 100, 0.08)',
        contentBg: '#eceff1',
        cardBg: 'rgba(255, 255, 255, 0.95)',
        textPrimary: '#37474f',
        textSecondary: '#546e7a',
        textMuted: '#607d8b',
        primaryColor: '#455a64',
        primaryDark: '#37474f',
        borderColor: 'rgba(55, 71, 79, 0.25)',
        bodyBg: 'linear-gradient(135deg, #eceff1 0%, #cfd8dc 50%, #eceff1 100%)',
      };
    })(),
    dark: (() => {
      const t = getDefaultDarkTheme();
      return { ...t, primaryColor: '#78909c', primaryDark: '#607d8b', headerBrandColor: '#78909c', sidebarActiveText: '#90a4ae' };
    })(),
  },
  {
    id: 'berry',
    name: 'Berry',
    accent: '#7b1fa2',
    light: (() => {
      const t = getDefaultLightTheme();
      return {
        ...t,
        headerBg: 'rgba(255, 255, 255, 0.95)',
        headerText: '#4a148c',
        headerBrandColor: '#7b1fa2',
        sidebarBg: 'rgba(243, 229, 245, 0.98)',
        sidebarText: '#6a1b9a',
        sidebarActiveBg: 'rgba(123, 31, 162, 0.18)',
        sidebarActiveText: '#4a148c',
        sidebarHoverBg: 'rgba(123, 31, 162, 0.08)',
        contentBg: '#f3e5f5',
        cardBg: 'rgba(255, 255, 255, 0.95)',
        textPrimary: '#4a148c',
        textSecondary: '#6a1b9a',
        textMuted: '#7b1fa2',
        primaryColor: '#7b1fa2',
        primaryDark: '#6a1b9a',
        borderColor: 'rgba(123, 31, 162, 0.25)',
        bodyBg: 'linear-gradient(135deg, #f3e5f5 0%, #e1bee7 50%, #f3e5f5 100%)',
      };
    })(),
    dark: (() => {
      const t = getDefaultDarkTheme();
      return { ...t, primaryColor: '#ba68c8', primaryDark: '#ab47bc', headerBrandColor: '#ba68c8', sidebarActiveText: '#ce93d8' };
    })(),
  },
];

/**
 * Get stored themes for both modes. Returns { light, dark } or null.
 * Backward compatible: if stored value is a single theme object, returns { light: parsed, dark: getDefaultDarkTheme() }.
 */
export const getStoredThemes = () => {
  try {
    const raw = localStorage.getItem(THEME_STORAGE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed.light === 'object' && typeof parsed.dark === 'object') {
      return {
        light: { ...getDefaultLightTheme(), ...parsed.light },
        dark: { ...getDefaultDarkTheme(), ...parsed.dark },
      };
    }
    if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
      const merged = { ...getDefaultTheme(), ...parsed };
      return { light: merged, dark: getDefaultDarkTheme() };
    }
    return null;
  } catch {
    return null;
  }
};

/** Get stored theme (single) – backward compat; returns current mode's theme from stored pair if available. */
export const getStoredTheme = () => {
  const pair = getStoredThemes();
  if (!pair) return null;
  const appMode = typeof localStorage !== 'undefined' ? localStorage.getItem(APP_THEME_KEY) : 'light';
  return appMode === 'night' ? pair.dark : pair.light;
};

/**
 * Apply theme object to document (CSS custom properties on :root).
 * Also overrides base design tokens so header, sidebar, content, forms, buttons, and text
 * all follow the preset theme.
 */
export const applyTheme = (theme) => {
  if (!theme) return;
  const root = document.documentElement;
  const defLight = getDefaultLightTheme();
  // Theme-specific variables (used where we explicitly want theme)
  root.style.setProperty('--theme-header-bg', theme.headerBg ?? defLight.headerBg);
  root.style.setProperty('--theme-header-text', theme.headerText ?? defLight.headerText);
  root.style.setProperty('--theme-header-brand', theme.headerBrandColor ?? defLight.headerBrandColor);
  root.style.setProperty('--theme-sidebar-bg', theme.sidebarBg ?? defLight.sidebarBg);
  root.style.setProperty('--theme-sidebar-text', theme.sidebarText ?? defLight.sidebarText);
  root.style.setProperty('--theme-sidebar-active-bg', theme.sidebarActiveBg ?? defLight.sidebarActiveBg);
  root.style.setProperty('--theme-sidebar-active-text', theme.sidebarActiveText ?? defLight.sidebarActiveText);
  root.style.setProperty('--theme-sidebar-hover-bg', theme.sidebarHoverBg ?? defLight.sidebarHoverBg);
  root.style.setProperty('--theme-content-bg', theme.contentBg ?? defLight.contentBg);
  root.style.setProperty('--theme-text-primary', theme.textPrimary ?? defLight.textPrimary);
  root.style.setProperty('--theme-text-secondary', theme.textSecondary ?? defLight.textSecondary);
  root.style.setProperty('--theme-text-muted', theme.textMuted ?? defLight.textMuted);
  root.style.setProperty('--theme-font-size', theme.fontSize ? `${theme.fontSize}%` : '100%');
  root.style.setProperty('--theme-font-family', theme.fontFamily || 'inherit');
  root.style.setProperty('--theme-font-size-body', theme.fontSizeBody ?? defLight.fontSizeBody ?? '1rem');
  root.style.setProperty('--theme-font-size-h1', theme.fontSizeH1 ?? defLight.fontSizeH1 ?? '1.75rem');
  root.style.setProperty('--theme-font-size-h2', theme.fontSizeH2 ?? defLight.fontSizeH2 ?? '1.5rem');
  root.style.setProperty('--theme-font-size-h3', theme.fontSizeH3 ?? defLight.fontSizeH3 ?? '1.25rem');
  root.style.setProperty('--theme-font-weight-body', theme.fontWeightBody ?? defLight.fontWeightBody ?? '400');
  root.style.setProperty('--theme-primary', theme.primaryColor ?? defLight.primaryColor);
  root.style.setProperty('--theme-primary-dark', theme.primaryDark ?? defLight.primaryDark);
  root.style.setProperty('--theme-radius', theme.borderRadius ?? defLight.borderRadius);
  root.style.setProperty('--theme-body-bg', theme.bodyBg ?? defLight.bodyBg);
  root.style.setProperty('--theme-border-color', theme.borderColor ?? defLight.borderColor);
  root.style.setProperty('--theme-card-bg', theme.cardBg ?? defLight.cardBg);
  root.style.setProperty('--theme-input-bg', theme.inputBg ?? defLight.inputBg);
  // Feedback & links
  root.style.setProperty('--success-color', theme.successColor ?? defLight.successColor);
  root.style.setProperty('--danger-color', theme.errorColor ?? defLight.errorColor);
  root.style.setProperty('--theme-warning-color', theme.warningColor ?? defLight.warningColor);
  root.style.setProperty('--theme-info-color', theme.infoColor ?? defLight.infoColor);
  root.style.setProperty('--theme-link-color', theme.linkColor ?? defLight.linkColor);
  // Layout & focus
  root.style.setProperty('--sidebar-width', theme.sidebarWidth ?? defLight.sidebarWidth);
  root.style.setProperty('--theme-border-width', theme.borderWidth ?? defLight.borderWidth);
  root.style.setProperty('--theme-focus-ring', theme.focusRingColor ?? defLight.focusRingColor);
  root.style.setProperty('--theme-table-header-bg', theme.tableHeaderBg ?? defLight.tableHeaderBg);
  root.style.setProperty('--theme-button-primary-text', theme.buttonPrimaryText ?? defLight.buttonPrimaryText);
  root.style.setProperty('--theme-button-secondary-text', theme.buttonSecondaryText ?? defLight.buttonSecondaryText);
  // Shadows
  root.style.setProperty('--shadow-sm', theme.shadowSm ?? defLight.shadowSm);
  root.style.setProperty('--shadow-md', theme.shadowMd ?? defLight.shadowMd);
  root.style.setProperty('--shadow-lg', theme.shadowLg ?? defLight.shadowLg);
  // Transitions
  root.style.setProperty('--transition-fast', theme.transitionFast ?? defLight.transitionFast);
  root.style.setProperty('--transition-normal', theme.transitionNormal ?? defLight.transitionNormal);
  root.style.setProperty('--transition-slow', theme.transitionSlow ?? defLight.transitionSlow);
  // Typography
  root.style.setProperty('--theme-heading-weight', theme.fontWeightHeading ?? defLight.fontWeightHeading);
  root.style.setProperty('--theme-letter-spacing', theme.letterSpacing ?? defLight.letterSpacing);
  root.style.setProperty('--theme-line-height', theme.lineHeight ?? defLight.lineHeight);
  // Override base design tokens
  root.style.setProperty('--primary-color', theme.primaryColor ?? defLight.primaryColor);
  root.style.setProperty('--primary-dark', theme.primaryDark ?? defLight.primaryDark);
  root.style.setProperty('--text-primary', theme.textPrimary ?? defLight.textPrimary);
  root.style.setProperty('--text-secondary', theme.textSecondary ?? defLight.textSecondary);
  root.style.setProperty('--text-muted', theme.textMuted ?? defLight.textMuted);
  root.style.setProperty('--bg-gray', theme.contentBg ?? defLight.contentBg);
  root.style.setProperty('--hover-overlay', theme.sidebarActiveBg ?? defLight.sidebarActiveBg);
  root.style.setProperty('--accent-color', theme.primaryColor ?? defLight.primaryColor);
  root.style.setProperty('--border-color', theme.borderColor ?? defLight.borderColor);
  root.style.setProperty('--bg-card', theme.cardBg ?? defLight.cardBg);
  root.style.setProperty('--bg-light-gray', theme.sidebarHoverBg ?? defLight.sidebarHoverBg ?? '#fafafa');
};

/**
 * Save a single theme (backward compat). Saves as both light and dark using the same object.
 */
export const saveTheme = (theme) => {
  const full = { ...getDefaultLightTheme(), ...theme };
  saveThemes({ light: full, dark: { ...getDefaultDarkTheme(), ...theme } });
  applyTheme(full);
};

/**
 * Save both light and dark themes to localStorage. Does NOT apply (caller applies if needed).
 */
export const saveThemes = (themes) => {
  try {
    const light = { ...getDefaultLightTheme(), ...themes.light };
    const dark = { ...getDefaultDarkTheme(), ...themes.dark };
    localStorage.setItem(THEME_STORAGE_KEY, JSON.stringify({ light, dark }));
  } catch (e) {
    console.warn('Theme save failed:', e);
  }
};

/**
 * Apply stored theme for current app mode (light/night). Call on load and when user toggles mode.
 */
export const applyStoredTheme = () => {
  const pair = getStoredThemes();
  const appMode = typeof localStorage !== 'undefined' ? localStorage.getItem(APP_THEME_KEY) : 'light';
  if (pair) {
    applyTheme(appMode === 'night' ? pair.dark : pair.light);
  } else {
    applyTheme(appMode === 'night' ? getDefaultDarkTheme() : getDefaultLightTheme());
  }
};
