please make it wokring and attach everything like porper flow after the user signs in or registers the poerpr must be saved like userid  toek nand email id it should go to  the verify-user route and it should check if user is verified by pinging thtserver continuoslu for the user and then move forward to the home page
"""
'use client'

import { useState } from 'react'
import { Eye, EyeOff, Mail, User, Lock, AlertCircle, CheckCircle } from 'lucide-react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { useToast } from "@/hooks/use-toast"
import { authService } from '../services/auth.service' // Import authService

interface FormData {
  username: string
  email: string
  password: string
  identifier: string
}

export default function AuthSystem() {
  const [activeTab, setActiveTab] = useState<'signin' | 'signup'>('signin')
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string>('')
  const [success, setSuccess] = useState<string>('')
  const { toast } = useToast()

  const [formData, setFormData] = useState<FormData>({
    username: '',
    email: '',
    password: '',
    identifier: '',
  })

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({ ...prev, [name]: value }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)
    setError('')
    setSuccess('')

    try {
      if (activeTab === 'signup') {
        // Client-side Validation
        if (formData.username.trim().length < 3 || formData.username.trim().length > 30) {
          setError('Username must be between 3 and 30 characters.')
          return
        }
        if (!/\S+@\S+\.\S+/.test(formData.email)) {
          setError('Please enter a valid email address.')
          return
        }
        if (formData.password.length < 8) {
          setError('Password must be at least 8 characters long.')
          return
        }

        // Signup via authService
        const data = await authService.signup({
          username: formData.username.trim(),
          email: formData.email.trim(),
          password: formData.password,
        })

        // Assuming the response contains a token
        localStorage.setItem('token', data.token)
        setSuccess('Registration successful. Please check your email to verify your account.')
        // Optionally, you might want to switch to sign-in tab or redirect
      } else {
        // Sign In Validation
        if (formData.identifier.trim().length < 3) {
          setError('Identifier must be at least 3 characters long.')
          return
        }
        if (formData.password.length < 8) {
          setError('Password must be at least 8 characters long.')
          return
        }

        // Login via authService
        const data = await authService.login(formData.identifier.trim(), formData.password)

        // Store token
        localStorage.setItem('token', data.token)
        setSuccess('Login successful.')
        // Optionally, redirect the user to a protected route
      }
    } catch (err: any) {
      // Handle errors returned by authService
      if (err.message) {
        setError(err.message)
      } else {
        setError('An unexpected error occurred.')
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Card className="w-full max-w-md mx-auto">
      <CardHeader className="space-y-1">
        <CardTitle className="text-2xl font-bold text-center">Welcome</CardTitle>
        <CardDescription className="text-center">
          {activeTab === 'signin' ? 'Sign in to your account' : 'Create a new account'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <Tabs
          value={activeTab}
          onValueChange={(value) => setActiveTab(value as 'signin' | 'signup')}
          className="w-full"
        >
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="signin">Sign In</TabsTrigger>
            <TabsTrigger value="signup">Sign Up</TabsTrigger>
          </TabsList>
          <form onSubmit={handleSubmit}>
            <TabsContent value="signin" className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="identifier">Email or Username</Label>
                <div className="relative">
                  <Input 
                    id="identifier" 
                    name="identifier"
                    placeholder="john@example.com or johndoe" 
                    value={formData.identifier}
                    onChange={handleInputChange}
                    className="pl-10"
                    required
                  />
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="signinPassword">Password</Label>
                <div className="relative">
                  <Input 
                    id="signinPassword" 
                    name="password"
                    type={showPassword ? 'text' : 'password'} 
                    value={formData.password}
                    onChange={handleInputChange}
                    className="pl-10 pr-10"
                    required
                  />
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? (
                      <EyeOff className="h-5 w-5 text-gray-400" />
                    ) : (
                      <Eye className="h-5 w-5 text-gray-400" />
                    )}
                  </Button>
                </div>
              </div>
            </TabsContent>
            <TabsContent value="signup" className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="username">Username</Label>
                <div className="relative">
                  <Input 
                    id="username" 
                    name="username"
                    placeholder="johndoe" 
                    value={formData.username}
                    onChange={handleInputChange}
                    className="pl-10"
                    required
                  />
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="email">Email</Label>
                <div className="relative">
                  <Input 
                    id="email" 
                    name="email"
                    type="email" 
                    placeholder="john@example.com" 
                    value={formData.email}
                    onChange={handleInputChange}
                    className="pl-10"
                    required
                  />
                  <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="signupPassword">Password</Label>
                <div className="relative">
                  <Input 
                    id="signupPassword" 
                    name="password"
                    type={showPassword ? 'text' : 'password'} 
                    value={formData.password}
                    onChange={handleInputChange}
                    className="pl-10 pr-10"
                    required
                  />
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                    onClick={() => setShowPassword(!showPassword)}
                  >
                    {showPassword ? (
                      <EyeOff className="h-5 w-5 text-gray-400" />
                    ) : (
                      <Eye className="h-5 w-5 text-gray-400" />
                    )}
                  </Button>
                </div>
              </div>
            </TabsContent>
            {error && (
              <Alert variant="destructive" className="mt-4">
                <AlertCircle className="h-4 w-4" />
                <AlertTitle>Error</AlertTitle>
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}
            {success && (
              <Alert variant="default" className="mt-4">
                <CheckCircle className="h-4 w-4" />
                <AlertTitle>Success</AlertTitle>
                <AlertDescription>{success}</AlertDescription>
              </Alert>
            )}
            <Button type="submit" className="w-full mt-4" disabled={isLoading}>
              {isLoading ? 'Processing...' : (activeTab === 'signin' ? 'Sign In' : 'Sign Up')}
            </Button>
          </form>
        </Tabs>
      </CardContent>
      <CardFooter className="flex flex-col items-center">
        <p className="text-center text-sm text-gray-600 mt-2">
          By signing up, you agree to our{' '}
          <a href="#" className="font-medium text-primary hover:underline">
            Terms of Service
          </a>{' '}
          and{' '}
          <a href="#" className="font-medium text-primary hover:underline">
            Privacy Policy
          </a>
          .
        </p>
      </CardFooter>
    </Card>
  )
}
"""
""
'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Loader2, CheckCircle, XCircle, Mail, RefreshCw, ArrowRight } from 'lucide-react'
import { Progress } from "@/components/ui/progress"
import { useToast } from "../../hooks/use-toast"

export default function VerificationCheck() {
  const [isVerified, setIsVerified] = useState<boolean | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [resendSuccess, setResendSuccess] = useState(false)
  const [userEmail, setUserEmail] = useState<string | null>(null)
  const [progress, setProgress] = useState(0)
  const router = useRouter()
  const { toast } = useToast()

  useEffect(() => {
    const checkVerification = async () => {
      const userId = localStorage.getItem('userId')
      const token = localStorage.getItem('token')
      const email = localStorage.getItem('userEmail')

      if (!userId || !token || !email) {
        setError('User information not found. Please sign in again.')
        setIsLoading(false)
        return
      }

      setUserEmail(email)

      try {
        const response = await fetch(`/api/auth/check-verification/${userId}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (!response.ok) {
          throw new Error('Failed to check verification status')
        }

        const data = await response.json()
        setIsVerified(data.verified)
      } catch (err) {
        setError('An error occurred while checking verification status')
      } finally {
        setIsLoading(false)
      }
    }

    checkVerification()
  }, [])

  useEffect(() => {
    if (isLoading) {
      const timer = setInterval(() => {
        setProgress((oldProgress) => {
          if (oldProgress === 100) {
            clearInterval(timer)
            return 100
          }
          return Math.min(oldProgress + 10, 100)
        })
      }, 500)

      return () => {
        clearInterval(timer)
      }
    }
  }, [isLoading])

  const handleResendVerification = async () => {
    setIsLoading(true)
    setError(null)
    setResendSuccess(false)

    if (!userEmail) {
      setError('User email not found. Please sign in again.')
      setIsLoading(false)
      return
    }

    try {
      const response = await fetch('/api/auth/resend-verification', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: userEmail }),
      })

      if (!response.ok) {
        throw new Error('Failed to resend verification email')
      }

      setResendSuccess(true)
      toast({
        title: "Verification Email Sent",
        description: `A new verification email has been sent to ${userEmail}`,
        duration: 5000,
      })
    } catch (err) {
      setError('An error occurred while resending the verification email')
    } finally {
      setIsLoading(false)
    }
  }

  const handleRefreshStatus = async () => {
    setIsLoading(true)
    setError(null)
    const userId = localStorage.getItem('userId')
    const token = localStorage.getItem('token')

    if (!userId || !token) {
      setError('User information not found. Please sign in again.')
      setIsLoading(false)
      return
    }

    try {
      const response = await fetch(`/api/auth/check-verification/${userId}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        throw new Error('Failed to check verification status')
      }

      const data = await response.json()
      setIsVerified(data.verified)
      if (data.verified) {
        toast({
          title: "Email Verified",
          description: "Your email has been successfully verified!",
          duration: 5000,
        })
      }
    } catch (err) {
      setError('An error occurred while checking verification status')
    } finally {
      setIsLoading(false)
    }
  }

  const handleContinue = () => {
    router.push('/home')
  }

  if (isLoading) {
    return (
      <Card className="w-full max-w-md mx-auto mt-8">
        <CardContent className="flex flex-col items-center justify-center p-6">
          <Loader2 className="h-16 w-16 animate-spin text-primary" />
          <p className="mt-4 text-lg font-semibold">Checking verification status...</p>
          <Progress value={progress} className="w-full mt-4" />
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="w-full max-w-md mx-auto mt-8">
      <CardHeader>
        <CardTitle className="text-2xl font-bold text-center">Email Verification</CardTitle>
        <CardDescription className="text-center">
          Please verify your email address to continue
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {error && (
          <Alert variant="destructive">
            <XCircle className="h-4 w-4" />
            <AlertTitle>Error</AlertTitle>
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}
        {isVerified === true && (
          <Alert variant="default" className="bg-green-50 border-green-200">
            <CheckCircle className="h-4 w-4 text-green-600" />
            <AlertTitle className="text-green-800">Verified</AlertTitle>
            <AlertDescription className="text-green-700">
              Your email has been successfully verified.
            </AlertDescription>
          </Alert>
        )}
        {isVerified === false && (
          <Alert variant="default" className="bg-yellow-50 border-yellow-200">
            <Mail className="h-4 w-4 text-yellow-600" />
            <AlertTitle className="text-yellow-800">Not Verified</AlertTitle>
            <AlertDescription className="text-yellow-700">
              Please check your email and click the verification link.
            </AlertDescription>
          </Alert>
        )}
        {resendSuccess && (
          <Alert variant="default" className="bg-blue-50 border-blue-200">
            <CheckCircle className="h-4 w-4 text-blue-600" />
            <AlertTitle className="text-blue-800">Email Sent</AlertTitle>
            <AlertDescription className="text-blue-700">
              A new verification email has been sent to {userEmail}. Please check your inbox and spam folder.
            </AlertDescription>
          </Alert>
        )}
        {userEmail && (
          <p className="text-sm text-gray-600 text-center">
            We sent a verification email to: <strong>{userEmail}</strong>
          </p>
        )}
      </CardContent>
      <CardFooter className="flex flex-col space-y-2">
        {isVerified === false && (
          <>
            <Button 
              onClick={handleResendVerification} 
              disabled={isLoading || resendSuccess}
              className="w-full"
            >
              {isLoading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Mail className="mr-2 h-4 w-4" />}
              Resend Verification Email
            </Button>
            <Button
              onClick={handleRefreshStatus}
              variant="outline"
              className="w-full"
            >
              <RefreshCw className="mr-2 h-4 w-4" />
              Refresh Verification Status
            </Button>
          </>
        )}
        <Button 
          onClick={handleContinue} 
          disabled={!isVerified}
          className="w-full"
        >
          {isVerified ? (
            <>
              Continue to Home
              <ArrowRight className="ml-2 h-4 w-4" />
            </>
          ) : (
            'Verify to Continue'
          )}
        </Button>
      </CardFooter>
    </Card>
  )
}
"""
"""
import Image from "next/image";

export default function Home() {
  return (
    <div>
      Hello
    </div>
  );
}
"""
"""
// services/auth.service.ts
import api from './api';

interface SignupResponse {
  message: string;
  token: string;
  user: {
    id: string;
    username: string;
    email: string;
    verified: boolean;
  };
}

interface LoginResponse {
  message: string;
  token: string;
  user: {
    id: string;
    username: string;
    email: string;
    verified: boolean;
  };
}

interface VerificationResponse {
  message: string;
  errors?: Array<{
    field: string;
    message: string;
  }>;
}

export const authService = {
  signup: async (data: {
    username: string;
    email: string;
    password: string;
  }): Promise<SignupResponse> => {
    const response = await api.post<SignupResponse>('/auth/signup', data)
    return response.data
  },

  login: async (identifier: string, password: string): Promise<LoginResponse> => {
    const response = await api.post<LoginResponse>('/auth/login', { identifier, password })
    return response.data
  },

  verifyEmail: async (token: string): Promise<VerificationResponse> => {
    const response = await api.post<VerificationResponse>('/auth/verify-email', { token })
    return response.data
  },

  // Add other auth-related API calls here
};
""
"""
// services/api.ts
import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

// Add response interceptor for error handling
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.data) {
      return Promise.reject(error.response.data);
    }
    return Promise.reject(error);
  }
);

export default api;
"""
"""