// tdd-guard:skip — auth gate UI (form state + supabase auth call); no pure logic to test in isolation
'use client'

import { useState, type ReactNode } from'react'
import { usePathname } from'next/navigation'
import { createClient } from'@/lib/supabase/client'
import { useUserSession } from'@/lib/auth/hooks'
import { CheckCircle2 } from'lucide-react'

const AUTH_PATHS = ['/login','/signup','/forgot-password','/reset-password','/auth']

function PasswordStrengthRow({ label, met }: { label: string; met: boolean }) {
 return (
 <div className="flex items-center gap-2 text-sm">
 <CheckCircle2
 size={14}
 className={met ?'text-success':'text-white/30'}
 />
 <span className={met ?'text-success':'text-white/50'}>{label}</span>
 </div>
 )
}

export default function RequirePasswordChange({ children }: { children: ReactNode }) {
 const session = useUserSession()
 const pathname = usePathname()

 const [password, setPassword] = useState('')
 const [confirm, setConfirm] = useState('')
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState<string | null>(null)

 const isAuthPath = AUTH_PATHS.some(
 (p) => pathname === p || pathname.startsWith(p +'/')
 )

 const meetsLength = password.length >= 8
 const meetsUppercase = /[A-Z]/.test(password)
 const meetsNumber = /[0-9]/.test(password)
 const meetsAll = meetsLength && meetsUppercase && meetsNumber

 async function handleSubmit(e: React.FormEvent) {
 e.preventDefault()
 setError(null)

 if (!meetsAll) {
 setError('Das Passwort erfüllt nicht alle Anforderungen.')
 return
 }
 if (password !== confirm) {
 setError('Die Passwörter stimmen nicht überein.')
 return
 }

 setSaving(true)
 const supabase = createClient()

 const { error: updateAuthError } = await supabase.auth.updateUser({ password })
 if (updateAuthError) {
 setError(updateAuthError.message)
 setSaving(false)
 return
 }

 const { error: profileError } = await supabase
 .from('user_profiles')
 .update({ must_change_password: false })
 .eq('auth_user_id', (await supabase.auth.getUser()).data.user?.id ??'')

 if (profileError) {
 setError(profileError.message)
 setSaving(false)
 return
 }

 window.location.reload()
 }

 if (!session || !session.mustChangePassword || isAuthPath) {
 return <>{children}</>
 }

 return (
 <>
 {/* inert: Children hinter dem Gate dürfen weder Fokus noch Taps bekommen (KAR-708) */}
 <div inert>{children}</div>
 <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-primary-dark/90 p-4">
 <div className="w-full max-w-md bg-card text-foreground rounded-sm overflow-hidden">
 <div className="bg-primary-dark px-6 py-5">
 <h1 className="text-xl font-bold text-white">Passwort ändern</h1>
 <p className="text-sm text-white/70 mt-1">
 Ihr Passwort muss vor der Nutzung geändert werden.
 </p>
 </div>

 <form onSubmit={handleSubmit} className="px-6 py-6 space-y-5">
 <div>
 <label className="block text-sm font-medium text-foreground mb-1.5">
 Neues Passwort
 </label>
 <input
 type="password"
 value={password}
 onChange={(e) => setPassword(e.target.value)}
 className="w-full h-11 px-3 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 placeholder="Mindestens 8 Zeichen"
 autoFocus
 autoComplete="new-password"
 />
 </div>

 <div className="space-y-1.5 bg-background rounded-lg px-4 py-3">
 <PasswordStrengthRow label="Mindestens 8 Zeichen"met={meetsLength} />
 <PasswordStrengthRow label="Mindestens 1 Großbuchstabe"met={meetsUppercase} />
 <PasswordStrengthRow label="Mindestens 1 Zahl"met={meetsNumber} />
 </div>

 <div>
 <label className="block text-sm font-medium text-foreground mb-1.5">
 Passwort bestätigen
 </label>
 <input
 type="password"
 value={confirm}
 onChange={(e) => setConfirm(e.target.value)}
 className="w-full h-11 px-3 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary"
 placeholder="Passwort wiederholen"
 autoComplete="new-password"
 />
 </div>

 {error && (
 <p className="text-sm text-destructive">{error}</p>
 )}

 <button
 type="submit"
 disabled={saving || !meetsAll || password !== confirm}
 className="w-full h-11 bg-primary text-white rounded-lg text-sm font-semibold hover:bg-primary/90 disabled:opacity-50 transition-colors"
 >
 {saving ?'Wird gespeichert…':'Passwort festlegen'}
 </button>
 </form>
 </div>
 </div>
 </>
 )
}
