import { Link, Outlet, useNavigate } from 'react-router-dom';
import * as authApi from '../api/auth';
import { useAuth } from '../context/AuthContext';

export function AdminLayout() {
  const { signOut } = useAuth();
  const navigate = useNavigate();

  const handleLogout = async () => {
    try {
      await authApi.logout();
    } catch {
      /* ignore */
    }
    signOut();
    navigate('/login');
  };

  return (
    <div className="shell admin-shell">
      <aside className="admin-sidebar">
        <div className="brand">管理後台</div>
        <nav className="admin-nav">
          <Link to="/admin">總覽</Link>
          <Link to="/admin/roles">角色管理</Link>
          <Link to="/admin/role-permissions">角色權限</Link>
          <Link to="/admin/users">使用者角色</Link>
        </nav>
        <Link to="/app" className="back-link">
          ← 回使用者前台
        </Link>
        <button type="button" className="btn-ghost" onClick={handleLogout}>
          登出
        </button>
      </aside>
      <main className="page admin-page">
        <Outlet />
      </main>
    </div>
  );
}
