'use client';

import React, { useEffect } from 'react';
import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
import { Lock, LogIn, ShieldCheck } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';

export default function UserLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const { user, isLoading } = useAuth();

  useEffect(() => {
    if (!isLoading && !user) {
      router.push(`/login?redirect=${encodeURIComponent(pathname)}`);
    }
  }, [user, isLoading, router, pathname]);

  if (isLoading) {
    return (
      <div className="min-h-[80vh] flex flex-col items-center justify-center space-y-3">
        <div className="w-10 h-10 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin"></div>
        <p className="text-xs text-gray-500 font-bold">Loading Account Dashboard...</p>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-[85vh] py-16 px-4 flex items-center justify-center bg-gray-50/50">
        <div className="max-w-md w-full bg-white rounded-3xl p-8 sm:p-10 shadow-2xl border border-gray-100 text-center space-y-5">
          <div className="w-16 h-16 rounded-3xl bg-indigo-50 text-indigo-600 flex items-center justify-center mx-auto shadow-md">
            <Lock className="w-8 h-8" />
          </div>

          <div className="space-y-2">
            <h1 className="text-2xl font-black text-gray-900 leading-tight">
              Sign In Required
            </h1>
            <p className="text-xs text-gray-600 leading-relaxed">
              Please log in to your HostNeko account to manage your purchased modules, domain licenses, and active downloads.
            </p>
          </div>

          <div className="pt-2 space-y-3">
            <Link
              href={`/login?redirect=${encodeURIComponent(pathname)}`}
              className="w-full py-3.5 px-6 rounded-2xl bg-indigo-600 hover:bg-indigo-700 text-white font-extrabold text-xs sm:text-sm flex items-center justify-center gap-2 shadow-lg shadow-indigo-600/20 transition active:scale-95 text-center"
            >
              <LogIn className="w-4 h-4" />
              <span>Sign In to Account</span>
            </Link>

            <Link
              href={`/register?redirect=${encodeURIComponent(pathname)}`}
              className="block w-full py-3 px-6 rounded-2xl bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold text-xs transition text-center"
            >
              Create New Account
            </Link>
          </div>

          <div className="pt-4 border-t border-gray-100 flex items-center justify-center gap-2 text-[11px] text-gray-400">
            <ShieldCheck className="w-3.5 h-3.5 text-emerald-500" />
            <span>256-Bit SSL Encrypted Customer Portal</span>
          </div>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
