'use client';
import { useState } from 'react';
import { usePathname } from 'next/navigation';
import Sidebar from '@/components/Sidebar';
import AuthGuard from '@/components/AuthGuard';

const titles = {
  '/':              'Dashboard',
  '/users':         'Usuarios',
  '/requirements':  'Requerimientos',
  '/plans':         'Planes de suscripción',
  '/categories':    'Categorías',
  '/subscriptions': 'Suscripciones',
  '/logs':          'Logs de administración',
};

export default function DashboardLayout({ children }) {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const pathname = usePathname();
  const title    = titles[pathname] || 'Admin';

  return (
    <AuthGuard>
      <div className="flex h-screen bg-[#f0f4f8] overflow-hidden">

        {/* Mobile overlay */}
        {sidebarOpen && (
          <div className="fixed inset-0 bg-black/40 z-20 lg:hidden" onClick={() => setSidebarOpen(false)} />
        )}

        {/* Sidebar */}
        <div className={`fixed lg:static inset-y-0 left-0 z-30 transition-transform duration-300 lg:translate-x-0 ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}>
          <Sidebar onClose={() => setSidebarOpen(false)} />
        </div>

        {/* Right column */}
        <div className="flex-1 flex flex-col min-w-0 overflow-hidden">

          {/* Single topbar */}
          <header className="bg-white border-b border-gray-100 px-5 py-3 flex items-center justify-between flex-shrink-0 shadow-sm">
            <div className="flex items-center gap-3">
              <button onClick={() => setSidebarOpen(o => !o)}
                className="lg:hidden p-2 rounded-xl hover:bg-gray-100 text-gray-500 transition">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16"/>
                </svg>
              </button>
              <h1 className="text-lg font-bold text-gray-800">{title}</h1>
            </div>
            <UserChip />
          </header>

          {/* Page content */}
          <main className="flex-1 overflow-y-auto p-4 lg:p-6">
            {children}
          </main>
        </div>
      </div>
    </AuthGuard>
  );
}

function UserChip() {
  const [user, setUser] = useState(null);
  if (typeof window !== 'undefined' && !user) {
    const u = localStorage.getItem('admin_user');
    if (u) setUser(JSON.parse(u));
  }
  return (
    <div className="flex items-center gap-3">
      <div className="text-right hidden sm:block">
        <p className="text-sm font-semibold text-gray-800 leading-tight">{user?.name || 'Admin'}</p>
        <p className="text-xs text-gray-400">{user?.email || 'admin@albaratai.com.mx'}</p>
      </div>
      <div className="w-9 h-9 rounded-xl bg-primary flex items-center justify-center text-white font-bold text-sm">
        {user?.name?.[0]?.toUpperCase() || 'A'}
      </div>
    </div>
  );
}
