import { useState } from 'react'
import { Link } from 'react-router-dom'
import { Menu, X, User, LogOut } from 'lucide-react'
import { useTenantCtx } from '../context/TenantContext'

interface Props {
  user?: { nome: string } | null
  onLogout?: () => void
}

// Link que pode ser interno (React Router) ou externo/hash
type NavLink =
  | { label: string; to: string; hash?: string }   // React Router
  | { label: string; href: string }                 // âncora externa

const LINKS: NavLink[] = [
  { label: 'Promoções',   to: '/',         hash: '#promocoes' },
  { label: 'Catálogo',    to: '/catalogo'                     },
  { label: 'Sorteio',     to: '/raffle'                       },
  { label: 'Vagas',       to: '/vagas'                        },
  { label: 'Clube Odonto',to: '/clube/odonto'                 },
  { label: 'Clube Médico',to: '/clube/medico'                 },
]

const linkClass = 'text-sm font-medium text-slate-400 hover:text-white transition-colors'
const mobileLinkClass = 'block text-sm font-medium text-slate-400 hover:text-white py-2 transition-colors'

function NavItem({ link, mobile, onClick }: { link: NavLink; mobile?: boolean; onClick?: () => void }) {
  const cls = mobile ? mobileLinkClass : linkClass

  if ('href' in link) {
    return (
      <a href={link.href} onClick={onClick} className={cls}>
        {link.label}
      </a>
    )
  }

  // Usa pathname + hash para o React Router — o browser faz scroll automático ao anchor
  const to = link.hash ? { pathname: link.to, hash: link.hash } : link.to

  return (
    <Link to={to} onClick={onClick} className={cls}>
      {link.label}
    </Link>
  )
}

export default function Navbar({ user, onLogout }: Props) {
  const [open, setOpen] = useState(false)
  const tenant = useTenantCtx()

  return (
    <nav className="fixed top-0 left-0 right-0 z-50 bg-black/80 backdrop-blur-xl border-b border-white/5">
      <div className="max-w-6xl mx-auto px-4 h-16 flex items-center justify-between">

        {/* Logo */}
        <Link to="/" className="flex items-center gap-2">
          {tenant.logo_url
            ? <img src={tenant.logo_url} alt={tenant.name} className="h-8 object-contain" />
            : <span className="font-black text-lg tracking-tight" style={{ color: tenant.primary_color }}>{tenant.name}</span>
          }
        </Link>

        {/* Desktop links */}
        <div className="hidden md:flex items-center gap-6">
          {LINKS.map(l => (
            <NavItem key={l.label} link={l} />
          ))}
        </div>

        {/* Auth — desktop */}
        <div className="hidden md:flex items-center gap-3">
          {user ? (
            <>
              <Link to="/minha-area"
                className="flex items-center gap-2 text-sm font-medium text-slate-300 hover:text-white transition-colors">
                <User size={16} /> {(user.nome || 'Conta').split(' ')[0]}
              </Link>
              <button onClick={onLogout}
                className="flex items-center gap-1.5 text-sm text-slate-500 hover:text-rose-400 transition-colors">
                <LogOut size={15} />
              </button>
            </>
          ) : (
            <Link to="/login"
              className="px-4 py-2 rounded-xl text-sm font-bold text-black transition-colors"
              style={{ background: tenant.primary_color }}>
              Entrar
            </Link>
          )}
        </div>

        {/* Mobile toggle */}
        <button onClick={() => setOpen(o => !o)} className="md:hidden text-slate-400 hover:text-white">
          {open ? <X size={22} /> : <Menu size={22} />}
        </button>
      </div>

      {/* Mobile drawer */}
      {open && (
        <div className="md:hidden bg-slate-950 border-t border-white/5 px-4 py-4 space-y-3">
          {LINKS.map(l => (
            <NavItem key={l.label} link={l} mobile onClick={() => setOpen(false)} />
          ))}
          {user ? (
            <>
              <Link to="/minha-area" onClick={() => setOpen(false)}
                className="block text-sm font-medium text-slate-300 py-2">
                Minha Área
              </Link>
              <button onClick={() => { onLogout?.(); setOpen(false) }}
                className="block text-sm text-rose-400 py-2">
                Sair
              </button>
            </>
          ) : (
            <Link to="/login" onClick={() => setOpen(false)}
              className="block text-center px-4 py-2.5 rounded-xl text-sm font-bold text-black"
              style={{ background: tenant.primary_color }}>
              Entrar
            </Link>
          )}
        </div>
      )}
    </nav>
  )
}
