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

const FONT_URL = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap";

// ── Terminal data cascade lines ───────────────────────────────────────────────
const TERMINAL_LINES = [
    "INIT SEQUENCE 0x4F2A...",
    "AUTH TOKEN: ██████████████",
    "SCAN FREQ   847.221 MHz",
    "SECTOR      [CLASSIFIED]",
    "NODE_ID     NX-9912-DELTA",
    "TIMESTAMP   2025.03.06",
    "CLEARANCE   LEVEL-OMEGA",
    "STATUS      AUTHORIZED",
    "PAYLOAD     ENCRYPTED",
    "UPLINK      ACTIVE",
    "SIGNAL      ████░░░░ 61%",
    "VERIFY      SHA256:c0d3f",
    "MATRIX      7×7 LATTICE",
    "HASH        0xDEADBEEF",
    "PING        12.4ms OK",
    "TRACE       DISABLED",
    "VAULT       SEALED",
    "PROTOCOL    OMEGA-9",
    "ENTROPY     HIGH",
    "FRAME       #00441",
    "BUFFER      FLUSHED",
    "CIPHER      AES-256",
    "RELAY       PROXIED",
    "ECHO        SILENT",
    "LOCK        ENGAGED",
    "GRID REF    44.0N 76.2W",
    "KERNEL      3.14.159",
    "DAEMON      RUNNING",
    "WATCHDOG    ARMED",
    "ROUTE       OBFUSCATED",
];

function useAnimFrame(cb) {
    const ref = useRef();
    useEffect(() => {
        let id;
        const loop = (t) => { cb(t); id = requestAnimationFrame(loop); };
        id = requestAnimationFrame(loop);
        return () => cancelAnimationFrame(id);
    }, [cb]);
}

// ── Noise / grain canvas ──────────────────────────────────────────────────────
function GrainOverlay({ strength = 0.18 }) {
    const canvasRef = useRef();
    const tick = useRef(0);

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

        const draw = () => {
            tick.current++;
            if (tick.current % 2 !== 0) { raf = requestAnimationFrame(draw); return; }
            const { width, height } = canvas;
            const img = ctx.createImageData(width, height);
            const d = img.data;
            for (let i = 0; i < d.length; i += 4) {
                const px = i / 4;
                const x = px % width;
                const y = Math.floor(px / width);
                // Vignette factor — stronger at edges
                const cx = x / width - 0.5, cy = y / height - 0.5;
                const dist = Math.sqrt(cx * cx + cy * cy);
                const vignette = Math.min(1, dist * 2.2);
                const noise = (Math.random() - 0.5) * 255 * (strength + vignette * 0.18);
                d[i] = d[i + 1] = d[i + 2] = 128 + noise;
                d[i + 3] = Math.floor(18 + vignette * 30);
            }
            ctx.putImageData(img, 0, 0);
            raf = requestAnimationFrame(draw);
        };

        const resize = () => {
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;
        };
        resize();
        draw();
        window.addEventListener("resize", resize);
        return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", resize); };
    }, [strength]);

    return (
        <canvas
            ref={canvasRef}
            style={{
                position: "absolute", inset: 0, width: "100%", height: "100%",
                pointerEvents: "none", mixBlendMode: "overlay", zIndex: 10,
            }}
        />
    );
}

// ── SVG geometric overlay ─────────────────────────────────────────────────────
function GeometricOverlay() {
    return (
        <svg
            viewBox="0 0 480 860"
            style={{
                position: "absolute", inset: 0, width: "100%", height: "100%",
                pointerEvents: "none", zIndex: 5, opacity: 0.12,
            }}
            preserveAspectRatio="none"
        >
            {/* Corner triangles */}
            <polygon points="0,0 72,0 0,72" fill="none" stroke="white" strokeWidth="0.8" />
            <polygon points="480,0 408,0 480,72" fill="none" stroke="white" strokeWidth="0.8" />
            <polygon points="0,860 72,860 0,788" fill="none" stroke="white" strokeWidth="0.8" />
            <polygon points="480,860 408,860 480,788" fill="none" stroke="white" strokeWidth="0.8" />
            {/* Subtle grid lines */}
            {[0.2, 0.4, 0.6, 0.8].map((t) => (
                <line key={t} x1={480 * t} y1="0" x2={480 * t} y2="860" stroke="white" strokeWidth="0.4" />
            ))}
            {[0.25, 0.5, 0.75].map((t) => (
                <line key={t} x1="0" y1={860 * t} x2="480" y2={860 * t} stroke="white" strokeWidth="0.4" />
            ))}
            {/* Radiating accent lines from center */}
            <line x1="240" y1="430" x2="0" y2="0" stroke="white" strokeWidth="0.3" />
            <line x1="240" y1="430" x2="480" y2="0" stroke="white" strokeWidth="0.3" />
            <line x1="240" y1="430" x2="0" y2="860" stroke="white" strokeWidth="0.3" />
            <line x1="240" y1="430" x2="480" y2="860" stroke="white" strokeWidth="0.3" />
            {/* Center circle accent */}
            <circle cx="240" cy="430" r="200" fill="none" stroke="white" strokeWidth="0.5" />
            <circle cx="240" cy="430" r="198" fill="none" stroke="white" strokeWidth="0.2" />
        </svg>
    );
}

// ── Terminal code cascade ─────────────────────────────────────────────────────
function TerminalMask() {
    const [offset, setOffset] = useState(0);
    const [glitch, setGlitch] = useState({ row: -1, px: 0 });

    useEffect(() => {
        const iv = setInterval(() => {
            setOffset((o) => (o + 1) % TERMINAL_LINES.length);
        }, 120);
        const gv = setInterval(() => {
            setGlitch({ row: Math.floor(Math.random() * 18), px: (Math.random() - 0.5) * 8 });
            setTimeout(() => setGlitch({ row: -1, px: 0 }), 80);
        }, 900);
        return () => { clearInterval(iv); clearInterval(gv); };
    }, []);

    const visible = Array.from({ length: 20 }, (_, i) =>
        TERMINAL_LINES[(offset + i) % TERMINAL_LINES.length]
    );

    return (
        <div
            style={{
                width: "100%", height: "100%",
                background: "#000",
                borderRadius: "50%",
                overflow: "hidden",
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                padding: "18px 14px",
                gap: 0,
                position: "relative",
            }}
        >
            {/* inner vignette */}
            <div style={{
                position: "absolute", inset: 0, borderRadius: "50%",
                background: "radial-gradient(ellipse at center, transparent 30%, rgba(0,0,0,0.72) 100%)",
                zIndex: 2, pointerEvents: "none",
            }} />
            {visible.map((line, i) => (
                <div
                    key={i}
                    style={{
                        fontFamily: "'IBM Plex Mono', monospace",
                        fontSize: "9.5px",
                        fontWeight: i === 0 ? 700 : 400,
                        letterSpacing: "0.08em",
                        color: i === 0 ? "#FFFFFF" : i < 3 ? "#D8D8D8" : "#888",
                        lineHeight: "1.55",
                        opacity: i === 0 ? 1 : Math.max(0.18, 1 - i * 0.045),
                        transform: glitch.row === i ? `translateX(${glitch.px}px)` : "none",
                        whiteSpace: "nowrap",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        transition: "transform 0.04s",
                        position: "relative",
                        zIndex: 3,
                    }}
                >
                    {i === 0 ? "▶ " : "  "}{line}
                </div>
            ))}
        </div>
    );
}

// ── Barcode SVG ───────────────────────────────────────────────────────────────
function Barcode() {
    const bars = Array.from({ length: 60 }, (_, i) => {
        const w = [1, 1, 2, 1, 3, 1, 2, 1, 1, 2][i % 10];
        return { w, gap: [2, 1, 2, 3, 1, 2, 1, 2, 3, 1][i % 10] };
    });
    return (
        <svg width="160" height="36" viewBox="0 0 160 36">
            {bars.reduce((acc, bar, i) => {
                const x = acc.x;
                acc.elements.push(
                    <rect key={i} x={x} y={2} width={bar.w} height={28} fill="white" />
                );
                acc.x += bar.w + bar.gap;
                return acc;
            }, { x: 2, elements: [] }).elements}
        </svg>
    );
}

// ── Tear line ─────────────────────────────────────────────────────────────────
function TearLine() {
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 0, margin: "0 -32px" }}>
            <div style={{
                width: 22, height: 22, borderRadius: "50%",
                background: "#0A0A0A", border: "1px solid #2a2a2a", flexShrink: 0,
            }} />
            <div style={{
                flex: 1, height: 1,
                backgroundImage: "repeating-linear-gradient(90deg, #333 0, #333 6px, transparent 6px, transparent 12px)",
            }} />
            <div style={{
                width: 22, height: 22, borderRadius: "50%",
                background: "#0A0A0A", border: "1px solid #2a2a2a", flexShrink: 0,
            }} />
        </div>
    );
}

// ── Main component ────────────────────────────────────────────────────────────
export default function CyberTicket() {
    const [pulse, setPulse] = useState(false);

    useEffect(() => {
        // inject font
        if (!document.getElementById("ibm-plex-mono")) {
            const link = document.createElement("link");
            link.id = "ibm-plex-mono";
            link.rel = "stylesheet";
            link.href = FONT_URL;
            document.head.appendChild(link);
        }
        const iv = setInterval(() => setPulse((p) => !p), 1400);
        return () => clearInterval(iv);
    }, []);

    return (
        <div
            style={{
                minHeight: "100vh",
                background: "#0A0A0A",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                padding: "40px 16px",
                fontFamily: "'IBM Plex Mono', monospace",
                position: "relative",
                overflow: "hidden",
            }}
        >
            {/* full-page grain */}
            <GrainOverlay strength={0.14} />

            {/* Ticket card */}
            <div
                style={{
                    width: "100%",
                    maxWidth: 420,
                    background: "#0A0A0A",
                    border: "1px solid #222",
                    borderRadius: 18,
                    overflow: "hidden",
                    position: "relative",
                    transform: "perspective(900px) rotateX(2.5deg) rotateY(-1.5deg)",
                    boxShadow: "0 32px 80px rgba(0,0,0,0.92), 0 2px 0 #333 inset",
                }}
            >
                <GrainOverlay strength={0.22} />
                <GeometricOverlay />

                {/* 1 ── TOP HEADER BAR */}
                <div
                    style={{
                        background: "#111",
                        borderBottom: "1px solid #222",
                        padding: "12px 20px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        position: "relative",
                        zIndex: 20,
                    }}
                >
                    <div>
                        <div style={{
                            fontSize: 9, fontWeight: 700, letterSpacing: "0.32em",
                            color: "#FFF", textTransform: "uppercase",
                        }}>NEXUS PROTOCOL</div>
                        <div style={{ fontSize: 7.5, color: "#666", letterSpacing: "0.18em", marginTop: 1 }}>
                            CLASSIFIED ACCESS DOCUMENT
                        </div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                        <div style={{ fontSize: 9, color: "#555", letterSpacing: "0.1em" }}>Ω-09</div>
                        <div style={{ fontSize: 7, color: "#3a3a3a", marginTop: 1 }}>© 2025</div>
                    </div>
                </div>

                {/* 2 ── BRANDING BLOCK */}
                <div style={{ padding: "24px 28px 16px", position: "relative", zIndex: 20 }}>
                    <div style={{
                        display: "flex", alignItems: "center", gap: 12, marginBottom: 6,
                    }}>
                        {/* Wave/neural icon */}
                        <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
                            <circle cx="14" cy="14" r="13" stroke="white" strokeWidth="1" />
                            <path d="M4 14 Q7 8 10 14 Q13 20 16 14 Q19 8 22 14 Q24 18 24 14"
                                stroke="white" strokeWidth="1.2" fill="none" strokeLinecap="round" />
                            <circle cx="14" cy="14" r="2" fill="white" />
                        </svg>
                        <div>
                            <div style={{
                                fontSize: 22, fontWeight: 700, letterSpacing: "0.18em",
                                color: "#FFF", textTransform: "uppercase", lineHeight: 1,
                            }}>NEURAL</div>
                            <div style={{
                                fontSize: 22, fontWeight: 400, letterSpacing: "0.34em",
                                color: "#888", textTransform: "uppercase", lineHeight: 1, marginTop: 2,
                            }}>ACCESS</div>
                        </div>
                    </div>
                    <div style={{
                        fontSize: 8, color: "#444", letterSpacing: "0.22em", textTransform: "uppercase",
                    }}>
                        HIGH-CLEARANCE ADMISSION DOCUMENT — SERIES 9 — OMEGA TIER
                    </div>
                </div>

                {/* 3 ── VISUAL CENTERPIECE — Terminal circle */}
                <div style={{
                    padding: "0 28px", position: "relative", zIndex: 20,
                    display: "flex", justifyContent: "center",
                }}>
                    <div style={{
                        width: 260, height: 260,
                        borderRadius: "50%",
                        border: "1px solid #333",
                        overflow: "hidden",
                        position: "relative",
                        boxShadow: "0 0 0 6px #111, 0 0 0 7px #222",
                    }}>
                        <TerminalMask />
                        <GrainOverlay strength={0.26} />
                    </div>
                </div>

                {/* scan status pill */}
                <div style={{
                    display: "flex", justifyContent: "center", marginTop: 12,
                    position: "relative", zIndex: 20,
                }}>
                    <div style={{
                        display: "flex", alignItems: "center", gap: 6,
                        border: "1px solid #2a2a2a", borderRadius: 999,
                        padding: "4px 14px",
                        background: "#0f0f0f",
                    }}>
                        <div style={{
                            width: 5, height: 5, borderRadius: "50%",
                            background: pulse ? "#FFF" : "#444",
                            transition: "background 0.4s",
                        }} />
                        <span style={{ fontSize: 8, letterSpacing: "0.2em", color: "#888", textTransform: "uppercase" }}>
                            SIGNAL {pulse ? "ACTIVE" : "PINGING"}
                        </span>
                    </div>
                </div>

                {/* 4 ── INFORMATION BLOCK */}
                <div style={{
                    padding: "22px 28px 0",
                    position: "relative", zIndex: 20,
                    display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px 12px",
                }}>
                    {[
                        { label: "BEARER", value: "AGENT_NX-44" },
                        { label: "ISSUED", value: "2025.03.06" },
                        { label: "CLEARANCE", value: "OMEGA / Ω" },
                        { label: "EXPIRES", value: "2025.12.31" },
                        { label: "SECTOR", value: "DELTA-9" },
                        { label: "NODE", value: "0xDEAD·BF9" },
                    ].map(({ label, value }) => (
                        <div key={label}>
                            <div style={{
                                fontSize: 7.5, color: "#444", letterSpacing: "0.24em",
                                textTransform: "uppercase", marginBottom: 3,
                            }}>{label}</div>
                            <div style={{
                                fontSize: 11, color: "#DEDEDE", letterSpacing: "0.1em",
                                fontWeight: 600,
                            }}>{value}</div>
                        </div>
                    ))}
                </div>

                {/* divider row */}
                <div style={{
                    padding: "20px 28px 0", position: "relative", zIndex: 20,
                }}>
                    <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                        {Array.from({ length: 3 }).map((_, i) => (
                            <div key={i} style={{
                                flex: 1, height: 1,
                                background: i === 1 ? "#2a2a2a" : "#1a1a1a",
                            }} />
                        ))}
                        <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{ opacity: 0.4 }}>
                            <polygon points="5,0 10,10 0,10" stroke="white" strokeWidth="1" fill="none" />
                        </svg>
                        {Array.from({ length: 3 }).map((_, i) => (
                            <div key={i} style={{
                                flex: 1, height: 1,
                                background: i === 1 ? "#2a2a2a" : "#1a1a1a",
                            }} />
                        ))}
                    </div>
                </div>

                {/* 5 ── TEAR LINE */}
                <div style={{ padding: "18px 10px 14px", position: "relative", zIndex: 20 }}>
                    <TearLine />
                </div>

                {/* 5 ── FOOTER STRIP */}
                <div style={{
                    padding: "8px 28px 22px",
                    position: "relative", zIndex: 20,
                    display: "flex", alignItems: "center", justifyContent: "space-between",
                }}>
                    {/* Barcode */}
                    <div>
                        <Barcode />
                        <div style={{ fontSize: 7, color: "#333", letterSpacing: "0.16em", marginTop: 3 }}>
                            NX-9912-DELTA-44-0x2F
                        </div>
                    </div>
                    {/* Footer icons & stamp */}
                    <div style={{ textAlign: "right" }}>
                        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", marginBottom: 6 }}>
                            {["★", "◈", "▲"].map((icon, i) => (
                                <span key={i} style={{
                                    fontSize: i === 0 ? 11 : 9, color: "#444",
                                    fontFamily: "monospace",
                                }}>{icon}</span>
                            ))}
                        </div>
                        <div style={{
                            fontSize: 7, color: "#3a3a3a", letterSpacing: "0.2em",
                            textTransform: "uppercase", lineHeight: 1.6,
                        }}>
                            ADMIT<br />ONE
                        </div>
                    </div>
                </div>

                {/* subtle bottom vignette */}
                <div style={{
                    position: "absolute", bottom: 0, left: 0, right: 0, height: 80,
                    background: "linear-gradient(to top, rgba(0,0,0,0.55), transparent)",
                    pointerEvents: "none", zIndex: 8,
                }} />
            </div>

            {/* ambient page label */}
            <div style={{
                position: "absolute", bottom: 18, left: "50%", transform: "translateX(-50%)",
                fontSize: 8, letterSpacing: "0.3em", color: "#2a2a2a",
                fontFamily: "'IBM Plex Mono', monospace", textTransform: "uppercase",
                zIndex: 20,
            }}>
                NEXUS PROTOCOL — DOCUMENT RENDER v9.1 — CLASSIFIED
            </div>
        </div>
    );
}