import { useState, useEffect, useRef } from "react";

const BG_IMG = "data:image/png;base64,[encoded data, 55660 characters]";

const Login = (): JSX.Element => {
    const [loading, setLoading] = useState(false);
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const sceneRef = useRef<HTMLDivElement>(null);
    const mouseRef = useRef({ x: 0.5, y: 0.5 });
    const animRef = useRef<number>(0);

    useEffect(() => {
        const canvas = canvasRef.current;
        const scene = sceneRef.current;
        if (!canvas || !scene) return;
        const ctx = canvas.getContext("2d")!;

        let W = 0, H = 0;
        const waves: Array<{ r: number; maxR: number; opacity: number; speed: number }> = [];
        let waveTimer = 0;
        let time = 0;

        function resize() {
            W = canvas.width = scene.offsetWidth;
            H = canvas.height = scene.offsetHeight;
        }
        resize();

        type Particle = {
            x: number; y: number; z: number;
            vx: number; vy: number;
            baseSize: number; opacity: number;
            hue: number; twinkle: number; twinkleSpeed: number;
            type: "dot" | "cross";
        };

        function mkParticle(): Particle {
            const depth = Math.random();
            return {
                x: Math.random(), y: Math.random(), z: depth,
                vx: (Math.random() - 0.5) * 0.00012,
                vy: (Math.random() - 0.5) * 0.00012,
                baseSize: 0.8 + Math.random() * 2.5,
                opacity: 0.15 + Math.random() * 0.6,
                hue: 250 + Math.random() * 60,
                twinkle: Math.random() * Math.PI * 2,
                twinkleSpeed: 0.02 + Math.random() * 0.03,
                type: Math.random() < 0.15 ? "cross" : "dot",
            };
        }

        const particles: Particle[] = Array.from({ length: 180 }, mkParticle);

        function mkWave() {
            return { r: 0, maxR: Math.max(W, H) * 0.55, opacity: 0.6, speed: 0.8 + Math.random() * 0.5 };
        }
        waves.push(mkWave());

        function drawCross(x: number, y: number, size: number, alpha: number, hue: number) {
            ctx.save();
            ctx.globalAlpha = alpha;
            ctx.strokeStyle = `hsl(${hue},70%,75%)`;
            ctx.lineWidth = 0.8;
            ctx.beginPath();
            ctx.moveTo(x - size, y); ctx.lineTo(x + size, y);
            ctx.moveTo(x, y - size); ctx.lineTo(x, y + size);
            ctx.stroke();
            ctx.restore();
        }

        function render() {
            time++;
            ctx.clearRect(0, 0, W, H);

            const px = (mouseRef.current.x - 0.5) * 30;
            const py = (mouseRef.current.y - 0.5) * 20;

            // Nebula blobs
            const blobs = [
                { cx: 0.3, cy: 0.35, rx: W * 0.28, ry: H * 0.3, col: "rgba(124,58,237,0.14)" },
                { cx: 0.72, cy: 0.65, rx: W * 0.25, ry: H * 0.25, col: "rgba(167,139,250,0.09)" },
                { cx: 0.5, cy: 0.5, rx: W * 0.22, ry: H * 0.22, col: "rgba(99,38,200,0.11)" },
            ];
            blobs.forEach(b => {
                const bx = b.cx * W + px * 0.4;
                const by = b.cy * H + py * 0.4;
                const grd = ctx.createRadialGradient(bx, by, 0, bx, by, Math.max(b.rx, b.ry));
                grd.addColorStop(0, b.col);
                grd.addColorStop(1, "rgba(0,0,0,0)");
                ctx.fillStyle = grd;
                ctx.save();
                ctx.scale(1, b.ry / b.rx);
                ctx.beginPath();
                ctx.arc(bx, (by) * (b.rx / b.ry), b.rx, 0, Math.PI * 2);
                ctx.fill();
                ctx.restore();
            });

            // Wave rings
            waveTimer++;
            if (waveTimer > 90) { waves.push(mkWave()); waveTimer = 0; }
            for (let i = waves.length - 1; i >= 0; i--) {
                const w = waves[i];
                w.r += w.speed;
                w.opacity -= 0.003;
                if (w.opacity <= 0) { waves.splice(i, 1); continue; }
                ctx.save();
                ctx.globalAlpha = w.opacity * 0.4;
                ctx.strokeStyle = `rgba(167,139,250,${w.opacity})`;
                ctx.lineWidth = 0.8;
                ctx.beginPath();
                ctx.arc(W * 0.5 + px * 0.2, H * 0.5 + py * 0.2, w.r, 0, Math.PI * 2);
                ctx.stroke();
                ctx.restore();
            }

            // Grid dots
            ctx.save();
            ctx.globalAlpha = 0.04;
            ctx.fillStyle = "rgba(255,255,255,1)";
            const gs = 36;
            for (let gx = 0; gx < W + gs; gx += gs) {
                for (let gy = 0; gy < H + gs; gy += gs) {
                    ctx.beginPath();
                    ctx.arc(gx + px * 0.15, gy + py * 0.15, 0.8, 0, Math.PI * 2);
                    ctx.fill();
                }
            }
            ctx.restore();

            // Particles (3D depth)
            particles.forEach(p => {
                p.x += p.vx; p.y += p.vy;
                if (p.x < -0.02) p.x = 1.02;
                if (p.x > 1.02) p.x = -0.02;
                if (p.y < -0.02) p.y = 1.02;
                if (p.y > 1.02) p.y = -0.02;
                p.twinkle += p.twinkleSpeed;

                const tw = 0.6 + 0.4 * Math.sin(p.twinkle);
                const df = 0.3 + p.z * 0.7;
                const size = p.baseSize * df;
                const alpha = p.opacity * tw * df;
                const sx = p.x * W + px * p.z;
                const sy = p.y * H + py * p.z;

                if (p.type === "cross") {
                    drawCross(sx, sy, size * 2, alpha, p.hue);
                } else {
                    const grd = ctx.createRadialGradient(sx, sy, 0, sx, sy, size * 3);
                    grd.addColorStop(0, `hsla(${p.hue},70%,75%,${alpha})`);
                    grd.addColorStop(0.4, `hsla(${p.hue},60%,65%,${alpha * 0.4})`);
                    grd.addColorStop(1, `hsla(${p.hue},50%,60%,0)`);
                    ctx.fillStyle = grd;
                    ctx.beginPath();
                    ctx.arc(sx, sy, size * 3, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.save();
                    ctx.globalAlpha = alpha;
                    ctx.fillStyle = `hsl(${p.hue},80%,88%)`;
                    ctx.beginPath();
                    ctx.arc(sx, sy, size * 0.5, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.restore();
                }
            });

            // Mouse glow
            const mx = mouseRef.current.x * W;
            const my = mouseRef.current.y * H;
            const mg = ctx.createRadialGradient(mx, my, 0, mx, my, 80);
            mg.addColorStop(0, "rgba(200,170,255,0.12)");
            mg.addColorStop(1, "rgba(0,0,0,0)");
            ctx.fillStyle = mg;
            ctx.beginPath();
            ctx.arc(mx, my, 80, 0, Math.PI * 2);
            ctx.fill();

            animRef.current = requestAnimationFrame(render);
        }

        const onMouseMove = (e: MouseEvent) => {
            const r = scene.getBoundingClientRect();
            mouseRef.current = {
                x: (e.clientX - r.left) / r.width,
                y: (e.clientY - r.top) / r.height,
            };
        };
        const onMouseLeave = () => { mouseRef.current = { x: 0.5, y: 0.5 }; };
        const onResize = () => resize();

        scene.addEventListener("mousemove", onMouseMove);
        scene.addEventListener("mouseleave", onMouseLeave);
        window.addEventListener("resize", onResize);
        animRef.current = requestAnimationFrame(render);

        return () => {
            cancelAnimationFrame(animRef.current);
            scene.removeEventListener("mousemove", onMouseMove);
            scene.removeEventListener("mouseleave", onMouseLeave);
            window.removeEventListener("resize", onResize);
        };
    }, []);

    return (
        <div style={{ minHeight: "100vh", display: "flex", fontFamily: '"Plus Jakarta Sans","Segoe UI",sans-serif' }}>
            <style>{`
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap');
        *,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0 }
        @keyframes fadeUp { from { opacity: 0; transform: translateY(14px) } to { opacity: 1; transform: translateY(0) } }
        @keyframes spin { to { transform: rotate(360deg) } }
        @keyframes ringPulse { 0%,100% { opacity: .5; transform: translate(-50%,-50%) scale(1); } 50% { opacity: .85; transform: translate(-50%,-50%) scale(1.04); } }
        .ms-btn {
            display: flex; align-items: center; justify-content: center; gap: 12px;
            width: 100%; padding: 15px 24px; background: #1e0e5c; color: #fff;
            border: none; border-radius: 10px; font-size: 15px; font-weight: 600;
            font-family: inherit; cursor: pointer; text-decoration: none;
            letter-spacing: .15px; transition: background .2s, transform .15s, box-shadow .2s;
            box-shadow: 0 2px 8px rgba(30,14,92,.25), 0 6px 24px rgba(30,14,92,.2);
        }
        .ms-btn:hover { background: #150a42; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(30,14,92,.3), 0 10px 32px rgba(30,14,92,.25); }
        .ms-btn:active { transform: translateY(0); }
        .ms-btn.loading { background: #6b6b9a; cursor: not-allowed; box-shadow: none; }
        .spinner { width: 17px; height: 17px; border: 2px solid rgba(255,255,255,.3); border-top-color: white; border-radius: 50%; animation: spin .75s linear infinite; flex-shrink: 0; }
        .ring { position: absolute; top: 50%; left: 50%; border-radius: 50%; border: 1px solid rgba(124,58,237,.15); animation: ringPulse 4s ease-in-out infinite; pointer-events: none; transform: translate(-50%,-50%); }
      `}</style>

            {/* ── LEFT PANEL ── */}
            <div style={{
                width: 460, minHeight: "100vh", background: "#fff",
                display: "flex", flexDirection: "column", justifyContent: "space-between",
                padding: "48px 56px", position: "relative", zIndex: 2,
                boxShadow: "2px 0 60px rgba(0,0,0,0.1)",
            }}>
                <div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 3, background: "linear-gradient(90deg,#1e0e5c,#7c3aed)" }} />

                <img src="/img/NDF_Image_Logo.png" alt="NDF" style={{ height: 52, objectFit: "contain" }} />

                <div style={{ animation: "fadeUp .5s cubic-bezier(.22,1,.36,1) both" }}>
                    <div style={{ marginBottom: 40 }}>
                        <p style={{ fontSize: 11, fontWeight: 700, letterSpacing: "2.5px", color: "#7c3aed", textTransform: "uppercase", marginBottom: 12 }}>
                            Accès sécurisé
                        </p>
                        <h1 style={{ fontSize: 32, fontWeight: 800, color: "#0f0a2e", letterSpacing: "-0.8px", lineHeight: 1.15, marginBottom: 10 }}>
                            Bienvenue sur NDF
                        </h1>
                        <p style={{ fontSize: 14.5, color: "#6b7280", lineHeight: 1.6, maxWidth: 320 }}>
                            Connectez-vous pour accéder à la plateforme de gestion des notes de frais ENSUP Group.
                        </p>
                    </div>

                    <a href="/api/auth/microsoft"
                        onClick={() => setLoading(true)}
                        className={`ms-btn${loading ? " loading" : ""}`}
                        style={{ pointerEvents: loading ? "none" : "auto" }}>
                        {loading ? (
                            <><div className="spinner" /><span>Connexion en cours…</span></>
                        ) : (
                            <>
                                <svg width="20" height="20" viewBox="0 0 23 23" fill="none" style={{ flexShrink: 0 }}>
                                    <path fill="#f3f3f3" d="M0 0h23v23H0z" /><path fill="#f35325" d="M1 1h10v10H1z" />
                                    <path fill="#81bc06" d="M12 1h10v10H12z" /><path fill="#05a6f0" d="M1 12h10v10H1z" />
                                    <path fill="#ffba08" d="M12 12h10v10H12z" />
                                </svg>
                                <span>Continuer avec Microsoft</span>
                            </>
                        )}
                    </a>

                    <div style={{ marginTop: 28, padding: "16px 18px", background: "#f9f8ff", border: "1px solid #ede9fe", borderRadius: 10, display: "flex", gap: 13, alignItems: "flex-start" }}>
                        <div style={{ width: 36, height: 36, flexShrink: 0, borderRadius: 9, background: "linear-gradient(135deg,#1e0e5c,#7c3aed)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                                <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
                            </svg>
                        </div>
                        <div>
                            <p style={{ fontSize: 13, fontWeight: 700, color: "#1e0e5c", marginBottom: 3 }}>Authentification Microsoft SSO</p>
                            <p style={{ fontSize: 12, color: "#7c6fa0", lineHeight: 1.55 }}>
                                Utilisez votre compte professionnel ENSUP Group. Aucun mot de passe supplémentaire requis.
                            </p>
                        </div>
                    </div>
                </div>

                <p style={{ fontSize: 11.5, color: "#d1d5db" }}>© 2026 ENSUP Group · Version 1.0.0</p>
            </div>

            {/* ── RIGHT PANEL — Canvas 3D + image base bg ── */}
            <div
                ref={sceneRef}
                style={{
                    flex: 1,
                    position: "relative",
                    overflow: "hidden",
                    background: "linear-gradient(145deg,#0f0a2e 0%,#1a0e4f 40%,#2e1878 70%,#1e0e5c 100%)",
                }}
            >
                {/* Image de fond en opacity basse — couleurs extraites */}
                <div style={{
                    position: "absolute", inset: 0,
                    backgroundImage: `url(${BG_IMG})`,
                    backgroundSize: "cover",
                    backgroundPosition: "center",
                    opacity: 0.18,
                    mixBlendMode: "luminosity",
                }} />

                {/* Canvas animation 3D par-dessus */}
                <canvas
                    ref={canvasRef}
                    style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}
                />

                {/* Anneaux pulsants */}
                {[{ s: 260, d: "0s", dur: "4s" }, { s: 380, d: "1.3s", dur: "5s" }, { s: 500, d: "2.6s", dur: "6s" }].map((r, i) => (
                    <div key={i} className="ring" style={{
                        width: r.s, height: r.s,
                        animationDelay: r.d,
                        animationDuration: r.dur,
                    }} />
                ))}

                {/* Badge statut */}
                <div style={{
                    position: "absolute", bottom: 28, left: "50%", transform: "translateX(-50%)",
                    display: "flex", alignItems: "center", gap: 8,
                    background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.1)",
                    borderRadius: 20, padding: "7px 20px", whiteSpace: "nowrap",
                    backdropFilter: "blur(8px)", zIndex: 2,
                }}>
                    <div style={{ width: 7, height: 7, borderRadius: "50%", background: "#22c55e", boxShadow: "0 0 8px rgba(34,197,94,.7)" }} />
                    <span style={{ fontSize: 11.5, color: "rgba(255,255,255,.45)", fontWeight: 500 }}>2026 · ENSUP Group</span>
                </div>
            </div>
        </div>
    );
};

export default Login;