---
import BaseLayout from '../layouts/BaseLayout.astro';
import { SITE_TITLE } from '../consts';
import { getEntry } from 'astro:content';

const pageTitle = `Contact | ${SITE_TITLE}`;

// Fetch contact page content
const contactEntry = await getEntry('pages', 'contact');
const contactContent = contactEntry.data;
---

<BaseLayout title={pageTitle} description="Get in touch for collaboration or inquiries." usePadding={false}>

    <!-- Background Grid (Optional, low opacity) -->
    <div class="fixed inset-0 z-0 pointer-events-none">
        <div class="w-full h-full grid grid-cols-12 gap-4 opacity-[0.03]">
            {Array.from({ length: 12 }).map((_) => (
                <div class="h-full border-r border-[var(--theme-text-primary)]"></div>
            ))}
        </div>
    </div>

    <!-- Hero Section -->
    <section class="relative z-10 pt-32 lg:pt-40 pb-16 lg:pb-20 overflow-hidden px-6 lg:px-12">
        <!-- Floating accent orb -->
        <div class="absolute top-0 right-1/4 w-64 h-64 bg-brand-accent/5 rounded-full blur-3xl pointer-events-none"></div>

        <div class="container mx-auto relative z-10">
            <!-- Main Hero Content -->
            <div>
                <div class="max-w-5xl">
                    <!-- Small label -->
                    <div class="flex items-center gap-3 mb-8">
                        <div class="w-1.5 h-1.5 bg-brand-accent rounded-full"></div>
                        <span class="text-xs font-medium uppercase tracking-[0.2em] text-[var(--theme-text-muted)]">Get In Touch</span>
                    </div>

                    <!-- Main Title -->
                    <h1 class="text-6xl md:text-8xl lg:text-9xl font-bold tracking-tighter leading-[0.9] mb-8">
                        <span class="block text-[var(--theme-text-primary)]">Let's</span>
                        <span class="block bg-gradient-to-r from-brand-accent to-brand-accent/70 bg-clip-text text-transparent">Connect</span>
                    </h1>

                    <!-- Description -->
                    <p class="text-xl md:text-2xl text-[var(--theme-text-secondary)] font-light leading-relaxed max-w-2xl">
                        {contactContent.availabilityText}
                    </p>
                </div>

                <!-- Stats Row -->
                <div class="flex items-center gap-8 mt-16 pt-8 border-t border-[var(--theme-border-primary)]">
                    <div class="flex items-center gap-3">
                        <span class="text-3xl font-bold text-brand-accent">Open</span>
                        <span class="text-xs uppercase tracking-widest text-[var(--theme-text-muted)]">To Work</span>
                    </div>
                    <div class="w-px h-8 bg-[var(--theme-border-primary)]"></div>
                    <div class="flex items-center gap-3">
                        <span class="text-3xl font-bold text-[var(--theme-text-primary)]">24h</span>
                        <span class="text-xs uppercase tracking-widest text-[var(--theme-text-muted)]">Response</span>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <section class="relative z-10 flex flex-col pb-20 px-6 lg:px-12">

        <div class="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-24 flex-grow">

            <!-- Left Column: Contact Form -->
            <div class="lg:col-span-7">
                <div class="mb-12 flex items-center gap-3">
                    <span class="w-1.5 h-1.5 bg-brand-accent rounded-full animate-pulse"></span>
                    <span class="font-mono text-[10px] text-brand-accent uppercase tracking-[0.2em] font-bold">/// TRANSMISSION_LOG</span>
                </div>

                <form id="contact-form" class="space-y-12">
                    <div class="group relative">
                        <input
                            type="text"
                            id="name"
                            name="name"
                            class="block w-full bg-transparent border-b border-[var(--theme-border-strong)] py-4 text-xl text-[var(--theme-text-primary)] focus:outline-none focus:border-brand-accent transition-colors duration-300 placeholder-transparent peer"
                            placeholder="Name"
                            required
                        />
                        <label for="name" class="absolute left-0 top-4 text-[var(--theme-text-muted)] text-[10px] font-mono uppercase tracking-[0.2em] transition-all duration-300 peer-focus:-top-6 peer-focus:text-brand-accent peer-valid:-top-6 peer-valid:text-[var(--theme-text-secondary)] pointer-events-none">
                            {contactContent.formLabels?.name}
                        </label>
                    </div>

                    <div class="group relative">
                        <input
                            type="email"
                            id="email"
                            name="email"
                            class="block w-full bg-transparent border-b border-[var(--theme-border-strong)] py-4 text-xl text-[var(--theme-text-primary)] focus:outline-none focus:border-brand-accent transition-colors duration-300 placeholder-transparent peer"
                            placeholder="Email"
                            required
                        />
                        <label for="email" class="absolute left-0 top-4 text-[var(--theme-text-muted)] text-[10px] font-mono uppercase tracking-[0.2em] transition-all duration-300 peer-focus:-top-6 peer-focus:text-brand-accent peer-valid:-top-6 peer-valid:text-[var(--theme-text-secondary)] pointer-events-none">
                            {contactContent.formLabels?.email}
                        </label>
                    </div>

                    <!-- Custom Dropdown -->
                    <div class="group relative" id="custom-select">
                        <input type="hidden" name="subject" id="subject-input" required>

                        <button type="button" id="select-trigger" class="block w-full text-left bg-transparent border-b border-[var(--theme-border-strong)] py-4 text-xl text-[var(--theme-text-primary)] focus:outline-none focus:border-brand-accent transition-colors duration-300 flex justify-between items-center group-hover:border-brand-accent/30">
                            <span id="select-value" class="text-transparent">Select</span> <!-- Hidden placeholder text to keep height -->
                            <div class="text-brand-accent transform transition-transform duration-300" id="select-arrow">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="square" stroke-linejoin="miter"><path d="m6 9 6 6 6-6"/></svg>
                            </div>
                        </button>

                        <label id="select-label" class="absolute left-0 top-4 text-[var(--theme-text-muted)] text-[10px] font-mono uppercase tracking-[0.2em] transition-all duration-300 pointer-events-none">
                            {contactContent.formLabels?.subject}
                        </label>

                        <!-- Dropdown Menu -->
                        <div id="select-options" class="absolute left-0 top-full w-full bg-[var(--theme-bg-primary)] border border-brand-accent/30 shadow-2xl z-50 hidden opacity-0 transform translate-y-2 transition-all duration-200 origin-top mt-2 backdrop-blur-xl">
                            <div class="p-1">
                                {contactContent.subjectOptions?.map((option) => (
                                    <div class="option px-5 py-4 hover:bg-brand-accent/5 cursor-pointer text-[var(--theme-text-primary)] text-lg font-light transition-colors flex items-center gap-3 group/option" data-value={option.value}>
                                        <span class="w-1.5 h-1.5 rounded-full bg-brand-accent opacity-0 group-hover/option:opacity-100 transition-opacity"></span>
                                        {option.label}
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>

                    <div class="group relative">
                        <textarea
                            id="message"
                            name="message"
                            rows="4"
                            class="block w-full bg-transparent border-b border-[var(--theme-border-strong)] py-4 text-xl text-[var(--theme-text-primary)] focus:outline-none focus:border-brand-accent transition-colors duration-300 placeholder-transparent peer resize-none"
                            placeholder="Message"
                            required
                        ></textarea>
                        <label for="message" class="absolute left-0 top-4 text-[var(--theme-text-muted)] text-[10px] font-mono uppercase tracking-[0.2em] transition-all duration-300 peer-focus:-top-6 peer-focus:text-brand-accent peer-valid:-top-6 peer-valid:text-[var(--theme-text-secondary)] pointer-events-none">
                            {contactContent.formLabels?.message}
                        </label>
                    </div>

                    <div class="pt-8">
                        <button type="submit" id="submit-btn" class="group relative inline-flex items-center justify-center gap-6 px-8 py-4 bg-brand-accent/5 border border-brand-accent/30 hover:bg-brand-accent hover:border-brand-accent transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed overflow-hidden rounded-full">
                            <span id="submit-text" data-default-text={contactContent.formLabels?.submit} class="relative z-10 font-mono text-xs font-bold uppercase tracking-[0.2em] text-brand-accent group-hover:text-brand-dark transition-colors">{contactContent.formLabels?.submit}</span>
                            <div class="relative z-10 w-8 h-8 flex items-center justify-center border border-brand-accent/20 group-hover:border-brand-dark/30 transition-colors">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="square" stroke-linejoin="miter" class="text-brand-accent group-hover:text-brand-dark group-hover:translate-x-1 transition-all">
                                    <path d="M5 12h14M12 5l7 7-7 7"/>
                                </svg>
                            </div>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Right Column: System Status / Info -->
            <div class="lg:col-span-5 space-y-16 lg:pt-24">

                <!-- Data Block 1 -->
                <div class="relative pl-6 border-l border-brand-accent/30 group">
                    <h3 class="font-mono text-[10px] text-[var(--theme-text-muted)] uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
                        <span class="text-brand-accent">/</span> DIRECT_LINK
                    </h3>
                    <a href={`mailto:${contactContent.email}`} class="text-2xl md:text-3xl font-bold text-[var(--theme-text-primary)] hover:text-brand-accent transition-colors break-all uppercase tracking-tight">
                        {contactContent.email}
                    </a>
                </div>

                <!-- Data Block 2 -->
                <div class="relative pl-6 border-l border-brand-accent/30 group">
                    <h3 class="font-mono text-[10px] text-[var(--theme-text-muted)] uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
                        <span class="text-brand-accent">/</span> GEOSPATIAL_COORDS
                    </h3>
                    <p class="text-xl text-[var(--theme-text-primary)] font-bold uppercase tracking-tight mb-2">
                        {contactContent.location}<br>
                        <span class="text-[var(--theme-text-muted)] text-sm tracking-widest">{contactContent.locationCountry}</span>
                    </p>
                    <div class="font-mono text-xs text-brand-accent/60 group-hover:text-brand-accent transition-colors">
                        {contactContent.coordinates}
                    </div>
                </div>

                <!-- Data Block 3 -->
                <div class="relative pl-6 border-l border-brand-accent/30">
                    <h3 class="font-mono text-[10px] text-[var(--theme-text-muted)] uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
                        <span class="text-brand-accent">/</span> SOCIAL_MANIFEST
                    </h3>
                    <ul class="space-y-4">
                        {contactContent.socialLinks?.map((link, idx) => (
                            <li class="group/social">
                                <a href={link.url} class="flex items-center gap-4">
                                    <span class="font-mono text-[9px] text-brand-accent opacity-0 group-hover/social:opacity-100 transition-opacity">[SIG.0{idx + 1}]</span>
                                    <span class="text-[var(--theme-text-secondary)] group-hover/social:text-brand-accent transition-colors text-xl font-bold uppercase tracking-tight">{link.name}</span>
                                    <div class="w-1.5 h-1.5 rounded-full bg-brand-accent/20 group-hover/social:bg-brand-accent transition-all"></div>
                                </a>
                            </li>
                        ))}
                    </ul>
                </div>

            </div>
        </div>

    </section>

    <!-- Toast Notification Container -->
    <div id="toast-container" class="fixed top-6 right-6 z-50 pointer-events-none"></div>

    <!-- Full-Screen Modal for Loading and Response -->
    <div id="transmission-modal" class="fixed inset-0 z-[100] flex items-center justify-center bg-[var(--theme-bg-primary)]/95 backdrop-blur-2xl opacity-0 pointer-events-none transition-opacity duration-500">
        <!-- Technical Grid Overlay for Modal -->
        <div class="absolute inset-0 z-0 pointer-events-none opacity-[0.03] bg-[linear-gradient(rgba(18,16,16,0)_50%,rgba(0,0,0,0.25)_50%),linear-gradient(90deg,rgba(255,0,0,0.06),rgba(0,255,0,0.02),rgba(0,0,112,0.06))] bg-[length:100%_2px,3px_100%]"></div>

        <!-- Loading State -->
        <div id="loading-state" class="relative z-10 text-center">
            <!-- Animated Transmission Graphic -->
            <div class="relative w-40 h-40 mx-auto mb-16">
                <!-- Outer rotating ring -->
                <div class="absolute inset-0 border border-brand-accent/20 rounded-full animate-spin-slow"></div>
                <!-- Middle pulsing ring -->
                <div class="absolute inset-6 border border-brand-accent/40 rounded-full animate-pulse"></div>
                <!-- Inner dot -->
                <div class="absolute inset-0 flex items-center justify-center">
                    <div class="w-6 h-6 bg-brand-accent rounded-full animate-ping opacity-40"></div>
                    <div class="w-2 h-2 bg-brand-accent rounded-full absolute"></div>
                </div>
                <!-- Scanning bars -->
                <div class="absolute inset-0 overflow-hidden rounded-full">
                    <div class="w-full h-full bg-gradient-to-b from-transparent via-brand-accent/10 to-transparent animate-scan-sweep-vertical"></div>
                </div>
            </div>

            <!-- Loading Text -->
            <div class="space-y-6">
                <div class="flex items-center justify-center gap-3">
                    <div class="w-1.5 h-1.5 bg-brand-accent animate-pulse"></div>
                    <h2 class="text-4xl md:text-6xl font-bold text-[var(--theme-text-primary)] uppercase tracking-tighter">
                        <span id="loading-text">TRANSMITTING</span>
                    </h2>
                    <div class="w-1.5 h-1.5 bg-brand-accent animate-pulse"></div>
                </div>
                <div class="font-mono text-[10px] text-brand-accent uppercase tracking-[0.4em] flex items-center justify-center gap-4">
                    <span class="opacity-40">ENCRYPTING_PACKETS</span>
                    <span class="w-8 h-px bg-brand-accent/20"></span>
                    <span class="animate-pulse">STABLIZING_UPLINK</span>
                </div>
            </div>
        </div>

        <!-- Response State (hidden initially) -->
        <div id="response-state" class="hidden w-full h-full absolute inset-0 z-20 flex flex-col items-center justify-center p-6 lg:p-12 opacity-0 transition-all duration-700">
            <!-- Close button -->
            <button id="close-modal" class="absolute top-12 right-12 z-50 group flex items-center gap-4">
                <span class="font-mono text-[10px] text-[var(--theme-text-muted)] uppercase tracking-[0.2em] group-hover:text-brand-accent transition-colors">Terminate_Session [ESC]</span>
                <div class="w-10 h-10 flex items-center justify-center border border-[var(--theme-border-strong)] group-hover:border-brand-accent group-hover:bg-brand-accent/5 transition-all">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="square" stroke-linejoin="miter" class="text-[var(--theme-text-primary)] group-hover:text-brand-accent transition-colors">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </div>
            </button>

            <!-- Content Container -->
            <div class="w-full max-w-6xl mx-auto flex flex-col items-center relative">
                
                <!-- Response content - The Focal Point -->
                <div class="w-full relative bg-white/[0.01] border border-white/5 backdrop-blur-sm p-8 md:p-16 lg:p-24">
                    <!-- Technical Corner Accents -->
                    <div class="absolute -top-px -left-px w-12 h-12 border-t-2 border-l-2 border-brand-accent"></div>
                    <div class="absolute -top-px -right-px w-12 h-12 border-t-2 border-r-2 border-brand-accent"></div>
                    <div class="absolute -bottom-px -left-px w-12 h-12 border-b-2 border-l-2 border-brand-accent"></div>
                    <div class="absolute -bottom-px -right-px w-12 h-12 border-b-2 border-r-2 border-brand-accent"></div>

                    <!-- Header -->
                    <div class="flex items-center gap-4 mb-12">
                        <div class="w-2 h-2 bg-brand-accent animate-pulse"></div>
                        <span class="font-mono text-[10px] text-brand-accent uppercase tracking-[0.4em]">INCOMING_RESPONSE /// MSG.ID_ACK</span>
                    </div>

                    <!-- Content -->
                    <div id="response-content" class="prose-response max-h-[60vh] overflow-y-auto custom-scrollbar pr-4"></div>
                </div>
            </div>
        </div>
    </div>
</BaseLayout>

<style>
    /* Custom autofill styles to match theme */
    input:-webkit-autofill,
    input:-webkit-autofill:hover,
    input:-webkit-autofill:focus,
    textarea:-webkit-autofill,
    textarea:-webkit-autofill:hover,
    textarea:-webkit-autofill:focus {
        -webkit-text-fill-color: var(--theme-text-primary);
        -webkit-box-shadow: 0 0 0px 1000px var(--theme-bg-primary) inset;
        transition: background-color 5000s ease-in-out 0s;
    }

    /* Label active state */
    .label-active {
        top: -1.5rem !important;
        font-size: 0.75rem !important;
        color: var(--theme-text-secondary) !important;
    }

    /* Dropdown open state */
    .dropdown-open #select-arrow {
        transform: rotate(180deg);
        color: var(--theme-text-primary);
    }

    /* Custom Animations */
    @keyframes spin-slow {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    @keyframes scan-sweep-vertical {
        0% { transform: translateY(-100%); opacity: 0; }
        50% { opacity: 1; }
        100% { transform: translateY(100%); opacity: 0; }
    }

    @keyframes scale-in {
        0% {
            transform: scale(0.9);
            opacity: 0;
        }
        100% {
            transform: scale(1);
            opacity: 1;
        }
    }

    .animate-spin-slow {
        animation: spin-slow 8s linear infinite;
    }

    .animate-scan-sweep-vertical {
        animation: scan-sweep-vertical 2s ease-in-out infinite;
    }

    .animate-scale-in {
        animation: scale-in 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }

    .delay-100 {
        animation-delay: 100ms;
    }

    .delay-150 {
        animation-delay: 150ms;
    }

    .delay-200 {
        animation-delay: 200ms;
    }

    /* Custom Scrollbar */
    .custom-scrollbar::-webkit-scrollbar {
        width: 8px;
    }

    .custom-scrollbar::-webkit-scrollbar-track {
        background: var(--theme-hover-bg-strong);
    }

    .custom-scrollbar::-webkit-scrollbar-thumb {
        background: var(--color-brand-accent);
        border-radius: 4px;
        opacity: 0.3;
    }

    .custom-scrollbar::-webkit-scrollbar-thumb:hover {
        opacity: 0.5;
    }

    /* Response Content Prose Styles - Enhanced Readability */
    .prose-response {
        color: var(--theme-text-primary);
        text-align: left;
    }

    .prose-response h1,
    .prose-response h2,
    .prose-response h3 {
        color: var(--theme-text-primary);
        margin-top: 1.5em;
        margin-bottom: 0.75em;
        font-weight: 800;
        line-height: 1.1;
        letter-spacing: -0.02em;
        text-transform: uppercase;
    }

    .prose-response h1 {
        font-size: 2.5rem;
        background: linear-gradient(to right, var(--theme-text-primary), var(--color-brand-accent));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 0.5em;
    }

    .prose-response h2 {
        font-size: 1.75rem;
        border-bottom: 1px solid var(--theme-border-primary);
        padding-bottom: 0.5rem;
    }

    .prose-response h3 {
        font-size: 1.25rem;
        color: var(--color-brand-accent);
    }

    .prose-response p {
        margin-bottom: 1.5em;
        line-height: 1.7;
        color: var(--theme-text-secondary);
        font-size: 1.125rem;
        font-weight: 400;
        max-width: 75ch;
        margin-right: auto;
    }

    .prose-response strong {
        color: var(--theme-text-primary);
        font-weight: 700;
    }

    .prose-response ul, .prose-response ol {
        margin-bottom: 1.5em;
        space-y: 0.5em;
    }

    .prose-response li {
        position: relative;
        padding-left: 1.5rem;
        color: var(--theme-text-secondary);
    }

    .prose-response li::before {
        content: "///";
        position: absolute;
        left: 0;
        color: var(--color-brand-accent);
        font-family: var(--font-mono);
        font-size: 0.75rem;
        font-weight: 700;
    }

    .prose-response em {
        font-style: italic;
        color: var(--theme-text-muted);
    }

    /* Blockquote for signature or special text */
    .prose-response blockquote {
        border-left: none;
        margin: 3em 0 1em;
        padding: 0;
        color: var(--color-brand-accent);
        font-family: 'Courier New', monospace;
        font-size: 1rem;
        text-transform: uppercase;
        letter-spacing: 0.2em;
        display: inline-block;
        border-top: 1px solid rgba(221, 65, 50, 0.3);
        padding-top: 2em;
    }

    .prose-response a {
        color: var(--color-brand-accent);
        text-decoration: underline;
        text-underline-offset: 4px;
        transition: all 0.3s;
    }

    .prose-response a:hover {
        color: var(--theme-text-primary);
        text-decoration-thickness: 2px;
    }

    /* Mobile adjustments */
    @media (max-width: 768px) {
        .prose-response h1 {
            font-size: 2.5rem;
        }
        .prose-response p {
            font-size: 1.125rem;
        }
    }
</style>

<script>
    // ===== Custom Dropdown Logic =====
    const selectContainer = document.getElementById('custom-select');
    const selectTrigger = document.getElementById('select-trigger');
    const selectOptions = document.getElementById('select-options');
    const selectValue = document.getElementById('select-value');
    const hiddenInput = document.getElementById('subject-input') as HTMLInputElement;
    const selectLabel = document.getElementById('select-label');
    const options = document.querySelectorAll('.option');
    const arrow = document.getElementById('select-arrow');

    if (selectTrigger && selectOptions && selectValue && hiddenInput && selectLabel) {

        // Toggle Dropdown
        selectTrigger.addEventListener('click', () => {
            const isOpen = !selectOptions.classList.contains('hidden');

            if (isOpen) {
                closeDropdown();
            } else {
                openDropdown();
            }
        });

        // Option Selection
        options.forEach(option => {
            option.addEventListener('click', (e) => {
                const target = e.currentTarget as HTMLElement;
                const value = target.dataset.value || '';
                const text = target.innerText;

                // Update UI
                selectValue.textContent = text;
                selectValue.classList.remove('text-transparent');
                selectValue.classList.add('text-[var(--theme-text-primary)]');

                // Update Data
                hiddenInput.value = value;

                // Update Label Style
                selectLabel.classList.add('label-active');
                selectLabel.classList.add('text-brand-accent');

                closeDropdown();
            });
        });

        // Close clicking outside
        document.addEventListener('click', (e) => {
            if (selectContainer && !selectContainer.contains(e.target as Node)) {
                closeDropdown();
            }
        });

        function openDropdown() {
            selectOptions?.classList.remove('hidden');
            // Small delay for opacity transition
            requestAnimationFrame(() => {
                selectOptions?.classList.remove('opacity-0', 'translate-y-2');
            });
            selectContainer?.classList.add('dropdown-open');
        }

        function closeDropdown() {
            selectOptions?.classList.add('opacity-0', 'translate-y-2');
            setTimeout(() => {
                selectOptions?.classList.add('hidden');
            }, 200);
            selectContainer?.classList.remove('dropdown-open');
        }
    }

    // ===== Toast Notification System =====
    function showToast(message: string, type: 'success' | 'error' = 'error') {
        const container = document.getElementById('toast-container');
        if (!container) return;

        const toast = document.createElement('div');
        toast.className = `pointer-events-auto mb-4 p-4 border backdrop-blur-sm transform transition-all duration-300 translate-x-full opacity-0 ${
            type === 'success'
                ? 'bg-green-500/10 border-green-500/30 text-green-400'
                : 'bg-red-500/10 border-red-500/30 text-red-400'
        }`;
        toast.setAttribute('role', 'alert');
        toast.innerHTML = `
            <div class="flex items-start gap-3 max-w-sm">
                <div class="flex-shrink-0">
                    ${type === 'success'
                        ? '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>'
                        : '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>'
                    }
                </div>
                <p class="text-sm font-mono">${message}</p>
            </div>
        `;

        container.appendChild(toast);

        // Trigger animation
        requestAnimationFrame(() => {
            toast.classList.remove('translate-x-full', 'opacity-0');
        });

        // Auto-dismiss after 6 seconds
        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => toast.remove(), 300);
        }, 6000);
    }

    // ===== Modal Control Functions =====
    const transmissionModal = document.getElementById('transmission-modal') as HTMLDivElement;
    const loadingState = document.getElementById('loading-state') as HTMLDivElement;
    const responseState = document.getElementById('response-state') as HTMLDivElement;
    const closeModalBtn = document.getElementById('close-modal') as HTMLButtonElement;

    function openModal() {
        transmissionModal.classList.remove('pointer-events-none', 'opacity-0');
        transmissionModal.classList.add('pointer-events-auto', 'opacity-100');
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        transmissionModal.classList.add('pointer-events-none', 'opacity-0');
        transmissionModal.classList.remove('pointer-events-auto', 'opacity-100');
        document.body.style.overflow = '';

        // Reset states after animation
        setTimeout(() => {
            loadingState.classList.remove('hidden');
            responseState.classList.add('hidden');
            responseState.classList.remove('opacity-100', 'scale-100');
            responseState.classList.add('opacity-0', 'scale-95');
        }, 500);
    }

    function showResponse() {
        loadingState.classList.add('hidden');
        responseState.classList.remove('hidden');

        // Trigger animation after a brief delay
        setTimeout(() => {
            responseState.classList.remove('opacity-0', 'scale-95');
            responseState.classList.add('opacity-100', 'scale-100');
        }, 100);
    }

    // Modal close handler
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', closeModal);
    }

    // Close on click outside
    if (transmissionModal) {
        transmissionModal.addEventListener('click', (e) => {
            const target = e.target as HTMLElement;
            
            // Only close if response state is active and visible
            // We check if the click target is the container itself (the background)
            // response-state covers the whole screen when active
            if (!responseState.classList.contains('hidden') && 
                (target === responseState || target === transmissionModal)) {
                closeModal();
            }
        });
    }

    // ===== Form Submission Handler =====
    const contactForm = document.getElementById('contact-form') as HTMLFormElement;
    const submitBtn = document.getElementById('submit-btn') as HTMLButtonElement;
    const submitText = document.getElementById('submit-text') as HTMLSpanElement;
    const responseContent = document.getElementById('response-content') as HTMLDivElement;

    if (contactForm && submitBtn && submitText && responseContent && transmissionModal) {
        contactForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            // Get form data
            const formData = new FormData(contactForm);
            const payload = {
                name: formData.get('name') as string,
                email: formData.get('email') as string,
                subject: formData.get('subject') as string,
                message: formData.get('message') as string,
                timestamp: new Date().toISOString(),
                source: 'portfolio-website'
            };

            // Open modal with loading state
            openModal();

            // Disable submit button
            submitBtn.disabled = true;
            submitText.textContent = 'Transmitting...';

            try {
                // Create abort controller for timeout
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout

                // Make the request
                const response = await fetch(import.meta.env.PUBLIC_N8N_WEBHOOK_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload),
                    signal: controller.signal
                });

                clearTimeout(timeoutId);

                // Check for non-2xx response
                if (!response.ok) {
                    throw new Error(`Server returned ${response.status}`);
                }

                // Parse response
                const data = await response.json();

                // Check if n8n returned an error
                if (data.success === false) {
                    throw new Error(data.error || 'An error occurred processing your message');
                }

                // Success path - render markdown response
                if (data.success && data.format === 'mdx' && data.message) {
                    try {
                        // Lazy-load markdown renderer only when needed (keeps initial JS lighter)
                        const { marked } = await import('marked');
                        const htmlContent = await marked.parse(data.message);
                        responseContent.innerHTML = htmlContent;

                        // Show response state with animation
                        showResponse();

                        // Reset button state
                        submitText.textContent = submitText.getAttribute('data-default-text') || 'Transmit Message';
                        submitBtn.disabled = false;

                    } catch (markdownError) {
                        console.error('Markdown parsing error:', markdownError);
                        // Fallback: show plain text instead of failing the whole interaction.
                        responseContent.textContent = String(data.message);
                        showResponse();
                    }
                } else {
                    throw new Error('Invalid response format from server');
                }

            } catch (error) {
                console.error('Form submission error:', error);

                // Close modal
                closeModal();

                // Determine error message
                let errorMessage = 'We couldn\'t reach the messaging system. Please try again or email me directly at nicholai@nicholai.work';

                if (error instanceof Error) {
                    if (error.name === 'AbortError') {
                        errorMessage = 'Request timed out. Please try again or email me directly at nicholai@nicholai.work';
                    } else if (error.message && !error.message.includes('Server returned')) {
                        errorMessage = error.message;
                    }
                }

                // Show error toast
                showToast(errorMessage, 'error');

                // Update button to failure state
                submitText.textContent = 'Transmission Failed';
                const defaultText = submitText.getAttribute('data-default-text') || 'Transmit Message';
                setTimeout(() => {
                    submitText.textContent = defaultText;
                    submitBtn.disabled = false;
                }, 2000);

                // Keep form data intact (don't reset)
            }
        });
    }
</script>
