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

export function UserLayout() {
  const { signOut, isAdmin, uid } = useAuth();
  const navigate = useNavigate();

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

  return (
    <div className="shell">
      <header className="topbar">
        <Link to="/app" className="brand">
          Gateway
        </Link>
        <nav className="nav">
          <Link to="/app">首頁</Link>
          <Link to="/app/profile">個人資料</Link>
          <Link to="/app/security">安全設定</Link>
          {isAdmin && <Link to="/admin">管理後台</Link>}
        </nav>
        <div className="topbar-right">
          <span className="uid">{uid}</span>
          <button type="button" className="btn-ghost" onClick={handleLogout}>
            登出
          </button>
        </div>
      </header>
      <main className="page">
        <Outlet />
      </main>
    </div>
  );
}
