import { Link, Outlet } from "react-router-dom";
import { Panel } from "../components/ui/Panel";
import { useAuth } from "./AuthContext";

/**
 * Route gate for admin-only sections (the Users plane). Sits inside
 * ProtectedRoute, so the user is already authenticated here — this only checks
 * the admin role.
 *
 * A non-admin who navigates to an admin route sees a calm, explicit
 * access-denied panel (NOT a redirect loop and NOT a 403 toast storm). The
 * server remains the real authority: the underlying /api/users calls are
 * admin-gated server-side, so this is defense-in-depth plus correct UX.
 */
export function AdminRoute() {
  const { isAdmin } = useAuth();

  if (!isAdmin) {
    return (
      <div className="page">
        <div className="denied">
          <Panel>
            <div className="denied__body">
              <span className="denied__badge" aria-hidden="true">
                <svg
                  width="22"
                  height="22"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <rect x="3" y="11" width="18" height="11" rx="2" />
                  <path d="M7 11V7a5 5 0 0 1 10 0v4" />
                </svg>
              </span>
              <h1 className="denied__title">Admins only</h1>
              <p className="denied__msg">
                User management is restricted to administrators. Your account
                does not have admin access. If you need it, ask an administrator
                to update your role.
              </p>
              <Link to="/machines" className="btn btn--primary denied__link">
                Back to Machines
              </Link>
            </div>
          </Panel>
        </div>
      </div>
    );
  }

  return <Outlet />;
}
