// [TSM.ID].[11031972] — All Rights Reserved. Proprietary & Confidential.
"use client";

import { useSearchParams } from "next/navigation";
import { use, useEffect, useState } from "react";
import { XCURoom } from "../../../components/xcuRoom";

export default function RoomPage({
	params,
}: {
	params: Promise<{ roomName: string }>;
}) {
	const resolvedParams = use(params);
	const roomName = resolvedParams.roomName;

	const searchParams = useSearchParams();
	const isVoiceCall = searchParams.get("audioOnly") === "true";

	const [token, setToken] = useState("");
	const [serverUrl, setServerUrl] = useState("");
	const [error, setError] = useState("");
	const [isInitializing, setIsInitializing] = useState(true);
	const [username, setUsername] = useState("");
	
	// Guest Lobby State
	const [showGuestLobby, setShowGuestLobby] = useState(false);
	const [guestName, setGuestName] = useState("");
	const [guestLoading, setGuestLoading] = useState(false);
	const [guestError, setGuestError] = useState("");

	useEffect(() => {
		(async () => {
			try {
				const authResp = await fetch(`/vc/api/auth/me?_cb=${Date.now()}`);
				const authData = await authResp.json();
				if (authData.error) {
					// User tidak login → tampilkan Guest Lobby (seperti Zoom)
					setShowGuestLobby(true);
					setIsInitializing(false);
					return;
				}
				const userEmail = authData.email;
				setUsername(userEmail);

				const qResp = await fetch(`/api/auth/quantum_token?_cb=${Date.now()}`, { credentials: 'include' });
				if (!qResp.ok) {
					throw new Error("Otorisasi JUMPA.ID Ditolak: Gagal memverifikasi Lisensi Tenant.");
				}
				const qData = await qResp.json();
				if (qData.error || !qData.token) {
					throw new Error("Akses Ilegal Terdeteksi: Harap masuk melalui Dasbor JUMPA.ID terlebih dahulu.");
				}
				
				setToken(qData.token);
				setServerUrl(process.env.NEXT_PUBLIC_XCU_SERVER_URL || "/xcu-engine");
				setIsInitializing(false);

			} catch (e: unknown) {
				// Auth failed but not critical → show guest lobby
				setShowGuestLobby(true);
				setIsInitializing(false);
			}
		})();
	}, [roomName]);

	// Handle Guest Join
	const handleGuestJoin = async () => {
		if (!guestName.trim() || guestName.trim().length < 2) {
			setGuestError("Masukkan nama Anda (minimal 2 karakter).");
			return;
		}
		setGuestLoading(true);
		setGuestError("");

		try {
			const res = await fetch('/api/auth/guest-token', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				credentials: 'include',
				body: JSON.stringify({ roomName, displayName: guestName.trim() }),
			});

			const data = await res.json();
			
			if (!res.ok || data.error) {
				setGuestError(data.error || "Gagal masuk sebagai tamu.");
				setGuestLoading(false);
				return;
			}

			// Guest token received — set state and enter room
			setToken(data.token);
			setUsername(data.displayName);
			setServerUrl(process.env.NEXT_PUBLIC_XCU_SERVER_URL || "/xcu-engine");
			setShowGuestLobby(false);

		} catch (e) {
			setGuestError("Koneksi gagal. Periksa jaringan Anda.");
			setGuestLoading(false);
		}
	};

	// ═══════════════════════════════════════
	// GUEST LOBBY UI (Zoom-Like)
	// ═══════════════════════════════════════
	if (showGuestLobby) {
		return (
			<div className="h-dvh flex items-center justify-center bg-[#0a101d] overflow-hidden relative">
				{/* Background Animation */}
				<div className="absolute inset-0 z-0 opacity-10 pointer-events-none">
					<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[120vw] h-[120vw] rounded-full border border-blue-500/20 animate-pulse"></div>
					<div className="absolute top-1/4 right-1/4 w-64 h-64 bg-blue-600/10 rounded-full blur-3xl"></div>
					<div className="absolute bottom-1/4 left-1/4 w-80 h-80 bg-purple-600/10 rounded-full blur-3xl"></div>
				</div>

				<div className="relative z-10 w-full max-w-md mx-4">
					<div className="bg-[#111827]/90 backdrop-blur-2xl border border-white/10 rounded-3xl shadow-2xl overflow-hidden">
						{/* Header */}
						<div className="px-8 pt-10 pb-6 text-center">
							<div className="w-16 h-16 mx-auto mb-5 rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/30">
								<svg className="w-8 h-8 text-white" fill="currentColor" viewBox="0 0 24 24">
									<path d="M4 4h10a2 2 0 0 1 2 2v3.5l4-3v11l-4-3V18a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z"></path>
								</svg>
							</div>
							<h1 className="text-2xl font-black text-white tracking-tight mb-1">
								Gabung Rapat
							</h1>
							<p className="text-sm text-gray-400">
								Room: <span className="text-blue-400 font-mono font-bold">{decodeURIComponent(roomName)}</span>
							</p>
						</div>

						{/* Form */}
						<div className="px-8 pb-8 space-y-4">
							<div>
								<label className="block text-xs font-bold text-gray-400 uppercase tracking-widest mb-2">
									Nama Tampilan
								</label>
								<input
									type="text"
									value={guestName}
									onChange={(e) => { setGuestName(e.target.value); setGuestError(""); }}
									onKeyDown={(e) => e.key === 'Enter' && handleGuestJoin()}
									placeholder="Masukkan nama Anda..."
									maxLength={50}
									autoFocus
									className="w-full px-4 py-3.5 bg-white/5 border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all text-base"
								/>
							</div>

							{guestError && (
								<div className="px-4 py-3 bg-red-500/10 border border-red-500/20 rounded-xl text-red-400 text-sm font-medium flex items-center gap-2">
									<svg className="w-4 h-4 shrink-0" fill="currentColor" viewBox="0 0 20 20">
										<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
									</svg>
									{guestError}
								</div>
							)}

							<button
								onClick={handleGuestJoin}
								disabled={guestLoading || guestName.trim().length < 2}
								className={`w-full py-3.5 rounded-xl font-bold text-base transition-all flex items-center justify-center gap-2 ${
									guestLoading || guestName.trim().length < 2
										? 'bg-gray-700 text-gray-500 cursor-not-allowed'
										: 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:shadow-lg hover:shadow-blue-500/30 hover:-translate-y-0.5 active:translate-y-0'
								}`}
							>
								{guestLoading ? (
									<>
										<div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
										Menghubungkan...
									</>
								) : (
									<>
										<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
											<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
										</svg>
										Gabung sebagai Tamu
									</>
								)}
							</button>

							<div className="text-center pt-2">
								<p className="text-xs text-gray-500 mb-3">
									Sudah punya akun JUMPA.ID?
								</p>
								<a
									href="/"
									className="text-sm text-blue-400 hover:text-blue-300 font-semibold transition-colors"
								>
									Masuk dengan Akun →
								</a>
							</div>
						</div>

						{/* Footer */}
						<div className="px-8 py-4 bg-white/[0.02] border-t border-white/5 text-center">
							<p className="text-[10px] text-gray-600 font-mono">
								Powered by JUMPA.ID • XCom ULTRA Engine • [TSM.ID].[11031972]
							</p>
						</div>
					</div>
				</div>
			</div>
		);
	}

	if (error) {
		return (
			<div className="h-dvh flex items-center justify-center bg-[#0a101d]">
				<div className="bg-red-950/40 p-8 rounded-3xl text-center border border-red-500/30 max-w-md">
					<h2 className="text-red-500 font-bold text-xl mb-2">
						Akses Ditolak
					</h2>
					<p className="text-gray-400 mb-6">{error}</p>
					<button
						onClick={() => (window.location.href = "/")}
						className="px-6 py-2.5 bg-red-600 text-white font-bold rounded-xl"
					>
						Kembali ke Dasbor
					</button>
				</div>
			</div>
		);
	}

	if (isInitializing) {
		return (
			<div className="h-dvh flex items-center justify-center bg-[#0a101d] overflow-hidden relative">
				<div className="absolute inset-0 z-0 opacity-20 pointer-events-none flex items-center justify-center">
					<div className="w-[80vw] h-[80vw] rounded-full border border-blue-500/30 animate-ping absolute"></div>
					<div className="w-[60vw] h-[60vw] rounded-full border border-blue-400/20 animate-ping absolute [animation-delay:0.5s]"></div>
					<div className="w-[40vw] h-[40vw] rounded-full border border-blue-300/10 animate-ping absolute [animation-delay:1s]"></div>
				</div>
				<div className="flex flex-col items-center z-10 p-8 bg-black/40 backdrop-blur-md rounded-3xl border border-white/5">
					<div className="mb-8 relative w-24 h-24 flex items-center justify-center">
					   <div className="absolute inset-0 rounded-full border-t-2 border-blue-500 animate-spin"></div>
					   <div className="absolute inset-2 rounded-full border-r-2 border-green-500 animate-spin [animation-direction:reverse]"></div>
					   <svg className="w-8 h-8 text-blue-400 animate-pulse" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2L2 22h20L12 2zm0 4.5l6.5 13h-13L12 6.5zM11 16h2v2h-2v-2zm0-5h2v4h-2v-4z"/></svg>
					</div>
					<div className="text-center">
						<p className="text-white font-black text-xl tracking-widest uppercase mb-1">
							Initializing JUMPA.ID Engine
						</p>
						<p className="text-blue-400 font-mono text-xs">
							ESTABLISHING SECURE CONNECTION FOR {username.toUpperCase()}...
						</p>
					</div>
				</div>
			</div>
		);
	}

	// THE ABSOLUTE XCU CORE ENGINE
	// 100% XCU Ultra Node [TSM.ID].[11031972]
	return (
		<ErrorBoundaryWrapper roomName={roomName}>
			<XCURoom
				roomName={roomName}
				token={token}
				serverUrl={serverUrl}
				isVoiceCall={isVoiceCall}
				initialCameraOn={false}
				initialMicOn={false}
				username={username}
			/>
		</ErrorBoundaryWrapper>
	);
}

// Custom Error Boundary to catch & display the EXACT crash reason
import React from "react";
class ErrorBoundaryWrapper extends React.Component<{roomName: string, children: React.ReactNode}, {hasError: boolean, error: string}> {
	constructor(props: any) {
		super(props);
		this.state = { hasError: false, error: "" };
	}
	static getDerivedStateFromError(error: Error) {
		return { hasError: true, error: `${error.name}: ${error.message}\n${error.stack}` };
	}
	render() {
		if (this.state.hasError) {
			return (
				<div className="h-dvh flex items-center justify-center bg-[#0a101d] p-4">
					<div className="bg-red-950/40 p-8 rounded-3xl text-center border border-red-500/30 max-w-2xl w-full">
						<h2 className="text-red-500 font-bold text-xl mb-4">XCU Engine Crash Report</h2>
						<pre className="text-left text-xs text-gray-300 bg-black/60 p-4 rounded-xl overflow-auto max-h-[60vh] whitespace-pre-wrap break-all">{this.state.error}</pre>
						<button onClick={() => window.location.reload()} className="mt-6 px-6 py-2.5 bg-red-600 text-white font-bold rounded-xl">Reload</button>
					</div>
				</div>
			);
		}
		return this.props.children;
	}
}
