'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { Plus, ChevronDown, Coins } from 'lucide-react';
import { clearTokens, getCurrentUser, apiRequest } from '../lib/api';
import { formatCoins } from '../lib/coins';
import { loginHref } from '../lib/authRedirect';
import { NotificationBell } from './NotificationBell';

const navLinks = [
  { href: '/', label: 'Home', exact: true },
  { href: '/fantasy', label: 'Contests' },
  { href: '/matches', label: 'Live' },
  { href: '/wallet', label: 'Wallet' },
  { href: '/profile', label: 'Account' },
];

function initials(name?: string) {
  if (!name) return 'U';
  return name
    .split(/\s+/)
    .slice(0, 2)
    .map((p) => p[0]?.toUpperCase() || '')
    .join('');
}

export function SiteHeader() {
  const pathname = usePathname();
  const router = useRouter();
  const [user, setUser] = useState<any>(() => getCurrentUser());
  const [balance, setBalance] = useState<number | null>(null);
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    setMenuOpen(false);
  }, [pathname]);

  useEffect(() => {
    const u = getCurrentUser();
    setUser(u);
    if (!u) {
      setBalance(null);
      return;
    }

    let cancelled = false;
    const loadBalance = () => {
      apiRequest('/wallet')
        .then((r) => {
          if (!cancelled) setBalance(r.data?.wallet?.totalBalance ?? 0);
        })
        .catch(() => {
          if (!cancelled) setBalance(null);
        });
    };

    loadBalance();

    const onFocus = () => loadBalance();
    const onCoins = () => loadBalance();
    window.addEventListener('focus', onFocus);
    window.addEventListener('my11s:coins', onCoins);
    return () => {
      cancelled = true;
      window.removeEventListener('focus', onFocus);
      window.removeEventListener('my11s:coins', onCoins);
    };
  }, []);

  const logout = async () => {
    setMenuOpen(false);
    try {
      await apiRequest('/auth/logout', { method: 'POST', body: JSON.stringify({}) });
    } catch {
      /* ignore */
    }
    clearTokens();
    setUser(null);
    router.push('/login');
  };

  return (
    <header className="sticky top-0 z-40 pt-[env(safe-area-inset-top,0px)]">
      <div className="bg-gradient-to-b from-d11-red to-d11-red-dark text-white shadow-header">
        <div className="mx-auto flex h-12 max-w-app-lg items-center justify-between gap-2 px-3 sm:px-4">
          <Link href="/" className="flex items-center gap-2" aria-label="MY11s home">
            <span className="flex h-8 w-8 items-center justify-center rounded-xl bg-white font-display text-xs font-extrabold text-d11-red shadow-sm">
              11
            </span>
            <span className="font-display text-lg font-extrabold tracking-tight">
              MY<span className="font-bold opacity-90">11s</span>
            </span>
          </Link>

          <div className="flex items-center gap-2">
            {user ? (
              <>
                <NotificationBell />
                <Link
                  href="/wallet"
                  className="flex h-9 items-center overflow-hidden rounded-full bg-black/20 shadow-sm ring-1 ring-white/15 transition hover:bg-black/30 active:scale-[0.98]"
                >
                  <span className="flex items-center gap-1 px-2.5 text-[11px] font-bold tabular-nums">
                    <Coins className="h-3.5 w-3.5 text-amber-300" aria-hidden />
                    {balance != null ? formatCoins(balance, { suffix: false }) : '—'}
                  </span>
                  <span
                    className="flex h-9 w-9 items-center justify-center bg-white text-d11-red"
                    aria-label="Add coins"
                  >
                    <Plus className="h-4 w-4 stroke-[2.5]" />
                  </span>
                </Link>

                <div className="relative">
                  <button
                    type="button"
                    onClick={() => setMenuOpen((v) => !v)}
                    className="flex h-9 items-center gap-1 rounded-full bg-black/20 py-0.5 pl-0.5 pr-1.5 ring-1 ring-white/15 transition hover:bg-black/30 active:scale-[0.98]"
                    aria-expanded={menuOpen}
                    aria-haspopup="menu"
                    aria-label="Account menu"
                  >
                    <span className="flex h-7 w-7 items-center justify-center rounded-full bg-white font-display text-[11px] font-extrabold text-d11-red">
                      {initials(user.name)}
                    </span>
                    <ChevronDown className={`h-3.5 w-3.5 opacity-80 transition ${menuOpen ? 'rotate-180' : ''}`} />
                  </button>

                  {menuOpen && (
                    <>
                      <button
                        type="button"
                        className="fixed inset-0 z-40 cursor-default bg-black/20 backdrop-blur-[1px]"
                        aria-label="Close menu"
                        onClick={() => setMenuOpen(false)}
                      />
                      <div
                        role="menu"
                        className="absolute right-0 z-50 mt-2 w-56 overflow-hidden rounded-2xl border border-d11-line bg-white py-1.5 text-d11-ink shadow-lift"
                      >
                        <div className="border-b border-gray-100 px-4 py-3">
                          <p className="truncate text-sm font-bold">{user.name}</p>
                          <p className="truncate font-mono text-[11px] text-d11-muted">{user.phone}</p>
                        </div>
                        {[
                          { href: '/profile', label: 'My Account' },
                          { href: '/wallet', label: 'My Balance' },
                          { href: '/fantasy/rankings', label: 'Leaderboard' },
                          { href: '/kyc', label: 'KYC' },
                          { href: '/rules', label: 'How to Play' },
                        ].map((item) => (
                          <Link
                            key={item.href}
                            href={item.href}
                            role="menuitem"
                            onClick={() => setMenuOpen(false)}
                            className="block min-h-[44px] px-4 py-3 text-sm font-semibold transition hover:bg-gray-50"
                          >
                            {item.label}
                          </Link>
                        ))}
                        <button
                          type="button"
                          role="menuitem"
                          onClick={logout}
                          className="block w-full min-h-[44px] px-4 py-3 text-left text-sm font-semibold text-d11-red hover:bg-d11-soft"
                        >
                          Logout
                        </button>
                      </div>
                    </>
                  )}
                </div>
              </>
            ) : (
              <Link
                href={loginHref(pathname)}
                className="inline-flex h-9 items-center rounded-full bg-white px-4 text-xs font-extrabold text-d11-red shadow-sm transition hover:bg-gray-100 active:scale-[0.98]"
              >
                Login
              </Link>
            )}
          </div>
        </div>
      </div>

      <nav
        className="hidden border-b border-d11-line/80 bg-white/90 backdrop-blur-xl md:block"
        aria-label="Main"
      >
        <div className="mx-auto flex max-w-app-lg items-center gap-0.5 overflow-x-auto px-3 sm:px-4">
          {navLinks.map((l) => {
            const pathOnly = l.href.split('?')[0];
            const active = l.exact
              ? pathname === pathOnly
              : pathname.startsWith(pathOnly);
            return (
              <Link
                key={l.href}
                href={l.href}
                prefetch={true}
                className={`relative shrink-0 px-3.5 py-2.5 text-xs font-bold transition ${
                  active ? 'text-d11-red' : 'text-gray-500 hover:text-d11-ink'
                }`}
              >
                {l.label}
                {active && (
                  <span className="absolute inset-x-3 bottom-0 h-0.5 rounded-full bg-d11-red" />
                )}
              </Link>
            );
          })}
        </div>
      </nav>
    </header>
  );
}
