import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { useTheme } from '../contexts/ThemeContext';
import { usePlatform } from '../platform';

const COLOR_TABLE = {
  'theme-dark':    { auth: '#1e1f22', sidebar: '#141318', channelPanel: '#1C1D22', chat: '#1C1D22', isDark: false },
  'theme-light':   { auth: '#e3e5e8', sidebar: '#e3e5e8', channelPanel: '#e3e5e8', chat: '#ffffff', isDark: true },
  'theme-darker':  { auth: '#121214', sidebar: '#121214', channelPanel: '#121214', chat: '#202225', isDark: false },
  'theme-midnight':{ auth: '#000000', sidebar: '#000000', channelPanel: '#000000', chat: '#0c0c14', isDark: false },
};

function getBarColors(theme, pathname, mobileView) {
  const entry = COLOR_TABLE[theme] || COLOR_TABLE['theme-dark'];

  // Auth pages
  if (pathname === '/' || pathname === '/register' || pathname === '/recovery') {
    return { statusBarColor: entry.auth, navigationBarColor: entry.auth, isDarkContent: entry.isDark };
  }

  // Chat page — pick based on which mobile panel is active
  if (mobileView === 'sidebar') {
    return { statusBarColor: entry.sidebar, navigationBarColor: entry.channelPanel, isDarkContent: entry.isDark };
  }

  return { statusBarColor: entry.chat, navigationBarColor: entry.chat, isDarkContent: entry.isDark };
}

export function useSystemBars(mobileView) {
  const { theme } = useTheme();
  const location = useLocation();
  const platform = usePlatform();
  const lastRef = useRef(null);

  useEffect(() => {
    if (!platform.features.hasSystemBars) return;

    const colors = getBarColors(theme, location.pathname, mobileView);
    const key = `${colors.statusBarColor}|${colors.navigationBarColor}|${colors.isDarkContent}`;

    if (lastRef.current === key) return;
    lastRef.current = key;

    platform.systemBars.setColors(colors);
  }, [theme, location.pathname, mobileView, platform]);
}
