// Theme loads from Supabase via API (survives deploys)
const THEME_API = '/api/branding.php';

let themeData = null;

export async function load() {
  try {
    const res = await fetch(THEME_API + '?_t=' + Date.now());
    if (!res.ok) { console.warn('[theme] API responded', res.status); return; }
    themeData = await res.json();
    applyColors();
    applyAnimations();
    if (themeData?.assets) console.log('[theme] loaded', Object.keys(themeData.assets).length, 'assets');
  } catch (e) { console.warn('[theme] load failed', e); }
}

export function getAsset(slot, fallback) {
  if (themeData?.assets?.[slot]) return themeData.assets[slot];
  return fallback || null;
}

export function getColor(key, fallback) {
  return themeData?.[key] || fallback;
}

function applyColors() {
  if (!themeData) return;
  const root = document.documentElement.style;

  const map = {
    bg_deep: '--bg-deep',
    bg_base: '--bg-base',
    bg_card: '--bg-card',
    bg_elevated: '--bg-elevated',
    bg_hover: '--bg-hover',
    bg_panel: '--bg-panel',
    bg_inset: '--bg-inset',
    bg_dark: '--bg-dark',
    gold: '--gold',
    gold_soft: '--gold-soft',
    gold_dark: '--gold-dark',
    blue: '--blue',
    cyan: '--cyan',
    orange: '--orange',
    purple: '--purple',
    purple_light: '--purple-light',
    violet: '--violet',
    emerald: '--emerald',
    green: '--green',
    green_light: '--green-light',
    pink: '--pink',
    amber: '--amber',
    red: '--red',
    red_light: '--red-light',
    red_soft: '--red-soft',
    success: '--success',
    error: '--error',
    warning: '--warning',
    info: '--info',
    text_primary: '--text-primary',
    text_secondary: '--text-secondary',
    text_muted: '--text-muted',
    text_dim: '--text-dim',
    text_light: '--text-light',
    chess_primary: '--chess-primary',
    chess_secondary: '--chess-secondary',
    domino_primary: '--domino-primary',
    domino_secondary: '--domino-secondary',
    ludo_primary: '--ludo-primary',
    ludo_secondary: '--ludo-secondary',
    backgammon_primary: '--backgammon-primary',
    backgammon_secondary: '--backgammon-secondary'
  };

  for (const [key, cssVar] of Object.entries(map)) {
    if (themeData[key]) {
      root.setProperty(cssVar, themeData[key]);
    }
  }

  // Ludo board colors
  const ludoMap = {
    ludo_red: '--ludo-red', ludo_blue: '--ludo-blue',
    ludo_green: '--ludo-green', ludo_yellow: '--ludo-yellow',
    ludo_board_bg: '--ludo-board-bg', ludo_path: '--ludo-path',
    ludo_safe: '--ludo-safe', ludo_piece_border: '--ludo-piece-border',
    ludo_grid_line: '--ludo-grid-line',
    // Chess board
    board_light: '--board-light', board_dark: '--board-dark',
    board_highlight_light: '--board-highlight-light', board_highlight_dark: '--board-highlight-dark',
    board_check: '--board-check'
  };
  for (const [key, cssVar] of Object.entries(ludoMap)) {
    if (themeData[key]) root.setProperty(cssVar, themeData[key]);
  }

  // Backgammon board colors
  const bgMap = {
    bg_board_border: '--bg-board-border', bg_board_light: '--bg-board-light',
    bg_board_dark: '--bg-board-dark', bg_bar_dark: '--bg-bar-dark',
    bg_bar_light: '--bg-bar-light', bg_bearoff: '--bg-bearoff',
    bg_point_dark: '--bg-point-dark', bg_point_dark_tip: '--bg-point-dark-tip',
    bg_point_light: '--bg-point-light', bg_point_light_tip: '--bg-point-light-tip',
    bg_checker_white: '--bg-checker-white', bg_checker_black: '--bg-checker-black',
    bg_highlight: '--bg-highlight', bg_selected: '--bg-selected'
  };
  for (const [key, cssVar] of Object.entries(bgMap)) {
    if (themeData[key]) root.setProperty(cssVar, themeData[key]);
  }

  // Also expose ALL theme values as a flat map for JS access
  window.__EL3AB_THEME = themeData;
}

function applyAnimations() {
  if (!themeData) return;
  const root = document.documentElement.style;

  if (themeData.anim_speed) root.setProperty('--dur-normal', themeData.anim_speed + 'ms');
  if (themeData.anim_fast) root.setProperty('--dur-fast', themeData.anim_fast + 'ms');
  if (themeData.anim_slow) root.setProperty('--dur-slow', themeData.anim_slow + 'ms');
  if (themeData.border_radius) root.setProperty('--r-md', themeData.border_radius + 'px');
  if (themeData.card_radius) root.setProperty('--r-xl', themeData.card_radius + 'px');
  if (themeData.btn_scale) root.setProperty('--btn-press-scale', themeData.btn_scale);
  if (themeData.btn_radius) root.setProperty('--r-full', themeData.btn_radius + 'px');
  if (themeData.btn_secondary_radius) root.setProperty('--r-btn-secondary', themeData.btn_secondary_radius + 'px');
  if (themeData.btn_height) root.setProperty('--btn-min-height', themeData.btn_height + 'px');
  if (themeData.btn_font_weight) root.setProperty('--btn-weight', themeData.btn_font_weight);
  if (themeData.btn_shadow) root.setProperty('--btn-shadow', themeData.btn_shadow);
  if (themeData.card_border_width) root.setProperty('--card-border-width', themeData.card_border_width + 'px');
  if (themeData.input_radius) root.setProperty('--r-input', themeData.input_radius + 'px');

  const layoutPx = {
    hud_height: '--hud-height', hud_avatar_size: '--hud-avatar-size',
    hud_avatar_border: '--hud-avatar-border', hud_icon_size: '--hud-icon-size',
    hud_bell_size: '--hud-bell-size', hud_stat_font: '--hud-stat-font',
    hud_stat_gap: '--hud-stat-gap', hud_btn_size: '--hud-btn-size',
    hud_badge_size: '--hud-badge-size', hud_badge_font: '--hud-badge-font',
    hud_padding_x: '--hud-padding-x',
    tab_height: '--tab-height', tab_icon_size: '--tab-icon-size',
    tab_label_font: '--tab-label-font', tab_item_gap: '--tab-item-gap',
    tab_item_padding_x: '--tab-item-padding-x', tab_item_padding_y: '--tab-item-padding-y',
    tab_item_min_size: '--tab-item-min-size',
    home_padding: '--home-padding', home_max_width: '--home-max-width',
    home_greeting_font: '--home-greeting-font', home_greeting_margin: '--home-greeting-margin',
    quick_btn_icon_size: '--quick-btn-icon-size', quick_btn_icon_radius: '--quick-btn-icon-radius',
    quick_btn_icon_font: '--quick-btn-icon-font', quick_btn_label_font: '--quick-btn-label-font',
    quick_btn_gap: '--quick-btn-gap', quick_btn_padding: '--quick-btn-padding',
    quick_row_gap: '--quick-row-gap', quick_row_margin: '--quick-row-margin',
    game_tile_radius: '--game-tile-radius', game_tile_gap: '--game-tile-gap',
    game_tile_icon_size: '--game-tile-icon-size', game_tile_icon_font: '--game-tile-icon-font',
    game_tile_name_font: '--game-tile-name-font', game_tile_content_gap: '--game-tile-content-gap',
    sheet_radius: '--sheet-radius', sheet_padding_x: '--sheet-padding-x',
    sheet_padding_top: '--sheet-padding-top',
    gm_btn_padding_y: '--gm-btn-padding-y', gm_btn_padding_x: '--gm-btn-padding-x',
    gm_btn_gap: '--gm-btn-gap', gm_btn_radius: '--gm-btn-radius',
    gm_btn_margin_bottom: '--gm-btn-margin-bottom', gm_btn_icon_size: '--gm-btn-icon-size',
    gm_btn_icon_radius: '--gm-btn-icon-radius', gm_btn_icon_font: '--gm-btn-icon-font',
    gm_btn_title_font: '--gm-btn-title-font', gm_btn_sub_font: '--gm-btn-sub-font',
    gm_btn_arrow_font: '--gm-btn-arrow-font',
    gm_chip_padding_y: '--gm-chip-padding-y', gm_chip_padding_x: '--gm-chip-padding-x',
    gm_chip_gap: '--gm-chip-gap', gm_chip_radius: '--gm-chip-radius',
    gm_chip_font: '--gm-chip-font', gm_chip_icon_font: '--gm-chip-icon-font',
    gm_chips_grid_gap: '--gm-chips-grid-gap', gm_chips_margin_top: '--gm-chips-margin-top',
    menu_close_size: '--menu-close-size', menu_close_font: '--menu-close-font',
    menu_header_icon_size: '--menu-header-icon-size', menu_header_icon_radius: '--menu-header-icon-radius',
    menu_header_icon_font: '--menu-header-icon-font', menu_header_title_font: '--menu-header-title-font',
    menu_header_gap: '--menu-header-gap', menu_header_margin: '--menu-header-margin',
    bot_card_avatar_size: '--bot-card-avatar-size', bot_card_avatar_border: '--bot-card-avatar-border',
    bot_card_name_font: '--bot-card-name-font', bot_card_sub_font: '--bot-card-sub-font',
    bot_card_accent_height: '--bot-card-accent-height', bot_grid_gap: '--bot-grid-gap',
    bot_back_btn_size: '--bot-back-btn-size', bot_back_btn_font: '--bot-back-btn-font',
    bot_title_font: '--bot-title-font',
  };
  for (const [key, cssVar] of Object.entries(layoutPx)) {
    if (themeData[key]) root.setProperty(cssVar, themeData[key] + 'px');
  }
  if (themeData.game_tile_aspect) root.setProperty('--game-tile-aspect', themeData.game_tile_aspect);
  if (themeData.sheet_max_height) root.setProperty('--sheet-max-height', themeData.sheet_max_height + 'vh');
  if (themeData.sheet_bg) root.setProperty('--sheet-bg', themeData.sheet_bg);
}

export function assetImg(slot, fallbackEmoji, width, height) {
  const url = getAsset(slot);
  if (url) {
    const isSvg = url.includes('.svg');
    const rendering = isSvg ? 'image-rendering:-webkit-optimize-contrast;' : '';
    return `<img src="${url}" alt="" style="width:${width}px;height:${height}px;object-fit:contain;${rendering}" draggable="false">`;
  }
  return `<span style="font-size:${Math.min(width, height) * 0.7}px;line-height:1;">${fallbackEmoji}</span>`;
}

export function emoji(key, fallback, size = 20) {
  const url = getAsset('emoji_' + key);
  if (url) {
    const isSvg = url.includes('.svg');
    const rendering = isSvg ? 'image-rendering:-webkit-optimize-contrast;' : '';
    return `<img src="${url}" alt="" style="width:${size}px;height:${size}px;object-fit:contain;vertical-align:middle;${rendering}" draggable="false">`;
  }
  return fallback;
}
