import { Link, NavLink, useNavigate } from "react-router-dom";
import { useAuth } from "../auth";
import type { ReactNode } from "react";

function navClass({ isActive }: { isActive: boolean }) {
  return `px-3 py-2 rounded-md text-sm font-medium ${
    isActive ? "bg-brand-50 text-brand-700" : "text-gray-600 hover:bg-gray-100"
  }`;
}

export default function Layout({ children }: { children: ReactNode }) {
  const { user, logout } = useAuth();
  const navigate = useNavigate();

  return (
    <div className="min-h-screen text-gray-900">
      <header className="border-b border-gray-200 bg-white sticky top-0 z-10">
        <div className="mx-auto max-w-5xl px-4 flex items-center justify-between h-14">
          <Link to="/" className="flex items-center font-bold tracking-tight text-brand-700">
            PawTrace
          </Link>
          <nav className="flex items-center gap-1">
            {user ? (
              <>
                {user.role === "admin" ? (
                  <NavLink to="/admin" className={navClass}>
                    Admin
                  </NavLink>
                ) : (
                  <>
                    <NavLink to="/dogs" className={navClass}>
                      My Dogs
                    </NavLink>
                    <NavLink to="/cases" className={navClass}>
                      My Cases
                    </NavLink>
                  </>
                )}
                <button
                  className="btn-secondary ml-2"
                  onClick={() => {
                    logout();
                    navigate("/");
                  }}
                >
                  Log out
                </button>
              </>
            ) : (
              <NavLink to="/login" className="btn-primary ml-2">
                Log in
              </NavLink>
            )}
          </nav>
        </div>
      </header>
      <main className="mx-auto max-w-5xl px-4 py-6">{children}</main>
      <footer className="mx-auto max-w-5xl px-4 py-8 text-center text-xs text-gray-400">
        PawTrace · Photo matches are suggestions requiring human confirmation. Contact is mediated
        through the platform — addresses are never shared.
      </footer>
    </div>
  );
}
