"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import Script from "next/script";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import { useRooSports, type SessionUser } from "@/components/app-provider";
import { RooSportsLogo } from "@/components/roosports-logo";
import { getSavedLoginEmail, saveLoginEmail, clearSavedLoginEmail } from "@/lib/remember-login";

const SignUpCardMedia = dynamic(
  () => import("../../components/LottieBasketballScene").then((m) => m.SignUpCardMedia),
  { ssr: false }
);

// Cloudflare Turnstile browser API
declare global {
  interface Window {
    turnstile?: {
      render: (
        container: HTMLElement,
        options: {
          sitekey: string;
          theme?: string;
          callback?: (token: string) => void;
          "expired-callback"?: () => void;
          "error-callback"?: () => void;
        }
      ) => string;
      remove: (widgetId: string) => void;
    };
  }
}

type AuthMode = "login" | "signup";
type AccountRole = "parent" | "player" | "coach";

const nameRegex = /^[A-Za-z\s'-]+$/;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const passwordChecks = [
  { label: "At least 8 characters", test: (value: string) => value.length >= 8 },
  { label: "At least 1 uppercase letter", test: (value: string) => /[A-Z]/.test(value) },
  { label: "At least 1 number", test: (value: string) => /\d/.test(value) },
  {
    label: "At least 1 special character (!@#$%^&*)",
    test: (value: string) => /[!@#$%^&*]/.test(value),
  },
];

const roles: { id: AccountRole; label: string; icon: string }[] = [
  { id: "parent", label: "Parent", icon: "family_restroom" },
  { id: "player", label: "Adult player", icon: "person" },
  { id: "coach", label: "Coach", icon: "sports" },
];

export default function LoginPage() {
  const router = useRouter();
  const { setAuthenticatedUser } = useRooSports();

  // Mobile Menu State
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

  // Nav Scroll Blur
  const [isScrolled, setIsScrolled] = useState(false);

  // Auth State
  const [mode, setMode] = useState<AuthMode>("login");
  const [role, setRole] = useState<AccountRole>("parent");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [statusMessage, setStatusMessage] = useState("");
  const [statusIsError, setStatusIsError] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [firstNameError, setFirstNameError] = useState("");
  const [lastNameError, setLastNameError] = useState("");
  const [emailError, setEmailError] = useState("");
  const [showTerms, setShowTerms] = useState(false);
  
  // Cloudflare Turnstile CAPTCHA state
  const [captchaCompleted, setCaptchaCompleted] = useState(false);
  const [captchaToken, setCaptchaToken] = useState("");
  const turnstileRef = useRef<HTMLDivElement>(null);
  const widgetIdRef = useRef<string | null>(null);
  const captchaGateActive = process.env.NODE_ENV === "production";

  const loginIsValid =
    emailRegex.test(email.trim()) &&
    password.length >= 8 &&
    (!captchaGateActive || captchaCompleted);
  const signupIsValid =
    firstName.trim().length > 0 &&
    lastName.trim().length > 0 &&
    nameRegex.test(firstName.trim()) &&
    nameRegex.test(lastName.trim()) &&
    emailRegex.test(email.trim()) &&
    passwordChecks.every((check) => check.test(password)) &&
    acceptedTerms &&
    (!captchaGateActive || captchaCompleted);

  // Render Cloudflare Turnstile CAPTCHA
  const renderTurnstile = () => {
    if (!window.turnstile || !turnstileRef.current || widgetIdRef.current) {
      return;
    }

    const siteKey =
      process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY || "1x00000000000000000000AA";

    widgetIdRef.current = window.turnstile.render(turnstileRef.current, {
      sitekey: siteKey,
      theme: "light",

      // CAPTCHA passed
      callback: (token) => {
        setCaptchaToken(token);
        setCaptchaCompleted(true);
      },

      // CAPTCHA expired or failed
      "expired-callback": () => {
        setCaptchaToken("");
        setCaptchaCompleted(false);
      },
      "error-callback": () => {
        setCaptchaToken("");
        setCaptchaCompleted(false);
      },
    });
  };

  useEffect(() => {
    const savedEmail = getSavedLoginEmail();
    if (savedEmail) {
      queueMicrotask(() => {
        setEmail(savedEmail);
        setRememberMe(true);
      });
      return;
    }

    const queryEmail = new URLSearchParams(window.location.search).get("email")?.trim();
    if (queryEmail) {
      queueMicrotask(() => {
        setEmail(queryEmail);
      });
    }
  }, []);

  useEffect(() => {
    const handleScroll = () => {
      if (window.scrollY > 50) {
        setIsScrolled(true);
      } else {
        setIsScrolled(false);
      }
    };
    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  useEffect(() => {
    renderTurnstile();

    const pollId = window.setInterval(() => {
      renderTurnstile();
      if (widgetIdRef.current) window.clearInterval(pollId);
    }, 250);
    const stopPolling = window.setTimeout(() => window.clearInterval(pollId), 10000);

    return () => {
      window.clearInterval(pollId);
      window.clearTimeout(stopPolling);
      if (widgetIdRef.current && window.turnstile) {
        window.turnstile.remove(widgetIdRef.current);
        widgetIdRef.current = null;
      }
    };
  }, []);

  const switchMode = (targetMode: AuthMode) => {
    setMode(targetMode);
    setStatusMessage("");
    setStatusIsError(false);
  };

  const forgotPasswordHref = email.trim()
    ? `/forgot-password?email=${encodeURIComponent(email.trim())}`
    : "/forgot-password";

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsSubmitting(true);
    setStatusIsError(false);
    setStatusMessage(mode === "login" ? "Checking your account..." : "Creating your account...");

    try {
      const response = await fetch(`/api/auth/${mode === "login" ? "login" : "register"}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          email,
          password,
          rememberMe,
          captchaToken,
          ...(mode === "signup" ? { firstName, lastName, role } : {}),
        }),
      });
      const text = await response.text();
      let payload: {
        user?: SessionUser;
        error?: string;
        code?: string;
        email?: string;
        requiresVerification?: boolean;
        previewUrl?: string;
        previewCode?: string;
      } = {};
      try {
        if (text && text.trim()) {
          payload = JSON.parse(text) as typeof payload;
        }
      } catch {
        // Non-JSON response (e.g. server error or HTML)
      }
      if (payload.code === "email_unverified" || payload.requiresVerification) {
        const targetEmail = payload.email || email.trim().toLowerCase();
        const params = new URLSearchParams({ email: targetEmail });
        if (payload.previewCode) params.set("previewCode", payload.previewCode);
        router.push(`/verify-email?${params.toString()}`);
        return;
      }
      if (!response.ok || !payload.user) {
        throw new Error(payload.error || "Authentication failed. Please try again.");
      }

      if (mode === "signup") {
        if (payload.requiresVerification !== false && payload.user.accountStatus === "pending") {
          const params = new URLSearchParams({ email: payload.user.email });
          if (payload.previewCode) params.set("previewCode", payload.previewCode);
          router.push(`/verify-email?${params.toString()}`);
          return;
        }
      }

      if (mode === "login") {
        if (rememberMe) {
          saveLoginEmail(email);
        } else {
          clearSavedLoginEmail();
        }
      }

      setAuthenticatedUser(payload.user, mode === "signup");
      setStatusMessage("Success. Redirecting to RooSports...");
      if (payload.user.mustChangePassword) {
        router.push("/change-password");
      } else if (payload.user.role === "admin") {
        if (mode === "login") {
          sessionStorage.setItem("roosports-admin-signin-toast", "true"); //pop up when logged in as admin
        }
        router.push("/admin"); 
      } else if (mode === "signup" && payload.user.role === "parent") {
        router.push("/onboarding/family");
      } else if (mode === "signup" && payload.user.role === "coach") {
        router.push("/coach/verification");
      } else {
        router.push("/dashboard");
      }
    } catch (error) {
      setStatusIsError(true);
      setStatusMessage(error instanceof Error ? error.message : "Authentication failed.");
      setIsSubmitting(false);
    }
  };

  return (
    <div
      suppressHydrationWarning
      className="bg-transparent text-[#0B0F12] min-h-screen antialiased selection:bg-[#0D131A] selection:text-white font-sans relative flex flex-col justify-between"
    >
      {/* TopNavBar */}
      <nav
        id="topNav"
        suppressHydrationWarning
        className={`fixed top-0 left-0 w-full z-50 flex justify-between items-center px-6 md:px-12 lg:px-16 transition-all duration-300 ${
          isScrolled
            ? "bg-white/80 backdrop-blur-md py-3 shadow-xs"
            : "bg-transparent py-6"
        }`}
      >
        <Link
          href="/"
          aria-label="RooSports home"
          className="text-4xl text-[#0B0F12] z-50 relative group md:text-5xl"
        >
          <RooSportsLogo />
          <span className="absolute -bottom-2 left-0 w-0 h-0.5 bg-[#0B0F12] transition-all duration-300 group-hover:w-full"></span>
        </Link>

        {/* Desktop Nav Links */}
        <div className="hidden md:flex items-center space-x-10 lg:space-x-12 z-50">
          <Link className="font-label-caps text-[#546067] hover:text-[#0B0F12] transition-colors py-1 border-b-2 border-transparent" href="/">
            Home
          </Link>
          <Link className="font-label-caps text-[#546067] hover:text-[#0B0F12] transition-colors py-1 border-b-2 border-transparent" href="/#about">
            About us
          </Link>
          <Link className="font-label-caps text-[#546067] hover:text-[#0B0F12] transition-colors py-1 border-b-2 border-transparent" href="/#faqs">
            FAQs
          </Link>
          <Link
            className="font-label-caps transition-all duration-300 text-[#0B0F12] font-bold px-5 py-2 rounded-full border-2 border-[#0B0F12] bg-white/60 shadow-xs"
            href="/login"
          >
            Login
          </Link>
          <button
            onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
            className="w-10 h-10 rounded-full border border-[#0B0F12]/10 flex items-center justify-center hover:bg-[#0B0F12] hover:text-white transition-all duration-300 cursor-pointer"
          >
            <span className="material-symbols-outlined text-xl">menu</span>
          </button>
        </div>

        {/* Mobile Nav Toggle */}
        <button
          onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
          className="md:hidden w-10 h-10 rounded-full border border-[#0B0F12]/10 flex items-center justify-center hover:bg-[#0B0F12] hover:text-white transition-all duration-300 z-50 cursor-pointer"
          id="mobileMenuBtn"
        >
          <span className="material-symbols-outlined text-xl">
            {isMobileMenuOpen ? "close" : "menu"}
          </span>
        </button>
      </nav>

      {/* Mobile Menu Overlay */}
      {isMobileMenuOpen && (
        <div
          id="mobileMenu"
          className="fixed inset-0 bg-white/95 backdrop-blur-md z-40 flex flex-col items-center justify-center space-y-8 pt-20"
        >
          <Link onClick={() => setIsMobileMenuOpen(false)} className="text-3xl font-bold text-[#0B0F12]/70 hover:opacity-100" href="/">
            Home
          </Link>
          <Link onClick={() => setIsMobileMenuOpen(false)} className="text-3xl font-bold text-[#0B0F12]/70 hover:opacity-100" href="/#about">
            About us
          </Link>
          <Link onClick={() => setIsMobileMenuOpen(false)} className="text-3xl font-bold text-[#0B0F12]/70 hover:opacity-100" href="/#faqs">
            FAQs
          </Link>
          <Link onClick={() => setIsMobileMenuOpen(false)} className="text-3xl font-bold text-[#0B0F12] underline" href="/login">
            Login
          </Link>
        </div>
      )}

      {/* Main Split-Screen Layout (Auth Form Left | Sign Up Lottie Animation Right) */}
      <main className="relative z-10 w-full max-w-7xl mx-auto px-6 md:px-12 lg:px-16 pt-28 md:pt-36 pb-20 md:pb-24 my-auto bg-transparent flex items-center min-h-[75vh]">
        <div className="w-full grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-center bg-transparent">
          
          {/* Left Column: Team Authentication Form */}
          <div className="w-full z-10">
            <div className="glass-panel bg-white/80 backdrop-blur-xl border border-white/60 shadow-xl rounded-3xl p-8 md:p-10 relative overflow-hidden">
              
              {/* Mode Toggle Switch with Active Underline Indicator */}
              <div className="mb-6 grid grid-cols-2 gap-1 rounded-2xl bg-[#e6ecf0] p-1 text-xs font-bold shadow-inner relative">
                <button
                  type="button"
                  onClick={() => switchMode("login")}
                  className={`rounded-xl py-2.5 transition-all cursor-pointer relative ${
                    mode === "login"
                      ? "bg-[#0D131A] text-white shadow-md font-extrabold border-b-2 border-white/80"
                      : "text-[#546067] hover:text-[#0B0F12]"
                  }`}
                >
                  Log in
                </button>
                <button
                  type="button"
                  onClick={() => switchMode("signup")}
                  className={`rounded-xl py-2.5 transition-all cursor-pointer relative ${
                    mode === "signup"
                      ? "bg-[#0D131A] text-white shadow-md font-extrabold border-b-2 border-white/80"
                      : "text-[#546067] hover:text-[#0B0F12]"
                  }`}
                >
                  Create account
                </button>
              </div>

              <div className="mb-6">
                <h1 className="font-headline-lg-mobile text-3xl font-extrabold text-[#0B0F12] mb-1">
                  {mode === "login" ? "Welcome back." : "Create account."}
                </h1>
                <p className="text-sm text-[#546067]">
                  {mode === "login"
                    ? "Sign in to manage bookings and family profiles."
                    : "Join the community and start your sports journey."}
                </p>
              </div>

              <form onSubmit={handleSubmit} className="space-y-5">
                
                {/* Signup Role Selection */}
                {mode === "signup" && (
                  <div>
                    <label className="block font-label-caps text-xs text-[#546067] mb-2">I AM A...</label>
                    <div className="grid grid-cols-3 gap-2">
                      {roles.map((item) => (
                        <button
                          key={item.id}
                          type="button"
                          onClick={() => setRole(item.id)}
                          aria-pressed={role === item.id}
                          className={`flex flex-col items-center justify-center gap-1.5 rounded-xl border p-3 text-xs font-bold transition-all cursor-pointer ${
                            role === item.id
                              ? "border-[#0B0F12] bg-[#0D131A] text-white shadow-md border-b-2 border-white"
                              : "border-[#0B0F12]/15 bg-white/50 text-[#546067] hover:border-[#0B0F12]"
                          }`}
                        >
                          <span className="material-symbols-outlined text-xl">{item.icon}</span>
                          {item.label}
                        </button>
                      ))}
                    </div>
                  </div>
                )}

                {mode === "signup" && (
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label htmlFor="firstName" className="block font-label-caps text-xs text-[#546067] mb-1">
                        FIRST NAME
                      </label>
                      <input
                        id="firstName"
                        type="text"
                        autoComplete="given-name"
                        required
                        maxLength={100}
                        value={firstName}
                        onChange={(event) =>  {
                          const value = event.target.value;
                          setFirstName(value);
                        setFirstNameError(
                          value.trim().length > 0 && !nameRegex.test(value.trim()) ? "Invalid name" : ""
                        );
                      }}
                        className="w-full bg-transparent border-b border-[#0B0F12]/20 focus:border-[#0B0F12] py-2 text-base text-[#0B0F12] focus:outline-hidden"
                      />
                      {firstNameError && (
                        <p className="mt-1 text-xs font-semibold text-red-600">{firstNameError}</p>
                      )}
                    </div>
                    <div>
                      <label htmlFor="lastName" className="block font-label-caps text-xs text-[#546067] mb-1">
                        LAST NAME
                      </label>
                      <input
                        id="lastName"
                        type="text"
                        autoComplete="family-name"
                        required
                        maxLength={100}
                        value={lastName}
                        onChange={(event) => {
                          const value = event.target.value;
                          setLastName(value);
                          setLastNameError(
                            value.trim().length > 0 && !nameRegex.test(value.trim()) ? "Invalid name" : ""
                          );
                        }}
                        className="w-full bg-transparent border-b border-[#0B0F12]/20 focus:border-[#0B0F12] py-2 text-base text-[#0B0F12] focus:outline-hidden"
                      />
                      {lastNameError && (
                        <p className="mt-1 text-xs font-semibold text-red-600">{lastNameError}</p>
                      )}
                    </div>
                  </div>
              
                )}

                {/* Email Field */}
                <div>
                  <label htmlFor="email" className="block font-label-caps text-xs text-[#546067] mb-1">
                    EMAIL ADDRESS
                  </label>
                  <div className="relative">
                    <input
                      id="email"
                      type="email"
                      autoComplete="email"
                      required
                      value={email}
                      onChange={(e) => {
                        const value = e.target.value;
                        setEmail(value);
                        setEmailError(
                          value.trim().length > 0 &&!emailRegex.test(value.trim()) ? "Invalid email format" : ""
                        );
                      }}  
                      placeholder="your@email.com"
                      className="w-full bg-transparent border-b border-[#0B0F12]/20 focus:border-[#0B0F12] py-2 text-base text-[#0B0F12] focus:outline-hidden"
                    />
                    </div>
                    {emailError && (
                      <p className="mt-1 text-xs font-semibold text-red-600">{emailError}</p>
                    )}
                </div>

                {/* Password Field */}
                <div>
                  <div className="flex items-center justify-between mb-1">
                    <label htmlFor="password" className="block font-label-caps text-xs text-[#546067]">
                      {mode === "login" ? "PASSWORD" : "CREATE PASSWORD"}
                    </label>
                    {mode === "login" && (
                      <Link href={forgotPasswordHref} className="font-label-caps text-xs text-[#546067] underline hover:text-[#0B0F12]">
                        FORGOT?
                      </Link>
                    )}
                  </div>
                  <div className="relative">
                    <input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      autoComplete={mode === "login" ? "current-password" : "new-password"}
                      required
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      placeholder="••••••••"
                      className="w-full bg-transparent border-b border-[#0B0F12]/20 focus:border-[#0B0F12] py-2 pr-10 text-base text-[#0B0F12] focus:outline-hidden"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-0 top-1/2 -translate-y-1/2 text-[#546067] hover:text-[#0B0F12] cursor-pointer"
                    >
                      <span className="material-symbols-outlined text-lg">
                        {showPassword ? "visibility" : "visibility_off"}
                      </span>
                    </button>
                  </div>
                </div>

                {/* Password Requirement Checklist (Signup Mode) */}
                {mode === "signup" && (
                  <div className="rounded-xl border border-[#0B0F12]/10 bg-white/40 p-3.5 space-y-2">
                    <p className="font-label-caps text-[10px] text-[#546067]">FIT3048 PASSWORD REQUIREMENTS:</p>
                    <ul className="space-y-1.5">
                      {passwordChecks.map((check) => {
                        const isMet = check.test(password);
                        return (
                          <li key={check.label} className={`flex items-center space-x-2 text-xs ${isMet ? "text-emerald-700 font-semibold" : "text-red-600 font-semibold"}`}>
                            <span className="material-symbols-outlined text-sm">
                              {isMet ? "check_circle" : "cancel"}
                            </span>
                            <span>{check.label}</span>
                          </li>
                        );
                      })}
                    </ul>
                  </div>
                )}

                {/* Terms / Remember Me Checkbox */}
                {mode === "login" ? (
                  <label className="flex items-center space-x-2 cursor-pointer pt-1">
                    <input
                      type="checkbox"
                      checked={rememberMe}
                      onChange={(e) => {
                        const checked = e.target.checked;
                        setRememberMe(checked);
                        if (!checked) clearSavedLoginEmail();
                      }}
                      className="h-4 w-4 text-[#0D131A] rounded-xs"
                    />
                    <span className="font-label-caps text-xs text-[#546067]">REMEMBER ME</span>
                  </label>
                ) : (
                  <label className="flex items-start space-x-2 cursor-pointer pt-1">
                    <input
                      type="checkbox"
                      checked={acceptedTerms}
                      onChange={(e) => setAcceptedTerms(e.target.checked)}
                      className="h-4 w-4 text-[#0D131A] rounded-xs mt-0.5"
                    />
                    <span className="text-xs text-[#546067] leading-tight">
                      I agree to the{" "}
                      <button type="button" onClick={() => setShowTerms(true)} className="underline font-bold text-[#0B0F12] cursor-pointer">
                        Terms of Service
                      </button>{" "}
                      and <Link href="/about" className="underline font-bold text-[#0B0F12]">Privacy Policy</Link>.
                    </span>
                  </label>
                )}

                {/* Cloudflare Turnstile CAPTCHA */}
                <Script
                  src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
                  strategy="afterInteractive"
                  onReady={renderTurnstile}
                />

                <div className="flex justify-center py-2">
                  <div ref={turnstileRef} />
                </div>

                {/* Status Message */}
                {statusMessage && (
                  <div className={`flex items-center space-x-2 rounded-xl p-3 text-xs font-medium ${statusIsError ? "bg-[#f8e2df] text-[#9a4338]" : "bg-[#dfecef]/70 text-[#102630]"}`} role="status">
                    <span className={`material-symbols-outlined text-base ${statusIsError ? "" : "animate-spin"}`}>
                      {statusIsError ? "error" : "sync"}
                    </span>
                    <span>{statusMessage}</span>
                  </div>
                )}

                {/* Submit Button */}
                <button
                  type="submit"
                  disabled={isSubmitting || (mode === "login" ? !loginIsValid : !signupIsValid)}
                  className="w-full py-4 mt-4 font-label-caps bg-[#0D131A] hover:bg-[#0B0F12] text-white rounded-sm transition-all duration-300 flex justify-center items-center space-x-2 cursor-pointer shadow-md disabled:bg-[#546067]/40 disabled:cursor-not-allowed disabled:shadow-none"
                >
                  <span>{isSubmitting ? "PLEASE WAIT" : mode === "login" ? "LOG IN" : "CREATE ACCOUNT"}</span>
                  <span className="material-symbols-outlined text-sm">arrow_forward</span>
                </button>
              </form>

              {/* Switch Mode Footer Text */}
              <p className="mt-6 text-center text-xs text-[#546067]">
                {mode === "login" ? "New to RooSports?" : "Already have an account?"}{" "}
                <button
                  type="button"
                  onClick={() => switchMode(mode === "login" ? "signup" : "login")}
                  className="font-bold text-[#0B0F12] underline hover:opacity-80 cursor-pointer"
                >
                  {mode === "login" ? "Create an account" : "Log in"}
                </button>
              </p>
            </div>
          </div>

          {/* Right Column: Hardware-Accelerated Sign Up Lottie Animation (Blended 100% into background) */}
          <div className="w-full h-auto min-h-[350px] md:min-h-[420px] bg-transparent border-0 shadow-none flex items-center justify-center overflow-visible pointer-events-none">
            <SignUpCardMedia speed={0.85} />
          </div>
        </div>
      </main>

      {/* Footer Component */}
      <footer className="bg-transparent border-t border-[#dfe3e5] w-full px-6 md:px-12 lg:px-16 py-16 flex flex-col md:flex-row justify-between items-end relative z-20">
        <div className="mb-8 md:mb-0 w-full md:w-auto flex flex-col items-start">
          <span className="font-label-caps font-bold tracking-widest text-[#0B0F12] mb-4 block">
            ROOSPORTS®
          </span>
          <p className="text-[#546067] font-label-caps">
            © 2026 ROOSPORTS® ELITE PERFORMANCE. ALL RIGHTS RESERVED.
          </p>
        </div>
        <div className="flex flex-wrap gap-x-8 gap-y-4 w-full md:w-auto justify-start md:justify-end">
          <Link className="text-[#546067] font-label-caps hover:text-[#0B0F12] underline transition-all font-bold text-[#0B0F12]" href="/login">
            Login
          </Link>
        </div>
      </footer>
      {/* Terms and Conditions Popup */}
      {showTerms && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-[#0B0F12]/50 backdrop-blur-sm" onClick={() => setShowTerms(false)} />
          <div className="relative w-full max-w-2xl max-h-[80vh] bg-white rounded-2xl shadow-xl flex flex-col overflow-hidden">
            <div className="flex items-center justify-between px-6 py-4 border-b border-[#0B0F12]/10">
              <h2 className="text-lg font-extrabold text-[#0B0F12]">Terms and Conditions</h2>
              <button type="button" onClick={() => setShowTerms(false)} className="cursor-pointer">
                <span className="material-symbols-outlined">close</span>
              </button>
            </div>
            <div className="px-6 py-4 overflow-y-auto text-sm text-[#0B0F12]/90 leading-relaxed space-y-4">
              <p className="text-xs text-[#546067]">Version 1.0 — Last updated [insert date]</p>
              <p><strong>1. Acceptance.</strong> By creating an account or using the rooSports platform, you agree to be bound by these Terms.</p>
              <p><strong>2. Eligibility and Accounts.</strong> You must be 18 or older to create a parent/guardian or adult player account. Parents may create linked child profiles and confirm they are the child&apos;s parent or legal guardian.</p>
              <p><strong>3. Children&apos;s Information.</strong> Children are identified by a parent-provided nickname only; full names are not displayed to other users. Volunteer coaches must hold a valid Working With Children Check (WWCC), verified by rooSports administrators, before accessing any player information.</p>
              <p><strong>4. Bookings and Payment.</strong> Fees are processed securely through our payment provider. A GST-compliant invoice is issued by email on successful payment.</p>
              <p><strong>5. Rescheduling and Refunds.</strong> If you can&apos;t attend a booked event, you may rebook into another available session within 60 days of your original booking at no extra charge, subject to availability. Fees are otherwise non-refundable. This does not limit any right you have under the Australian Consumer Law.</p>
              <p><strong>6. Liability.</strong> Participation in sporting activities carries an inherent risk of injury. To the maximum extent permitted by law, rooSports is not liable for injury, loss or damage arising from participation, except where liability cannot be excluded under the Australian Consumer Law.</p>
              <p><strong>7. Contact.</strong> Questions about these Terms? Email us at [insert contact email].</p>
            </div>
            <div className="px-6 py-4 border-t border-[#0B0F12]/10 flex justify-end">
              <button
                type="button"
                onClick={() => setShowTerms(false)}
                className="font-label-caps px-5 py-2.5 bg-[#0D131A] hover:bg-[#0B0F12] text-white rounded-sm cursor-pointer"
              >
                CLOSE
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
