'use client'

import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { UserProvider, useUser } from '@/lib/user-context'
import styles from './layout.module.css'

const NAV_BASE = [
  { href: '/dashboard',     label: 'Dashboard',    ic: '⊞' },
  { href: '/leads',         label: 'Leads',         ic: '≡' },
  { href: '/prospect',      label: 'Prospect',      ic: '◈' },
  { href: '/contatos',      label: 'Contatos',      ic: '◉' },
  { href: '/tarefas',       label: 'Tarefas',       ic: '◷' },
  { href: '/pipeline',      label: 'Pipeline',      ic: '⊟' },
  { href: '/configuracoes', label: 'Configurações', ic: '⌀' },
]
const NAV_GESTOR = [
  { href: '/usuarios',      label: 'Usuários',      ic: '○' },
]

function AppShell({ children }: { children: React.ReactNode }) {
  const path   = usePathname()
  const router = useRouter()
  const user   = useUser()

  const nav = user?.role === 'gestor' ? [...NAV_BASE, ...NAV_GESTOR] : NAV_BASE

  async function logout() {
    await fetch('/api/auth/logout', { method: 'POST' })
    router.replace('/login')
  }

  const initials = user
    ? user.nome.split(' ').slice(0, 2).map(w => w[0]).join('').toUpperCase()
    : '…'

  return (
    <div className={styles.shell}>
      <aside className={styles.sidebar}>
        <div className={styles.brand}>
          <span className={styles.dot} />
          <span className={styles.brandLabel}>RAVAPI · CRM</span>
        </div>

        <nav className={styles.nav}>
          {nav.map(({ href, label, ic }) => (
            <Link
              key={href}
              href={href}
              className={`${styles.navItem} ${path.startsWith(href) ? styles.active : ''}`}
            >
              <span className={`${styles.ic} ${path.startsWith(href) ? styles.icActive : ''}`}>{ic}</span>
              {label}
            </Link>
          ))}
        </nav>

        <div className={styles.spacer} />

        <div className={styles.userChip}>
          <div className={styles.avatar}>{initials}</div>
          <div className={styles.who}>
            <span className={styles.name}>{user?.nome.split(' ')[0] ?? '…'}</span>
            <span className={styles.role}>{user?.role === 'gestor' ? 'Gestor' : 'Vendedor'}</span>
          </div>
          <button className={styles.logoutLink} title="Sair" onClick={logout}>↩</button>
        </div>
      </aside>

      <main className={styles.main}>{children}</main>
    </div>
  )
}

export default function AppLayout({ children }: { children: React.ReactNode }) {
  return (
    <UserProvider>
      <AppShell>{children}</AppShell>
    </UserProvider>
  )
}
