// Design tokens for Himma

const DEFAULT_FONTS = {
  display: "'Fraunces', 'Times New Roman', serif",
  ui:      "'Inter', system-ui, sans-serif",
  mono:    "'JetBrains Mono', ui-monospace, monospace",
  arabic:  "'Amiri', 'Fraunces', serif",
};

const FONTS = { ...DEFAULT_FONTS };

const DEFAULT_RADIUS = {
  xs: 3,
  sm: 10,
  md: 14,
  lg: 18,
  xl: 20,
  modal: 24,
  sheet: 28,
  pill: 999,
};

const DEFAULT_SPACE = {
  pageX: 16,
  card: 18,
  rowX: 16,
  rowY: 12,
  sheetX: 18,
  sheetBottom: 30,
};

const DEFAULT_SHADOW = {
  sheet: '0 -18px 40px rgba(0,0,0,0.16)',
  modal: '0 24px 50px rgba(0,0,0,0.22)',
  popover: '0 18px 34px rgba(0,0,0,0.12)',
  toast: '0 16px 34px rgba(0,0,0,0.14)',
  pillToast: '0 12px 26px rgba(0,0,0,0.13)',
  panel: '0 20px 60px rgba(0,0,0,0.35)',
};

function alpha(color, opacity) {
  const amount = Math.max(0, Math.min(1, opacity));
  const shortHex = /^#([0-9a-f]{3})$/i.exec(color);
  const fullHex = /^#([0-9a-f]{6})$/i.exec(color);

  if (shortHex) {
    const [r, g, b] = shortHex[1].split('').map((c) => parseInt(c + c, 16));
    return `rgba(${r},${g},${b},${amount})`;
  }
  if (fullHex) {
    const value = fullHex[1];
    const r = parseInt(value.slice(0, 2), 16);
    const g = parseInt(value.slice(2, 4), 16);
    const b = parseInt(value.slice(4, 6), 16);
    return `rgba(${r},${g},${b},${amount})`;
  }

  return color;
}

function defineTheme(theme) {
  const radius = { ...DEFAULT_RADIUS, ...(theme.radius || {}) };
  const space = { ...DEFAULT_SPACE, ...(theme.space || {}) };
  const shadow = { ...DEFAULT_SHADOW, ...(theme.shadow || {}) };
  const normalized = { ...theme, radius, space, shadow };

  normalized.components = {
    card: {
      bg: normalized.surface,
      border: normalized.line,
      radius: radius.xl,
      padding: space.card,
    },
    compactCard: {
      bg: normalized.surface,
      border: normalized.line,
      radius: radius.lg,
    },
    row: {
      bg: 'transparent',
      border: normalized.line,
      padding: `${space.rowY}px ${space.rowX}px`,
    },
    iconButton: {
      size: 36,
      radius: 18,
      bg: 'transparent',
      border: normalized.line2,
      color: normalized.text,
    },
    sheet: {
      bg: normalized.surface,
      border: normalized.line,
      radius: radius.sheet,
      padding: `${space.sheetX}px ${space.sheetX}px ${space.sheetBottom}px`,
      shadow: shadow.sheet,
    },
    overlay: {
      scrim: 'rgba(0,0,0,0.24)',
      modalScrim: 'rgba(0,0,0,0.28)',
    },
    primaryButton: {
      bg: normalized.text,
      color: normalized.bg,
      radius: 25,
    },
    dangerButton: {
      bg: normalized.negative,
      color: '#FFFFFF',
      radius: 25,
    },
    secondaryButton: {
      bg: 'transparent',
      color: normalized.text,
      border: normalized.line2,
      radius: 13,
    },
    input: {
      bg: normalized.bg,
      border: normalized.line2,
      radius: 16,
    },
    toast: {
      bg: normalized.surface,
      border: normalized.line,
      radius: 16,
      shadow: shadow.toast,
      iconBg: alpha(normalized.positive, 0.10),
    },
    promoCard: {
      bg: `linear-gradient(155deg, ${normalized.surface2} 0%, ${normalized.surface} 90%)`,
      border: normalized.line,
      iconBg: normalized.surface3,
      ctaBg: normalized.text,
      ctaColor: normalized.bg,
    },
    ...theme.components,
  };

  return normalized;
}

const INTER_ONLY = {
  display: "'Inter', system-ui, sans-serif",
  ui: "'Inter', system-ui, sans-serif",
  mono: "'JetBrains Mono', ui-monospace, monospace",
};

const THEMES = {
  clinic: defineTheme({
    label: 'Clinic',
    description: 'electric blue',
    // Pure white / black / electric blue — Inter only
    bg:       '#FFFFFF',
    surface:  '#FFFFFF',
    surface2: '#F6F7F9',
    surface3: '#EEF0F4',
    line:     'rgba(0,0,0,0.06)',
    line2:    'rgba(0,0,0,0.12)',
    text:     '#0A0A0A',
    textDim:  'rgba(10,10,10,0.62)',
    textMute: 'rgba(10,10,10,0.42)',
    positive: '#1F8A4C',
    negative: '#D23B2E',
    warning:  '#C77A00',
    accentOverride: '#2C5BFF',       // electric blue
    pageBg: 'radial-gradient(circle at 30% 20%, #F4F6FA, #E4E8EF)',
    fontOverride: INTER_ONLY,
  }),
  dawn: defineTheme({
    label: 'Dawn',
    description: 'teal + ink',
    bg:       '#FAFBF8',
    surface:  '#FFFFFF',
    surface2: '#EEF5F2',
    surface3: '#E6EEF7',
    line:     'rgba(13,31,26,0.07)',
    line2:    'rgba(13,31,26,0.14)',
    text:     '#111C18',
    textDim:  'rgba(17,28,24,0.64)',
    textMute: 'rgba(17,28,24,0.43)',
    positive: '#16825A',
    negative: '#C53F36',
    warning:  '#A86800',
    accentOverride: '#007E75',
    pageBg: 'radial-gradient(circle at 28% 18%, #F3F7EF, #DDE9F2)',
    fontOverride: INTER_ONLY,
  }),
  midnight: defineTheme({
    label: 'Midnight',
    description: 'slate + cyan',
    bg:       '#10141B',
    surface:  '#171C24',
    surface2: '#202632',
    surface3: '#2A3342',
    line:     'rgba(255,255,255,0.07)',
    line2:    'rgba(255,255,255,0.14)',
    text:     '#F6F8FB',
    textDim:  'rgba(246,248,251,0.68)',
    textMute: 'rgba(246,248,251,0.46)',
    positive: '#67D39E',
    negative: '#FF7A72',
    warning:  '#F5B84B',
    accentOverride: '#7CCBFF',
    pageBg: 'radial-gradient(circle at 30% 20%, #273141, #0B0F15)',
    fontOverride: INTER_ONLY,
    shadow: {
      sheet: '0 -18px 42px rgba(0,0,0,0.42)',
      modal: '0 24px 54px rgba(0,0,0,0.48)',
      popover: '0 18px 34px rgba(0,0,0,0.35)',
      toast: '0 16px 34px rgba(0,0,0,0.34)',
      pillToast: '0 12px 26px rgba(0,0,0,0.32)',
      panel: '0 20px 60px rgba(0,0,0,0.42)',
    },
    components: {
      overlay: {
        scrim: 'rgba(0,0,0,0.42)',
        modalScrim: 'rgba(0,0,0,0.48)',
      },
    },
  }),
};

const warnedThemeKeys = new Set();

function getTheme(themeKey) {
  const key = themeKey || 'clinic';
  if (THEMES[key]) return THEMES[key];

  if (!warnedThemeKeys.has(key)) {
    console.warn(`[Himma] Unknown theme "${key}". Falling back to "clinic".`);
    warnedThemeKeys.add(key);
  }
  return THEMES.clinic;
}

function getThemeOptions() {
  return Object.keys(THEMES).map((key) => ({
    key,
    label: THEMES[key].label || key,
    description: THEMES[key].description || '',
    accent: THEMES[key].accentOverride,
  }));
}

function applyThemeFonts(theme) {
  Object.assign(FONTS, DEFAULT_FONTS, theme?.fontOverride || {});
}

const ACCENTS = {
  champagne: '#D4B27A',
  bronze:    '#B8824A',
  copper:    '#C98752',
  sand:      '#C9B088',
};

// AED currency formatter (numbers only; prefix/suffix handled separately)
function fmtAED(n, opts = {}) {
  const { decimals = 0, compact = false } = opts;
  if (compact && Math.abs(n) >= 1000) {
    if (Math.abs(n) >= 1_000_000) return (n/1_000_000).toFixed(1).replace(/\.0$/,'') + 'M';
    return (n/1000).toFixed(1).replace(/\.0$/,'') + 'K';
  }
  return n.toLocaleString('en-AE', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
}

function useTweaks() {
  const [t, setT] = React.useState(() => ({ ...(window.__HIMMA_TWEAKS__ || {}) }));
  React.useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__edit_mode_set_keys' && e.data.edits) {
        setT(prev => ({ ...prev, ...e.data.edits }));
      }
    };
    window.addEventListener('message', handler);
    return () => window.removeEventListener('message', handler);
  }, []);
  return [t, (edits) => setT(prev => ({ ...prev, ...edits }))];
}

Object.assign(window, {
  THEMES,
  getTheme,
  getThemeOptions,
  applyThemeFonts,
  alpha,
  ACCENTS,
  DEFAULT_FONTS,
  FONTS,
  fmtAED,
  useTweaks,
});
