'use client';

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useTranslation, SUPPORTED_LOCALES, type Locale } from '@/lib/i18n';

// ─── Hamburger Icon ───────────────────────────────────────────────

function HamburgerIcon({ open }: { open: boolean }) {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      {open ? (
        <>
          <line x1="4" y1="4" x2="16" y2="16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
          <line x1="16" y1="4" x2="4" y2="16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
        </>
      ) : (
        <>
          <line x1="3" y1="5" x2="17" y2="5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
          <line x1="3" y1="10" x2="17" y2="10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
          <line x1="3" y1="15" x2="17" y2="15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
        </>
      )}
    </svg>
  );
}

// ─── Logo ─────────────────────────────────────────────────────────

function InvestibookLogo({ size = 28 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="ib-hdr-bg" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
          <stop offset="0%" stopColor="#5c5fbc" />
          <stop offset="100%" stopColor="#7c7fdc" />
        </linearGradient>
      </defs>
      <rect width="32" height="32" rx="7" fill="url(#ib-hdr-bg)" />
      <rect x="5" y="3" width="22" height="26" rx="3" fill="white" fillOpacity="0.18" />
      <rect x="5" y="3" width="22" height="26" rx="3" stroke="white" strokeWidth="1.5" />
      <rect x="8" y="7" width="7" height="5" rx="1" fill="white" fillOpacity="0.7" />
      <rect x="17" y="8" width="7" height="1.5" rx="0.75" fill="white" fillOpacity="0.5" />
      <rect x="17" y="11" width="5" height="1.5" rx="0.75" fill="white" fillOpacity="0.5" />
      <rect x="8" y="16" width="16" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
      <rect x="8" y="19.5" width="13" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
      <rect x="8" y="23" width="14" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
    </svg>
  );
}

// ─── User Dropdown ────────────────────────────────────────────────

function UserDropdown({ email, onSettings, onLogout }: { email: string; onSettings: () => void; onLogout: () => void }) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const { t } = useTranslation();

  useEffect(() => {
    if (!open) return;
    const close = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-flex', flexShrink: 0, width: '32px', height: '32px' }}>
      <button
        onClick={() => setOpen(v => !v)}
        title={email}
        style={{
          width: '32px', height: '32px', minWidth: '32px', borderRadius: '50%',
          background: 'linear-gradient(135deg, #5c5fbc, #7c7fdc)',
          border: 'none', cursor: 'pointer', padding: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: '13px', fontWeight: 700, color: '#fff',
          flexShrink: 0,
          boxSizing: 'border-box',
          transition: 'opacity 0.15s',
        }}
        onMouseEnter={e => (e.currentTarget.style.opacity = '0.85')}
        onMouseLeave={e => (e.currentTarget.style.opacity = '1')}
      >
        {email[0].toUpperCase()}
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', right: 0,
          background: '#fff', borderRadius: '10px',
          boxShadow: '0 4px 20px rgba(0,0,0,0.12)',
          border: '1px solid #eee',
          overflow: 'hidden', zIndex: 300, minWidth: '200px',
        }}>
          {/* Email header */}
          <div style={{ padding: '12px 16px', borderBottom: '1px solid #f0f0f0' }}>
            <div style={{ fontSize: '13px', color: '#999', marginBottom: '2px' }}>{t('header.signedInAs')}</div>
            <div style={{ fontSize: '13px', fontWeight: 600, color: '#333', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{email}</div>
          </div>
          {[
            { key: 'settings', label: t('header.settings'), muted: false, onClick: () => { setOpen(false); onSettings(); } },
            { key: 'signout', label: t('header.signOut'), muted: true, onClick: () => { setOpen(false); onLogout(); } },
          ].map(item => (
            <button
              key={item.key}
              onClick={item.onClick}
              style={{
                display: 'block', width: '100%', padding: '11px 16px',
                background: 'none', border: 'none', cursor: 'pointer',
                textAlign: 'left', fontSize: '14px', color: item.muted ? '#888' : '#333',
              }}
              onMouseEnter={e => (e.currentTarget.style.background = '#f7f7f7')}
              onMouseLeave={e => (e.currentTarget.style.background = 'none')}
            >
              {item.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Locale Switch ────────────────────────────────────────────────

const LOCALE_SHORT_LABEL: Record<Locale, string> = {
  zh: '中',
  en: 'EN',
  ja: '日',
};

const LOCALE_FULL_LABEL: Record<Locale, string> = {
  zh: '简体中文',
  en: 'English',
  ja: '日本語',
};

function LocaleSwitch({ variant = 'inline' }: { variant?: 'inline' | 'menu' }) {
  const { locale, setLocale, t } = useTranslation();

  if (variant === 'menu') {
    return (
      <div style={{ padding: '8px 12px 10px', borderBottom: '1px solid #f0f0f0' }}>
        <div style={{ fontSize: '11px', fontWeight: 700, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.6px', marginBottom: '8px' }}>
          {t('language.title')}
        </div>
        <div style={{ display: 'flex', gap: '6px' }}>
          {SUPPORTED_LOCALES.map(code => {
            const isActive = code === locale;
            return (
              <button
                key={code}
                onClick={() => setLocale(code)}
                aria-pressed={isActive}
                style={{
                  flex: 1,
                  padding: '6px 8px',
                  borderRadius: '6px',
                  border: isActive ? '1px solid #5c5fbc' : '1px solid #e5e7eb',
                  background: isActive ? '#ededf7' : '#fff',
                  color: isActive ? '#5c5fbc' : '#374151',
                  fontSize: '12px',
                  fontWeight: isActive ? 700 : 500,
                  cursor: 'pointer',
                  transition: 'background 0.15s, border-color 0.15s, color 0.15s',
                }}
              >
                {LOCALE_FULL_LABEL[code]}
              </button>
            );
          })}
        </div>
      </div>
    );
  }

  return <LocaleDropdown locale={locale} setLocale={setLocale} t={t} />;
}

function LocaleDropdown({
  locale,
  setLocale,
  t,
}: {
  locale: Locale;
  setLocale: (next: Locale) => void;
  t: (key: 'language.title' | 'language.zh' | 'language.en' | 'language.ja') => string;
}) {
  const [open, setOpen] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onMouseDown = (e: MouseEvent) => {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    document.addEventListener('mousedown', onMouseDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onMouseDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  return (
    <div ref={wrapperRef} style={{ position: 'relative' }}>
      <button
        type="button"
        onClick={() => setOpen(v => !v)}
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-label={t('language.title')}
        title={LOCALE_FULL_LABEL[locale]}
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: '6px',
          padding: '4px 8px 4px 7px',
          border: '1px solid #e5e7eb',
          borderRadius: '7px',
          background: open ? '#f4f4f7' : '#fff',
          color: '#374151',
          fontSize: '12px',
          fontWeight: 600,
          cursor: 'pointer',
          transition: 'background 0.15s, border-color 0.15s',
          lineHeight: 1,
        }}
        onMouseEnter={e => { if (!open) e.currentTarget.style.background = '#f9fafb'; }}
        onMouseLeave={e => { if (!open) e.currentTarget.style.background = '#fff'; }}
      >
        <GlobeIcon />
        <span style={{ minWidth: '18px', textAlign: 'left' }}>{LOCALE_SHORT_LABEL[locale]}</span>
        <ChevronDown open={open} />
      </button>

      {open && (
        <div
          role="listbox"
          aria-label={t('language.title')}
          style={{
            position: 'absolute',
            top: 'calc(100% + 6px)',
            right: 0,
            background: '#fff',
            border: '1px solid #eee',
            borderRadius: '10px',
            boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
            minWidth: '160px',
            padding: '6px',
            zIndex: 200,
          }}
        >
          {SUPPORTED_LOCALES.map(code => {
            const isActive = code === locale;
            return (
              <button
                key={code}
                role="option"
                aria-selected={isActive}
                onClick={() => { setLocale(code); setOpen(false); }}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  gap: '12px',
                  width: '100%',
                  padding: '7px 10px',
                  border: 'none',
                  borderRadius: '6px',
                  background: isActive ? '#ededf7' : 'transparent',
                  color: isActive ? '#5c5fbc' : '#374151',
                  fontSize: '13px',
                  fontWeight: isActive ? 600 : 500,
                  cursor: 'pointer',
                  textAlign: 'left',
                  transition: 'background 0.12s',
                }}
                onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#f5f5fa'; }}
                onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
              >
                <span>{LOCALE_FULL_LABEL[code]}</span>
                {isActive && <CheckIcon />}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function GlobeIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="1.7" />
      <path d="M3 12h18" stroke="currentColor" strokeWidth="1.7" />
      <path d="M12 3c2.8 3 4.2 6 4.2 9s-1.4 6-4.2 9c-2.8-3-4.2-6-4.2-9s1.4-6 4.2-9z" stroke="currentColor" strokeWidth="1.7" />
    </svg>
  );
}

function ChevronDown({ open }: { open: boolean }) {
  return (
    <svg
      width="10"
      height="10"
      viewBox="0 0 24 24"
      fill="none"
      aria-hidden="true"
      style={{ transform: open ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.15s' }}
    >
      <path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M5 12l4 4 10-10" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

// ─── AppHeader ────────────────────────────────────────────────────

export type ActivePage = 'workspaces' | 'ranking' | 'docs' | 'release-notes' | 'admin' | 'analytics';

const ADMIN_EMAILS = new Set([
  'chenyiwen@pingcap.com',
  'lingtao.li@pingcap.com',
  'chensiyu@pingcap.com',
  'charles.m@pingcap.com',
  'xieyujie@pingcap.com',
  'dihong.wang@pingcap.com',
  'xuhuaiyu@pingcap.com',
  'huoyao@pingcap.com',
  'dev@localhost',
]);

interface AppHeaderProps {
  activePage: ActivePage;
  email: string | null;
  onSettings: () => void;
  onLogout: () => void;
  isMobile: boolean;
}

export default function AppHeader({ activePage, email, onSettings, onLogout, isMobile }: AppHeaderProps) {
  const router = useRouter();
  const { t } = useTranslation();
  const isAdmin = ADMIN_EMAILS.has((email ?? '').toLowerCase());
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!menuOpen) return;
    const close = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) setMenuOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [menuOpen]);

  const navLinks: { label: string; page: ActivePage; href: string }[] = [
    { label: t('header.workspaces'), page: 'workspaces', href: '/' },
    { label: t('header.docs'), page: 'docs', href: '/docs' },
    { label: t('header.rankings'), page: 'ranking', href: '/ranking' },
    { label: t('header.whatsNew'), page: 'release-notes', href: '/release-notes' },
    ...(isAdmin ? [{ label: t('header.admin'), page: 'admin' as ActivePage, href: '/admin' }] : []),
  ];

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: isMobile ? '0 16px' : '0 40px',
      height: '52px',
      background: 'transparent',
    }}>
      {/* ── Left: Logo + brand ── */}
      <button
        onClick={() => router.push('/')}
        style={{
          display: 'flex', alignItems: 'center', gap: '9px',
          background: 'none', border: 'none', cursor: 'pointer', padding: 0,
          textDecoration: 'none',
        }}
      >
        <InvestibookLogo size={26} />
        {!isMobile && (
          <span style={{ fontSize: '16px', fontWeight: 700, color: '#1a1a2e', letterSpacing: '-0.3px' }}>
            Investibook
          </span>
        )}
      </button>

      {/* ── Right: Desktop nav or Mobile menu ── */}
      {isMobile ? (
        <div ref={menuRef} style={{ display: 'flex', alignItems: 'center', gap: '8px', flexShrink: 0 }}>
          {/* User avatar */}
          {email && (
            <UserDropdown email={email} onSettings={onSettings} onLogout={onLogout} />
          )}
          {/* Hamburger */}
          <button
            onClick={() => setMenuOpen(v => !v)}
            style={{
              background: menuOpen ? '#f0f0f0' : 'none',
              border: 'none', cursor: 'pointer',
              padding: '6px', borderRadius: '8px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              width: '32px', height: '32px', minWidth: '32px',
              boxSizing: 'border-box',
              color: '#374151',
              transition: 'background 0.15s',
              flexShrink: 0,
            }}
            aria-label={t('header.navigationMenu')}
          >
            <HamburgerIcon open={menuOpen} />
          </button>

          {/* Mobile dropdown menu */}
          {menuOpen && (
            <div style={{
              position: 'absolute', top: '52px', right: '16px',
              background: '#fff', borderRadius: '12px',
              boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
              border: '1px solid #eee',
              overflow: 'hidden', zIndex: 200, minWidth: '220px',
            }}>
              <LocaleSwitch variant="menu" />
              {navLinks.map(link => {
                const isActive = activePage === link.page;
                return (
                  <button
                    key={link.page}
                    onClick={() => { setMenuOpen(false); router.push(link.href); }}
                    style={{
                      display: 'flex', alignItems: 'center', width: '100%',
                      padding: '12px 16px', background: 'none', border: 'none',
                      cursor: 'pointer', textAlign: 'left',
                      fontSize: '14px',
                      fontWeight: isActive ? 700 : 500,
                      color: isActive ? '#5c5fbc' : '#374151',
                      borderLeft: isActive ? '3px solid #5c5fbc' : '3px solid transparent',
                      transition: 'background 0.15s',
                    }}
                    onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#f5f5f5'; }}
                    onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'none'; }}
                  >
                    {link.label}
                  </button>
                );
              })}
              {!email && (
                <button
                  onClick={() => {
                    setMenuOpen(false);
                    const path = typeof window !== 'undefined' ? window.location.pathname + window.location.search : '/';
                    router.push(`/login?redirect=${encodeURIComponent(path)}`);
                  }}
                  style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center', width: '100%',
                    padding: '12px 16px', background: 'none', border: 'none', borderTop: '1px solid #f0f0f0',
                    cursor: 'pointer', textAlign: 'center',
                    fontSize: '14px', fontWeight: 700, color: '#5c5fbc',
                  }}
                >
                  {t('login.signIn')}
                </button>
              )}
            </div>
          )}
        </div>
      ) : (
        <div style={{ display: 'flex', alignItems: 'center', gap: '2px' }}>
          {navLinks.map(link => {
            const isActive = activePage === link.page;
            return (
              <button
                key={link.page}
                onClick={() => router.push(link.href)}
                style={{
                  background: 'none', border: 'none', cursor: 'pointer',
                  padding: '6px 12px',
                  fontSize: '14px',
                  fontWeight: isActive ? 700 : 500,
                  color: isActive ? '#1a1a2e' : '#6b7280',
                  borderRadius: '6px',
                  transition: 'color 0.15s, background 0.15s',
                  letterSpacing: '0px',
                }}
                onMouseEnter={e => { if (!isActive) { e.currentTarget.style.color = '#1a1a2e'; e.currentTarget.style.background = '#f5f5f5'; } }}
                onMouseLeave={e => { if (!isActive) { e.currentTarget.style.color = '#6b7280'; e.currentTarget.style.background = 'none'; } }}
              >
                {link.label}
              </button>
            );
          })}

          {/* Divider */}
          <div style={{ width: '1px', height: '18px', background: '#e5e7eb', margin: '0 8px' }} />

          {/* Language switcher */}
          <LocaleSwitch />

          {/* Trailing user controls: avatar when signed in, Sign in CTA otherwise */}
          <div style={{ width: '1px', height: '18px', background: '#e5e7eb', margin: '0 8px' }} />
          {email ? (
            <UserDropdown email={email} onSettings={onSettings} onLogout={onLogout} />
          ) : (
            <button
              onClick={() => router.push(`/login?redirect=${encodeURIComponent(typeof window !== 'undefined' ? window.location.pathname + window.location.search : '/')}`)}
              style={{
                padding: '6px 14px',
                fontSize: '13px',
                fontWeight: 600,
                color: '#fff',
                background: 'linear-gradient(135deg, #5c5fbc, #7c7fdc)',
                border: 'none',
                borderRadius: '7px',
                cursor: 'pointer',
                transition: 'opacity 0.15s',
              }}
              onMouseEnter={e => (e.currentTarget.style.opacity = '0.9')}
              onMouseLeave={e => (e.currentTarget.style.opacity = '1')}
            >
              {t('login.signIn')}
            </button>
          )}
        </div>
      )}
    </header>
  );
}
