import React, { useState } from 'react';
import { RotateCw, Menu, X, Globe, Moon, Sun } from 'lucide-react';
import { useApp } from '../context/AppContext';

export const Header: React.FC = () => {
  const {
    state,
    texts,
    settings,
    menuItems,
    language,
    theme,
    toggleTheme,
    setTheme,
    setLanguage,
    t,
    setTimeFilter,
    handleManualRefresh,
    openContentModal
  } = useApp();

  const [isRotating, setIsRotating] = useState(false);
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  const onRefresh = () => {
    setIsRotating(true);
    handleManualRefresh();
    setTimeout(() => setIsRotating(false), 600);
  };

  const handleNavClick = (item: any) => {
    setIsMobileMenuOpen(false);
    const url = item.url || '';
    if (item.open_as === 'modal' || (item.description && !url.startsWith('http') && !url.startsWith('/'))) {
      openContentModal(item.id);
      return;
    }
    if (url.startsWith('#')) {
      const modalType = url.replace('#', '');
      openContentModal(modalType);
      return;
    }
    if (item.target === '_blank' || url.startsWith('http://') || url.startsWith('https://')) {
      window.open(url, item.target || '_blank');
      return;
    }
    if (url === '/') {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      return;
    }
    window.location.href = url;
  };

  return (
    <header
      id="topbd-header"
      className="sticky top-0 z-40 w-full border-b backdrop-blur-md transition-colors"
      style={{
        backgroundColor: 'var(--header-bg, #0A0D0FEE)',
        borderColor: 'var(--border-color, #222A33)'
      }}
    >
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between gap-2 sm:gap-4">
        {/* Left Side: Original TOPBD Logo */}
        <div className="flex items-center gap-2 sm:gap-3 shrink-0">
          <a
            href="/"
            onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            className="flex items-center gap-2 group cursor-pointer"
            id="brand-logo-btn"
          >
            {/* Custom TOPBD Upward-Step Outbid Icon */}
            <div className="w-8 h-8 sm:w-9 sm:h-9 rounded-lg bg-gradient-to-tr from-emerald-600 to-emerald-400 flex items-center justify-center shadow-lg shadow-emerald-950/40 group-hover:scale-105 transition-transform shrink-0">
              <svg
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                className="text-white sm:w-5 sm:h-5"
              >
                {/* Outbid Step & Arrow Path */}
                <path
                  d="M4 18L9 13H13L18 6M18 6H13M18 6V11"
                  stroke="currentColor"
                  strokeWidth="2.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <circle cx="18" cy="6" r="1.5" fill="#F42A41" />
              </svg>
            </div>

            <span
              className="font-extrabold text-base sm:text-lg tracking-tight font-mono transition-colors"
              style={{ color: 'var(--heading-color, #FFFFFF)' }}
            >
              {t('site_logo_text', undefined, texts.site_logo_text || 'TOPBD')}
            </span>
          </a>
        </div>

        {/* Right Side: Grouped Controls (Time Filter, Language Switcher, Theme Toggle, Refresh & Menu) */}
        <div className="flex items-center gap-1.5 sm:gap-2.5 shrink-0 ml-auto">
          {/* Time Switch (ALL TIME / TODAY) - Aligned to the Right */}
          <div
            id="time-switch-tabs"
            className="inline-flex items-center p-0.5 sm:p-1 rounded-lg border shadow-inner transition-colors"
            style={{
              backgroundColor: 'var(--sub-card-bg, #141A20)',
              borderColor: 'var(--border-color, #222A33)'
            }}
          >
            <button
              id="tab-all-time"
              onClick={() => setTimeFilter('all_time')}
              className={`px-2.5 sm:px-3 py-1 text-[11px] sm:text-xs font-semibold rounded-md transition-all cursor-pointer whitespace-nowrap ${
                state.timeFilter === 'all_time'
                  ? 'bg-emerald-600 text-white shadow-sm'
                  : 'text-slate-400 hover:text-slate-200 dark:hover:text-slate-100'
              }`}
            >
              {t('tab_all_time', undefined, texts.tab_all_time || 'ALL TIME')}
            </button>
            <button
              id="tab-today"
              onClick={() => setTimeFilter('today')}
              className={`px-2.5 sm:px-3 py-1 text-[11px] sm:text-xs font-semibold rounded-md transition-all cursor-pointer whitespace-nowrap ${
                state.timeFilter === 'today'
                  ? 'bg-emerald-600 text-white shadow-sm'
                  : 'text-slate-400 hover:text-slate-200 dark:hover:text-slate-100'
              }`}
            >
              {t('tab_today', undefined, texts.tab_today || 'TODAY')}
            </button>
          </div>

          {/* Desktop Language Switcher (Only visible on md+ screens to preserve mobile header space) */}
          {settings.translation_enabled !== false && (
            <div
              id="language-switcher"
              className="hidden md:inline-flex items-center p-0.5 rounded-lg border shadow-inner text-xs font-medium transition-colors"
              style={{
                backgroundColor: 'var(--sub-card-bg, #141A20)',
                borderColor: 'var(--border-color, #222A33)'
              }}
              title="Change Language / ভাষা পরিবর্তন করুন"
            >
              <button
                id="btn-lang-en"
                type="button"
                onClick={() => setLanguage('en')}
                className={`px-2.5 py-1 rounded-md transition-all cursor-pointer font-semibold ${
                  language === 'en'
                    ? 'bg-emerald-600 text-white shadow-sm'
                    : 'text-slate-400 hover:text-slate-200'
                }`}
              >
                ENG
              </button>
              <button
                id="btn-lang-bn"
                type="button"
                onClick={() => setLanguage('bn')}
                className={`px-2.5 py-1 rounded-md transition-all cursor-pointer font-semibold font-serif ${
                  language === 'bn'
                    ? 'bg-emerald-600 text-white shadow-sm'
                    : 'text-slate-400 hover:text-slate-200'
                }`}
              >
                বাংলা
              </button>
            </div>
          )}

          {/* Compact Theme Toggle Button (🌙 Dark / ☀️ Light) */}
          <button
            id="btn-theme-toggle"
            type="button"
            onClick={toggleTheme}
            title={theme === 'dark' ? 'Switch to Light Mode (লাইট মোড)' : 'Switch to Dark Mode (ডার্ক মোড)'}
            aria-label="Toggle dark and light theme"
            className="p-1.5 sm:p-2 rounded-lg border transition-all active:scale-95 cursor-pointer shrink-0 flex items-center justify-center hover:opacity-90"
            style={{
              backgroundColor: 'var(--sub-card-bg, #141A20)',
              borderColor: 'var(--border-color, #222A33)',
              color: 'var(--text-color, #F0F4F8)'
            }}
          >
            {theme === 'dark' ? (
              <span className="flex items-center gap-1">
                <Moon className="w-4 h-4 text-amber-300 fill-amber-300/20" />
              </span>
            ) : (
              <span className="flex items-center gap-1">
                <Sun className="w-4 h-4 text-amber-500 fill-amber-500/20" />
              </span>
            )}
          </button>

          {/* Refresh Action */}
          <button
            id="btn-refresh-ranking"
            onClick={onRefresh}
            title={t('refresh_tooltip', undefined, 'Refresh Ranking & Statistics')}
            className="p-1.5 sm:p-2 rounded-lg border transition-all active:scale-95 cursor-pointer shrink-0"
            style={{
              backgroundColor: 'var(--sub-card-bg, #141A20)',
              borderColor: 'var(--border-color, #222A33)',
              color: 'var(--text-color, #F0F4F8)'
            }}
          >
            <RotateCw className={`w-4 h-4 ${isRotating ? 'animate-spin text-emerald-400' : ''}`} />
          </button>

          {/* Universal Menu Toggle Button (Mobile, Tablet, Desktop) */}
          <button
            id="btn-mobile-menu-toggle"
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            aria-label="Toggle navigation menu"
            className="p-1.5 sm:p-2 rounded-lg border transition-colors cursor-pointer shrink-0"
            style={{
              backgroundColor: 'var(--sub-card-bg, #141A20)',
              borderColor: 'var(--border-color, #222A33)',
              color: 'var(--text-color, #F0F4F8)'
            }}
          >
            {isMobileMenuOpen ? <X className="w-4 h-4" /> : <Menu className="w-4 h-4" />}
          </button>
        </div>
      </div>

      {/* Universal Dropdown Menu (Mobile, Tablet & Desktop) */}
      {isMobileMenuOpen && (
        <div
          className="border-t px-4 sm:px-6 lg:px-8 py-3.5 shadow-2xl transition-colors animate-in slide-in-from-top-2"
          style={{
            backgroundColor: 'var(--card-color, #0E1216)',
            borderColor: 'var(--border-color, #222A33)'
          }}
        >
          <div className="max-w-4xl mx-auto space-y-3">
          {/* Mobile Theme & Language Controls Bar */}
          <div className="flex flex-col sm:flex-row gap-2">
            {/* Mobile-Only Language Switcher Bar */}
            {settings.translation_enabled !== false && (
              <div
                className="md:hidden flex-1 flex items-center justify-between p-2.5 rounded-xl border"
                style={{
                  backgroundColor: 'var(--sub-card-bg, #141A20)',
                  borderColor: 'var(--border-color, #222A33)'
                }}
              >
                <div className="flex items-center gap-2">
                  <Globe className="w-4 h-4 text-emerald-500 shrink-0" />
                  <span
                    className="text-xs font-semibold"
                    style={{ color: 'var(--heading-color, #F0F4F8)' }}
                  >
                    {language === 'bn' ? 'ভাষা / Language' : 'Language / ভাষা'}
                  </span>
                </div>
                <div
                  className="inline-flex items-center p-0.5 rounded-lg border text-xs font-semibold"
                  style={{
                    backgroundColor: 'var(--bg-color, #0A0D0F)',
                    borderColor: 'var(--border-color, #222A33)'
                  }}
                >
                  <button
                    type="button"
                    onClick={() => setLanguage('en')}
                    className={`px-3 py-1 rounded-md transition-all cursor-pointer ${
                      language === 'en'
                        ? 'bg-emerald-600 text-white shadow-sm font-bold'
                        : 'text-slate-400 hover:text-slate-200'
                    }`}
                  >
                    English
                  </button>
                  <button
                    type="button"
                    onClick={() => setLanguage('bn')}
                    className={`px-3 py-1 rounded-md transition-all cursor-pointer font-serif ${
                      language === 'bn'
                        ? 'bg-emerald-600 text-white shadow-sm font-bold'
                        : 'text-slate-400 hover:text-slate-200'
                    }`}
                  >
                    বাংলা
                  </button>
                </div>
              </div>
            )}

            {/* Mobile Theme Switcher Bar */}
            <div
              className="md:hidden flex items-center justify-between p-2.5 rounded-xl border"
              style={{
                backgroundColor: 'var(--sub-card-bg, #141A20)',
                borderColor: 'var(--border-color, #222A33)'
              }}
            >
              <div className="flex items-center gap-2">
                {theme === 'dark' ? (
                  <Moon className="w-4 h-4 text-amber-300 shrink-0" />
                ) : (
                  <Sun className="w-4 h-4 text-amber-500 shrink-0" />
                )}
                <span
                  className="text-xs font-semibold"
                  style={{ color: 'var(--heading-color, #F0F4F8)' }}
                >
                  {theme === 'dark' ? 'Dark Mode' : 'Light Mode'}
                </span>
              </div>
              <div
                className="inline-flex items-center p-0.5 rounded-lg border text-xs font-semibold"
                style={{
                  backgroundColor: 'var(--bg-color, #0A0D0F)',
                  borderColor: 'var(--border-color, #222A33)'
                }}
              >
                <button
                  type="button"
                  onClick={() => setTheme('dark')}
                  className={`px-2.5 py-1 rounded-md transition-all cursor-pointer flex items-center gap-1 ${
                    theme === 'dark'
                      ? 'bg-emerald-600 text-white shadow-sm font-bold'
                      : 'text-slate-400 hover:text-slate-200'
                  }`}
                >
                  <Moon className="w-3.5 h-3.5" />
                  <span>Dark</span>
                </button>
                <button
                  type="button"
                  onClick={() => setTheme('light')}
                  className={`px-2.5 py-1 rounded-md transition-all cursor-pointer flex items-center gap-1 ${
                    theme === 'light'
                      ? 'bg-emerald-600 text-white shadow-sm font-bold'
                      : 'text-slate-400 hover:text-slate-200'
                  }`}
                >
                  <Sun className="w-3.5 h-3.5" />
                  <span>Light</span>
                </button>
              </div>
            </div>
          </div>

          {/* Navigation Links Grid (Responsive for Mobile, Tablet, and Desktop) */}
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2 text-xs">
            {menuItems
              .filter(m => m.is_active && (!m.location || m.location === 'header' || m.location === 'both'))
              .sort((a, b) => a.display_order - b.display_order)
              .map((item) => {
                const navKey = `nav_${item.title.toLowerCase().replace(/[^a-z0-9]/g, '_')}`;
                return (
                  <button
                    key={item.id}
                    onClick={() => handleNavClick(item)}
                    className="px-3 py-2.5 rounded-lg border text-left font-medium transition-colors cursor-pointer flex flex-col justify-center group hover:border-emerald-500/50"
                    style={{
                      backgroundColor: 'var(--sub-card-bg, #141A20)',
                      borderColor: 'var(--border-color, #222A33)',
                      color: 'var(--text-color, #F0F4F8)'
                    }}
                  >
                    <span className="font-semibold text-xs group-hover:text-emerald-400 transition-colors">{t(navKey, undefined, item.title)}</span>
                    {item.description && (
                      <span className="text-[10px] text-slate-400 line-clamp-1 mt-0.5">{item.description}</span>
                    )}
                  </button>
                );
              })}
          </div>
          </div>
        </div>
      )}
    </header>
  );
};
