import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { api } from '../api';

const navItems = [
  { path: '/', label: 'Dashboard' },
  { path: '/inventory', label: 'Inventory' },
  { path: '/customers', label: 'Customers' },
  { path: '/orders', label: 'Orders' },
];

export default function Layout({ children, onLogout }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const location = useLocation();

  async function handleLogout() {
    await api('/auth/logout', { method: 'POST' });
    onLogout?.();
  }

  return (
    <div className="layout">
      <header className="header">
        <div className="header-inner container">
          <Link to="/" className="logo">Cookie Tracker</Link>
          <button
            type="button"
            className="menu-toggle"
            onClick={() => setMenuOpen(!menuOpen)}
            aria-expanded={menuOpen}
            aria-label="Toggle menu"
          >
            <span className="menu-icon" />
          </button>
          <nav className={`nav ${menuOpen ? 'nav-open' : ''}`}>
            {navItems.map(({ path, label }) => (
              <Link
                key={path}
                to={path}
                className={location.pathname === path ? 'active' : ''}
                onClick={() => setMenuOpen(false)}
              >
                {label}
              </Link>
            ))}
            <Link
              to="/orders/new"
              className="nav-cta"
              onClick={() => setMenuOpen(false)}
            >
              New order
            </Link>
            {onLogout && (
              <button
                type="button"
                className="nav-logout secondary"
                onClick={() => { setMenuOpen(false); handleLogout(); }}
              >
                Log out
              </button>
            )}
          </nav>
        </div>
      </header>
      <main className="main">
        <div className="container">
          {children}
        </div>
      </main>
    </div>
  );
}
