// 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',
    gold: '--gold',
    gold_soft: '--gold-soft',
    blue: '--blue',
    cyan: '--cyan',
    purple: '--purple',
    success: '--success',
    error: '--error',
    text_primary: '--text-primary',
    text_secondary: '--text-secondary',
    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]);
  }

  // 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');
}

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;
}
