// ─── Toast ────────────────────────────────────────────────────────────────────

function AdminToast() {
  const [toast, setToast] = React.useState(null);

  React.useEffect(() => {
    const handler = (e) => {
      setToast(e.detail);
      setTimeout(() => setToast(null), 2500);
    };
    window.addEventListener('admin-toast', handler);
    return () => window.removeEventListener('admin-toast', handler);
  }, []);

  if (!toast) return null;

  return (
    <div className={`admin-toast admin-toast--${toast.type}`} role="status" aria-live="polite">
      {toast.type === 'success' ? (
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
          <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.3"/>
          <path d="M4.5 7l2 2 3-3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      ) : (
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
          <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.3"/>
          <path d="M7 4.5v3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
          <circle cx="7" cy="9.5" r="0.6" fill="currentColor"/>
        </svg>
      )}
      {toast.msg}
    </div>
  );
}

// ─── Layout ───────────────────────────────────────────────────────────────────

function Layout({ activePage, onNavigate, title, newCount, role, onSignOut, userEmail, children }) {
  const [sidebarOpen, setSidebarOpen] = React.useState(false);

  const navigate = (page) => {
    onNavigate(page);
    setSidebarOpen(false); // close sidebar on navigation (mobile)
  };

  return (
    <React.Fragment>
      <Sidebar
        activePage={activePage}
        onNavigate={navigate}
        role={role}
        onSignOut={onSignOut}
        userEmail={userEmail}
        isOpen={sidebarOpen}
      />

      {/* Overlay — tapping outside closes sidebar on mobile */}
      <div
        className={'sidebar-overlay' + (sidebarOpen ? ' is-open' : '')}
        onClick={() => setSidebarOpen(false)}
        aria-hidden="true"
      />

      <div className="layout">
        <TopHeader
          title={title}
          newCount={newCount}
          onMenuToggle={() => setSidebarOpen((v) => !v)}
        />
        <main className="main">{children}</main>
      </div>

      <AdminToast />
    </React.Fragment>
  );
}
