<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shomotion AI - TouchReveal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                        display: ['Space Grotesk', 'sans-serif'],
                    },
                    colors: {
                        primary: {
                            50: '#f5f3ff', 100: '#ede9fe', 200: '#ddd6fe',
                            300: '#c4b5fd', 400: '#a78bfa', 500: '#8b5cf6',
                            600: '#7c3aed', 700: '#6d28d9', 800: '#5b21b6',
                            900: '#4c1d95', 950: '#2e1065',
                        }
                    }
                }
            }
        }
    </script>
    
    <style>
        body { 
            background-color: #050505; 
            color: #fafafa;
            font-family: 'Inter', sans-serif;
            overflow-x: hidden;
        }
        
        .noise-overlay {
            position: fixed; top: 0; left: 0;
            width: 100%; height: 100%;
            pointer-events: none; z-index: 50; opacity: 0.015;
            background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
        }

        .orb {
            position: absolute; border-radius: 50%;
            filter: blur(80px); opacity: 0.35; pointer-events: none;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-12px); }
        }

        .glow-purple { box-shadow: 0 0 60px -15px rgba(139, 92, 246, 0.5); }
        
        .pricing-card {
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .pricing-card:hover { transform: translateY(-8px); }
        
        .feature-icon {
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.2), rgba(139, 92, 246, 0.05));
        }
        
        .font-display { font-family: 'Space Grotesk', sans-serif; }
        
        .gradient-text {
            background: linear-gradient(135deg, #fff 0%, #a78bfa 50%, #fff 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-size: 200% auto;
            animation: shimmer 3s linear infinite;
        }
        
        @keyframes shimmer {
            0% { background-position: -200% 0; }
            100% { background-position: 200% 0; }
        }
        
        .glass-panel {
            background: rgba(255, 255, 255, 0.03);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .hero-carousel {
            width: 100vw;
            margin-left: calc(-50vw + 50%);
            padding: 30px 0;
            perspective: 900px;
            -webkit-mask-image: linear-gradient(90deg, transparent, black 8%, black 92%, transparent);
            mask-image: linear-gradient(90deg, transparent, black 8%, black 92%, transparent);
        }
        .hero-track {
            display: flex;
            align-items: center;
            gap: 6px;
            width: max-content;
            height: 360px;
            transform-style: preserve-3d;
            animation: hero-scroll 48s linear infinite;
            will-change: transform;
        }
        .hero-carousel:hover .hero-track { animation-play-state: paused; }
        @keyframes hero-scroll {
            from { transform: translateX(0); }
            to { transform: translateX(-50%); }
        }
        .hero-card {
            position: relative;
            flex: 0 0 auto;
            width: 210px;
            height: 320px;
            border-radius: 16px;
            overflow: hidden;
            border: 1px solid rgba(255,255,255,0.08);
            background: #0c0c0f;
            background-size: cover;
            background-position: center;
            transform-style: preserve-3d;
            transition: box-shadow 0.4s;
        }
        .hero-card img,
        .hero-card video {
            width: 100%; height: 100%; object-fit: cover; display: block;
            filter: saturate(1.05);
        }
        .hero-card:hover { filter: brightness(1) !important; z-index: 5; }
        .hero-card.glow-card {
            box-shadow: 0 0 70px -6px rgba(139,92,246,0.7);
            border-color: rgba(139,92,246,0.55);
        }
        @media (max-width: 768px) {
            .hero-card { width: 130px; height: 200px; }
            .hero-track { height: 200px; }
            .hero-carousel { padding: 20px 0; perspective: 600px; }
        }


        .template-card {
            position: relative;
            overflow: hidden;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .template-card:hover {
            transform: translateY(-8px) scale(1.02);
            box-shadow: 0 20px 40px -15px rgba(139, 92, 246, 0.4);
            border-color: rgba(139, 92, 246, 0.5);
        }
        
        .template-card .card-image {
            transition: transform 0.6s cubic-bezier(0.4, 0, 0.2, 1);
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .template-card:hover .card-image {
            transform: scale(1.05);
        }

        .card-media-wrap {
            position: relative;
            aspect-ratio: 16 / 9;
            overflow: hidden;
            background: #0a0a0a;
        }

        .card-preview-video {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            opacity: 0;
            transition: opacity 0.5s ease;
        }

        .card-preview-video.playing {
            opacity: 1;
        }

        .card-image {
            transition: opacity 0.5s ease;
        }

        .card-image.hidden-by-video {
            opacity: 0;
        }

        .upload-overlay {
            position: absolute;
            inset: 0;
            background: rgba(0, 0, 0, 0.82);
            backdrop-filter: blur(10px);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.25s ease;
            cursor: pointer;
        }

        .upload-overlay.visible {
            opacity: 1;
            pointer-events: auto;
        }

        .upload-icon {
            width: 64px;
            height: 64px;
            border-radius: 50%;
            background: linear-gradient(135deg, #8b5cf6, #7c3aed);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
            transform: translateY(16px);
            opacity: 0;
            transition: all 0.3s ease 0.05s;
        }

        .upload-overlay.visible .upload-icon {
            transform: translateY(0);
            opacity: 1;
        }

        .upload-text {
            color: white;
            font-weight: 600;
            font-size: 1.125rem;
            transform: translateY(16px);
            opacity: 0;
            transition: all 0.3s ease 0.1s;
        }

        .upload-overlay.visible .upload-text {
            transform: translateY(0);
            opacity: 1;
        }

        .upload-hint {
            color: #9ca3af;
            font-size: 0.875rem;
            margin-top: 8px;
            transform: translateY(16px);
            opacity: 0;
            transition: all 0.3s ease 0.15s;
        }

        .upload-overlay.visible .upload-hint {
            transform: translateY(0);
            opacity: 1;
        }

        .card-play-hint {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background: rgba(0,0,0,0.55);
            border-radius: 8px;
            padding: 4px 10px;
            font-size: 0.7rem;
            color: rgba(255,255,255,0.75);
            opacity: 0;
            transition: opacity 0.3s;
            pointer-events: none;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .template-card:hover .card-play-hint {
            opacity: 1;
        }

        .processing-overlay {
            position: fixed;
            inset: 0;
            background: rgba(5, 5, 5, 0.98);
            backdrop-filter: blur(20px);
            z-index: 100;
            display: none;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        
        .processing-overlay.active {
            display: flex;
        }
        
        .spinner {
            width: 80px;
            height: 80px;
            border: 3px solid rgba(139, 92, 246, 0.2);
            border-top-color: #8b5cf6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* ── Result Page ── */
        .result-modal {
            position: fixed;
            inset: 0;
            background: #030303;
            z-index: 100;
            display: none;
            flex-direction: column;
            overflow-y: auto;
        }
        .result-modal.active { display: flex; }

        .result-modal::before {
            content: '';
            position: fixed;
            inset: 0;
            background: 
                radial-gradient(ellipse 80% 50% at 50% -20%, rgba(124,58,237,0.25) 0%, transparent 60%),
                radial-gradient(ellipse 60% 40% at 80% 100%, rgba(139,92,246,0.15) 0%, transparent 60%);
            pointer-events: none;
            z-index: 0;
        }

        .result-topbar {
            position: fixed;
            top: 0; left: 0; right: 0;
            height: 64px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 2rem;
            background: rgba(3,3,3,0.8);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255,255,255,0.06);
            z-index: 10;
        }

        .result-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 100px 2rem 2rem;
            position: relative;
            z-index: 1;
            min-height: 100vh;
        }

        .video-stage {
            width: 100%;
            max-width: 560px;
            position: relative;
        }

        .video-glow {
            position: absolute;
            inset: -40px;
            background: radial-gradient(ellipse at center, rgba(124,58,237,0.3) 0%, transparent 70%);
            filter: blur(30px);
            pointer-events: none;
            animation: pulseGlow 3s ease-in-out infinite;
        }

        @keyframes pulseGlow {
            0%, 100% { opacity: 0.6; transform: scale(1); }
            50% { opacity: 1; transform: scale(1.05); }
        }

        .video-wrapper {
            position: relative;
            border-radius: 20px;
            overflow: hidden;
            background: #000;
            border: 1px solid rgba(255,255,255,0.1);
            box-shadow: 
                0 0 0 1px rgba(124,58,237,0.3),
                0 40px 80px -20px rgba(0,0,0,0.8),
                inset 0 1px 0 rgba(255,255,255,0.08);
            aspect-ratio: 16 / 9;
        }

        #result-video {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            display: block;
            object-fit: contain;
            border-radius: 20px;
        }

        /* Custom video controls overlay */
        .video-controls {
            position: absolute;
            bottom: 0; left: 0; right: 0;
            padding: 40px 20px 20px;
            background: linear-gradient(to top, rgba(0,0,0,0.9) 0%, transparent 100%);
            opacity: 0;
            transition: opacity 0.3s ease;
            display: flex;
            flex-direction: column;
            gap: 10px;
            z-index: 10;
            border-radius: 0 0 20px 20px;
        }

        .video-wrapper:hover .video-controls { opacity: 1; }

        .progress-track {
            width: 100%;
            height: 3px;
            background: rgba(255,255,255,0.2);
            border-radius: 2px;
            cursor: pointer;
            position: relative;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #7c3aed, #a78bfa);
            border-radius: 2px;
            width: 0%;
            transition: width 0.1s linear;
            position: relative;
        }

        .progress-fill::after {
            content: '';
            position: absolute;
            right: -5px; top: -4px;
            width: 11px; height: 11px;
            border-radius: 50%;
            background: white;
            box-shadow: 0 0 8px rgba(124,58,237,0.8);
            opacity: 0;
            transition: opacity 0.2s;
        }

        .progress-track:hover .progress-fill::after { opacity: 1; }

        .controls-row {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .ctrl-btn {
            width: 36px; height: 36px;
            border-radius: 50%;
            border: none;
            background: rgba(255,255,255,0.1);
            color: white;
            cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: all 0.2s;
            flex-shrink: 0;
        }
        .ctrl-btn:hover { background: rgba(255,255,255,0.2); transform: scale(1.1); }

        .time-display {
            color: rgba(255,255,255,0.7);
            font-size: 0.8rem;
            font-family: 'SF Mono', monospace;
            margin-left: auto;
        }

        .result-actions {
            display: flex;
            gap: 12px;
            margin-top: 24px;
            width: 100%;
            max-width: 560px;
        }

        .action-btn {
            flex: 1;
            padding: 14px 24px;
            border-radius: 12px;
            font-weight: 600;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex; align-items: center; justify-content: center; gap: 8px;
            border: none;
            letter-spacing: 0.02em;
        }

        .action-btn.primary {
            background: linear-gradient(135deg, #7c3aed, #6d28d9);
            color: white;
            box-shadow: 0 4px 20px rgba(124,58,237,0.4);
        }
        .action-btn.primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(124,58,237,0.5);
        }

        .action-btn.secondary {
            background: rgba(255,255,255,0.05);
            color: rgba(255,255,255,0.8);
            border: 1px solid rgba(255,255,255,0.1);
        }
        .action-btn.secondary:hover {
            background: rgba(255,255,255,0.1);
            transform: translateY(-2px);
        }

        .result-meta {
            display: flex;
            gap: 24px;
            margin-top: 16px;
            padding: 16px 20px;
            background: rgba(255,255,255,0.03);
            border: 1px solid rgba(255,255,255,0.06);
            border-radius: 12px;
            width: 100%;
            max-width: 560px;
        }

        .meta-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .meta-label {
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: rgba(255,255,255,0.3);
        }

        .meta-value {
            font-size: 0.85rem;
            color: rgba(255,255,255,0.7);
            font-family: 'SF Mono', monospace;
        }

        .close-btn {
            width: 40px; height: 40px;
            border-radius: 10px;
            background: rgba(255,255,255,0.06);
            border: 1px solid rgba(255,255,255,0.1);
            color: white;
            cursor: pointer;
            display: flex; align-items: center; justify-content: center;
            transition: all 0.2s;
        }
        .close-btn:hover { background: rgba(255,255,255,0.12); }
        /* Notifications */
        .notif-bell { position:relative; cursor:pointer; padding:6px; border-radius:8px; transition:background 0.2s; }
        .notif-bell:hover { background:rgba(255,255,255,0.08); }
        .notif-badge { position:absolute; top:0px; right:0px; min-width:16px; height:16px; background:#7c3aed; border-radius:8px; font-size:0.65rem; font-weight:700; color:white; display:none; align-items:center; justify-content:center; padding:0 4px; }
        .notif-badge.show { display:flex; }
        .notif-dropdown { position:absolute; top:calc(100% + 8px); right:0; width:300px; background:#0f0f12; border:1px solid rgba(255,255,255,0.08); border-radius:16px; box-shadow:0 20px 60px rgba(0,0,0,0.6); z-index:9999; display:none; overflow:hidden; }
        .notif-dropdown.open { display:block; }
        .notif-header { padding:12px 16px; border-bottom:1px solid rgba(255,255,255,0.06); display:flex; align-items:center; justify-content:space-between; }
        .notif-item { padding:10px 14px; border-bottom:1px solid rgba(255,255,255,0.04); cursor:pointer; transition:background 0.15s; display:flex; gap:10px; align-items:flex-start; }
        .notif-item:hover { background:rgba(255,255,255,0.03); }
        .notif-item.unread { background:rgba(124,58,237,0.06); }
        .notif-icon { width:30px; height:30px; border-radius:8px; display:flex; align-items:center; justify-content:center; flex-shrink:0; font-size:0.9rem; }
        .notif-empty { padding:20px; text-align:center; color:#4b5563; font-size:0.82rem; }
    </style>
</head>
<body class="min-h-screen antialiased">

    <!-- Noise Overlay -->
    <div class="noise-overlay"></div>

    <!-- Navigation -->
    <nav class="fixed top-0 w-full z-50 glass-panel border-b border-white/5">
        <div class="max-w-7xl mx-auto px-6 lg:px-8">
            <div class="flex justify-between items-center h-20">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center glow-purple" style="padding:1px;">
                        <svg viewBox="0 0 1122 1402" xmlns="http://www.w3.org/2000/svg" fill="white" width="42" height="42"><g transform="translate(0,1402) scale(0.1,-0.1)" fill="white"><path d="M4670 11474 c-124 -33 -250 -115 -318 -206 -42 -55 -694 -1129 -1032 -1698 -106 -179 -225 -379 -265 -445 -73 -121 -536 -899 -614 -1032 -76 -128 -85 -162 -86 -303 0 -121 1 -127 33 -195 18 -38 53 -101 76 -140 24 -38 121 -196 216 -350 95 -154 209 -338 253 -410 122 -197 188 -255 325 -284 37 -8 349 -11 1027 -11 536 0 975 -3 974 -7 0 -5 -33 -62 -73 -128 l-72 -120 -909 -5 c-986 -5 -921 -2 -1032 -59 -74 -37 -122 -101 -303 -401 -97 -162 -261 -434 -363 -603 -208 -344 -227 -388 -227 -521 1 -143 13 -167 509 -1006 234 -396 271 -444 377 -498 32 -16 84 -35 114 -41 41 -9 480 -11 1760 -9 l1705 3 60 23 c80 30 186 103 240 166 25 28 151 227 281 441 131 215 300 494 377 620 77 127 206 338 287 470 195 317 370 606 700 1150 150 248 292 482 316 520 106 172 134 295 99 443 -20 82 -40 121 -214 406 -81 133 -212 349 -290 481 -79 132 -162 259 -185 283 -23 24 -74 60 -115 80 l-75 37 -994 3 c-920 2 -993 4 -988 19 4 9 32 56 63 105 l56 88 851 0 c530 0 875 4 914 10 90 15 160 49 224 111 47 45 117 155 417 655 198 330 375 632 393 669 55 119 51 279 -11 405 -26 51 -97 172 -401 680 -64 107 -149 249 -187 315 -101 171 -180 242 -317 284 -68 21 -69 21 -1795 20 -1489 0 -1734 -2 -1781 -15z m3477 -406 c18 -21 563 -933 563 -944 0 -2 -726 -4 -1613 -4 -1758 0 -1666 3 -1756 -55 -85 -54 -30 32 -966 -1520 -202 -335 -398 -659 -435 -720 -109 -178 -282 -462 -449 -737 -116 -192 -159 -254 -167 -245 -6 7 -135 215 -287 463 -195 317 -277 460 -277 480 0 16 10 47 21 69 58 108 1860 3115 1896 3163 13 17 41 41 61 52 36 19 70 19 1713 20 l1676 0 20 -22z m489 -1370 c-8 -13 -134 -223 -281 -468 -147 -245 -276 -455 -288 -467 l-20 -23 -922 0 -921 0 -52 -26 c-63 -31 -47 -8 -346 -492 -144 -234 -236 -393 -236 -408 0 -15 12 -38 29 -55 l29 -29 1031 0 c567 0 1031 -2 1031 -5 0 -6 -130 -222 -715 -1190 -153 -253 -376 -622 -495 -820 -543 -902 -565 -936 -585 -941 -11 -2 -710 -3 -1552 -2 l-1533 3 274 460 c151 253 282 470 291 483 l16 22 950 0 c1033 0 987 -2 1040 56 27 31 212 345 399 679 127 227 133 250 81 297 l-31 28 -1010 0 c-556 0 -1010 3 -1010 8 0 4 61 109 137 232 172 284 741 1225 968 1600 94 157 276 458 404 670 128 212 240 391 249 398 12 9 338 12 1549 12 l1533 0 -14 -22z m-207 -2484 c151 -250 276 -466 278 -479 3 -12 -1 -33 -7 -46 -17 -33 -228 -380 -515 -849 -270 -440 -791 -1297 -925 -1520 -524 -872 -549 -909 -621 -924 -17 -3 -753 -6 -1635 -6 -1195 0 -1610 3 -1629 12 -14 6 -38 32 -54 57 -69 110 -520 877 -528 897 -4 12 222 14 1603 14 1058 0 1624 4 1654 11 67 15 145 71 184 132 26 41 353 579 496 817 15 25 145 241 290 480 354 585 532 879 822 1360 313 518 302 500 308 500 3 0 128 -205 279 -456z"/></g></svg>
                    </div>
                    <span class="text-xl font-display font-bold tracking-tight text-white">
                        Shomotion <span class="text-primary-400">AI</span>
                    </span>
                </div>
                <!-- Mobile hamburger -->
                <button id="mobile-menu-btn" class="md:hidden flex flex-col gap-1.5 p-2" onclick="toggleMobileMenu()">
                    <span class="block w-6 h-0.5 bg-white transition-all" id="ham-1"></span>
                    <span class="block w-6 h-0.5 bg-white transition-all" id="ham-2"></span>
                    <span class="block w-6 h-0.5 bg-white transition-all" id="ham-3"></span>
                </button>
                <div class="hidden md:flex items-center gap-8">
                    <a href="#templates" class="text-sm font-medium text-gray-400 hover:text-white transition-colors">Templates</a>
                    <a href="#pricing" class="text-sm font-medium text-gray-400 hover:text-white transition-colors flex items-center gap-1.5">
                        Pricing
                        <span id="nav-discount-badge" style="display:none;background:#e91e8c;color:white;font-size:0.6rem;font-weight:700;padding:2px 7px;border-radius:20px;white-space:nowrap;"></span>
                    </a>
                    <!-- Auth buttons - shown/hidden by JS -->
                    <div id="nav-auth-guest" class="flex items-center gap-3">
                        <a href="/login" class="text-sm font-medium text-gray-400 hover:text-white transition-colors">Sign In</a>
                        <a href="/register" class="px-5 py-2.5 rounded-full bg-violet-600 hover:bg-violet-500 text-sm font-medium text-white transition-all">Get Started Free</a>
                    </div>
                    <div id="nav-auth-user" class="flex items-center gap-3" style="display:none!important;">
                        <div class="flex items-center gap-2 px-3 py-1.5 rounded-full glass border border-white/10">
                            <svg class="w-3.5 h-3.5 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
                            <span class="text-xs font-medium text-white" id="nav-credits">— credits</span>
                        </div>
                        <!-- Notification Bell -->
                        <div style="position:relative;display:inline-block;">
                            <div class="notif-bell" onclick="toggleNotif(event)">
                                <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" style="color:rgba(255,255,255,0.7);">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/>
                                </svg>
                                <span class="notif-badge" id="notif-badge"></span>
                            </div>
                            <div class="notif-dropdown" id="notif-dropdown">
                                <div class="notif-header">
                                    <span style="font-weight:700;color:white;font-size:0.9rem;">Notifications</span>
                                    <button onclick="clearAllNotifs()" style="font-size:0.75rem;color:#6b7280;background:none;border:none;cursor:pointer;">Clear all</button>
                                </div>
                                <div id="notif-list"><div class="notif-empty">No notifications yet</div></div>
                            </div>
                        </div>
                        <a href="/dashboard" class="text-sm font-medium text-gray-400 hover:text-white transition-colors">Dashboard</a>
                        <div class="w-8 h-8 rounded-full bg-gradient-to-br from-violet-500 to-violet-700 flex items-center justify-center text-xs font-bold cursor-pointer" id="nav-avatar" onclick="window.location='/dashboard'">U</div>
                    </div>
                </div>
            </div>
        </div>
    </nav>
    <!-- Mobile Menu -->
    <div id="mobile-menu" style="display:none;position:fixed;top:80px;left:0;right:0;background:#0a0a0f;border-bottom:1px solid rgba(255,255,255,0.08);z-index:998;padding:16px 24px;display:none;flex-direction:column;gap:4px;">
        <a href="#templates" onclick="closeMobileMenu()" class="block py-3 px-4 text-gray-300 hover:text-white hover:bg-white/5 rounded-lg transition-colors">Templates</a>
        <a href="#pricing" onclick="closeMobileMenu()" class="block py-3 px-4 text-gray-300 hover:text-white hover:bg-white/5 rounded-lg transition-colors" style="position:relative;">
            Pricing
            <span id="mobile-discount-badge" style="display:none;background:#e91e8c;color:white;font-size:0.65rem;font-weight:700;padding:2px 8px;border-radius:20px;margin-left:8px;"></span>
        </a>
        <div style="border-top:1px solid rgba(255,255,255,0.06);margin:8px 0;"></div>
        <div id="mobile-nav-guest">
            <a href="/login" class="block py-3 px-4 text-gray-300 hover:text-white hover:bg-white/5 rounded-lg transition-colors">Sign In</a>
            <a href="/register" class="block py-3 px-4 mt-1 text-center rounded-lg bg-violet-600 hover:bg-violet-500 text-white font-medium transition-colors">Get Started Free</a>
        </div>
        <div id="mobile-nav-user" style="display:none;">
            <a href="/dashboard" onclick="closeMobileMenu()" class="block py-3 px-4 text-gray-300 hover:text-white hover:bg-white/5 rounded-lg transition-colors">Dashboard</a>
        </div>
    </div>

    <!-- Hero Section -->
    <section class="relative pt-36 pb-16 overflow-hidden">

        <div class="relative z-10 max-w-7xl mx-auto px-6 lg:px-8 text-center">
            <div class="inline-flex items-center gap-2 px-4 py-2 rounded-full glass-panel border border-primary-500/30 mb-8" style="animation: float 6s ease-in-out infinite;">
                <span class="w-2 h-2 rounded-full bg-primary-400 animate-pulse"></span>
                <span class="text-sm font-medium text-primary-200">Powered by Advanced AI Technology</span>
            </div>

            <h1 class="text-5xl md:text-7xl lg:text-8xl font-display font-bold tracking-tight mb-2 leading-tight">
                <span class="block text-white mb-2">Turn Your Logo</span>
                <span class="gradient-text">into a 3D Masterpiece</span>
            </h1>
        </div>

        <!-- Auto-scrolling template carousel — right under the headline -->
        <div class="hero-carousel">
            <div class="hero-track" id="hero-track"></div>
        </div>

        <div class="relative z-10 max-w-7xl mx-auto px-6 lg:px-8 text-center">
            <p class="mt-4 text-xl md:text-2xl text-gray-400 max-w-3xl mx-auto font-light leading-relaxed">
                Create hyper-realistic 3D animations from your logo in seconds
            </p>

            <div class="mt-10">
                <button onclick="document.getElementById('templates').scrollIntoView({behavior:'smooth'})" 
                    class="px-8 py-4 bg-white text-black rounded-full font-semibold text-lg hover:scale-105 transition-transform duration-300 inline-flex items-center gap-2">
                    <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="M19 9l-7 7-7-7"/>
                    </svg>
                    Browse Templates
                </button>
            </div>
        </div>

        <!-- Feature highlights -->
        <div class="relative z-10 max-w-6xl mx-auto px-6 lg:px-8 mt-14 grid grid-cols-1 md:grid-cols-3 gap-10 text-center">
            <div>
                <h3 class="text-white font-semibold text-lg mb-2">Lightning-Fast Generation</h3>
                <p class="text-gray-400 text-sm leading-relaxed">Upload your logo, pick a template, and watch it come to life in moments.</p>
            </div>
            <div>
                <h3 class="text-white font-semibold text-lg mb-2">Dozens of Styles</h3>
                <p class="text-gray-400 text-sm leading-relaxed">From glossy reveals to cinematic 3D scenes, with color controls to match your brand.</p>
            </div>
            <div>
                <h3 class="text-white font-semibold text-lg mb-2">High-Resolution Downloads</h3>
                <p class="text-gray-400 text-sm leading-relaxed">Export in up to 1080p, ready for web, social, or client delivery.</p>
            </div>
        </div>
    </section>

    <!-- Templates Section -->
    <section id="templates" class="py-20 px-6 lg:px-8 max-w-7xl mx-auto">
        <div class="text-center mb-12">
            <h2 class="text-3xl md:text-5xl font-display font-bold text-white mb-4">Choose a Template</h2>
            <p class="text-gray-400 text-lg">Hover over any template to upload your logo</p>
        </div>

        <!-- Templates Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="templates-grid"></div>
    </section>

    <!-- Pricing Section -->
    <section id="pricing" class="py-32 relative">
        <div class="max-w-7xl mx-auto px-6 lg:px-8">
            <div class="text-center mb-14">
                <span class="text-primary-400 font-semibold tracking-wider uppercase text-sm">Pricing</span>
                <h2 class="text-3xl md:text-5xl font-display font-bold text-white mt-4 mb-4">Choose Your Plan</h2>
                <p class="text-gray-400 text-lg">Start free, upgrade when you're ready</p>
                <!-- Monthly/Annual Toggle -->
                <div class="flex items-center justify-center gap-3 mt-8">
                    <button onclick="setPricingCycle('monthly')" id="price-btn-monthly"
                        class="px-5 py-2 rounded-full text-sm font-semibold transition-all"
                        style="background:var(--primary-600,#7c3aed);color:white;">Monthly</button>
                    <button onclick="setPricingCycle('annual')" id="price-btn-annual"
                        class="px-5 py-2 rounded-full text-sm font-semibold transition-all"
                        style="background:rgba(255,255,255,0.06);color:#9ca3af;">
                        Annual <span id="annual-discount-badge" style="color:#34d399;">Save 27%</span>
                    </button>
                </div>
            </div>
            <div id="pricing-grid" class="grid md:grid-cols-4 gap-6 max-w-7xl mx-auto" style="align-items:stretch;"></div>
        </div>
    </section>

    <!-- Footer -->
    <footer class="border-t border-white/5 pt-20 pb-10">
        <div class="max-w-7xl mx-auto px-6 lg:px-8">
            <div class="grid md:grid-cols-4 gap-12 mb-16">
                <div class="col-span-2">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-500 to-primary-700 flex items-center justify-center" style="padding:3px;">
                            <svg viewBox="0 0 1122 1402" xmlns="http://www.w3.org/2000/svg" fill="white" width="42" height="42"><g transform="translate(0,1402) scale(0.1,-0.1)" fill="white"><path d="M4670 11474 c-124 -33 -250 -115 -318 -206 -42 -55 -694 -1129 -1032 -1698 -106 -179 -225 -379 -265 -445 -73 -121 -536 -899 -614 -1032 -76 -128 -85 -162 -86 -303 0 -121 1 -127 33 -195 18 -38 53 -101 76 -140 24 -38 121 -196 216 -350 95 -154 209 -338 253 -410 122 -197 188 -255 325 -284 37 -8 349 -11 1027 -11 536 0 975 -3 974 -7 0 -5 -33 -62 -73 -128 l-72 -120 -909 -5 c-986 -5 -921 -2 -1032 -59 -74 -37 -122 -101 -303 -401 -97 -162 -261 -434 -363 -603 -208 -344 -227 -388 -227 -521 1 -143 13 -167 509 -1006 234 -396 271 -444 377 -498 32 -16 84 -35 114 -41 41 -9 480 -11 1760 -9 l1705 3 60 23 c80 30 186 103 240 166 25 28 151 227 281 441 131 215 300 494 377 620 77 127 206 338 287 470 195 317 370 606 700 1150 150 248 292 482 316 520 106 172 134 295 99 443 -20 82 -40 121 -214 406 -81 133 -212 349 -290 481 -79 132 -162 259 -185 283 -23 24 -74 60 -115 80 l-75 37 -994 3 c-920 2 -993 4 -988 19 4 9 32 56 63 105 l56 88 851 0 c530 0 875 4 914 10 90 15 160 49 224 111 47 45 117 155 417 655 198 330 375 632 393 669 55 119 51 279 -11 405 -26 51 -97 172 -401 680 -64 107 -149 249 -187 315 -101 171 -180 242 -317 284 -68 21 -69 21 -1795 20 -1489 0 -1734 -2 -1781 -15z m3477 -406 c18 -21 563 -933 563 -944 0 -2 -726 -4 -1613 -4 -1758 0 -1666 3 -1756 -55 -85 -54 -30 32 -966 -1520 -202 -335 -398 -659 -435 -720 -109 -178 -282 -462 -449 -737 -116 -192 -159 -254 -167 -245 -6 7 -135 215 -287 463 -195 317 -277 460 -277 480 0 16 10 47 21 69 58 108 1860 3115 1896 3163 13 17 41 41 61 52 36 19 70 19 1713 20 l1676 0 20 -22z m489 -1370 c-8 -13 -134 -223 -281 -468 -147 -245 -276 -455 -288 -467 l-20 -23 -922 0 -921 0 -52 -26 c-63 -31 -47 -8 -346 -492 -144 -234 -236 -393 -236 -408 0 -15 12 -38 29 -55 l29 -29 1031 0 c567 0 1031 -2 1031 -5 0 -6 -130 -222 -715 -1190 -153 -253 -376 -622 -495 -820 -543 -902 -565 -936 -585 -941 -11 -2 -710 -3 -1552 -2 l-1533 3 274 460 c151 253 282 470 291 483 l16 22 950 0 c1033 0 987 -2 1040 56 27 31 212 345 399 679 127 227 133 250 81 297 l-31 28 -1010 0 c-556 0 -1010 3 -1010 8 0 4 61 109 137 232 172 284 741 1225 968 1600 94 157 276 458 404 670 128 212 240 391 249 398 12 9 338 12 1549 12 l1533 0 -14 -22z m-207 -2484 c151 -250 276 -466 278 -479 3 -12 -1 -33 -7 -46 -17 -33 -228 -380 -515 -849 -270 -440 -791 -1297 -925 -1520 -524 -872 -549 -909 -621 -924 -17 -3 -753 -6 -1635 -6 -1195 0 -1610 3 -1629 12 -14 6 -38 32 -54 57 -69 110 -520 877 -528 897 -4 12 222 14 1603 14 1058 0 1624 4 1654 11 67 15 145 71 184 132 26 41 353 579 496 817 15 25 145 241 290 480 354 585 532 879 822 1360 313 518 302 500 308 500 3 0 128 -205 279 -456z"/></g></svg>
                        </div>
                        <span class="text-xl font-display font-bold text-white">Shomotion <span class="text-primary-400">AI</span></span>
                    </div>
                    <p class="text-gray-400 max-w-sm leading-relaxed">Transforming 2D logos into stunning 3D masterpieces using advanced AI technology.</p>
                </div>
                <div>
                    <h4 class="text-white font-semibold mb-4">Product</h4>
                    <ul class="space-y-3 text-gray-400">
                        <li><a href="#templates" class="hover:text-primary-400 transition-colors">Templates</a></li>
                        <li><a href="#pricing" class="hover:text-primary-400 transition-colors">Pricing</a></li>
                        
                    </ul>
                </div>
                <div>
                    <h4 class="text-white font-semibold mb-4">Company</h4>
                    <ul class="space-y-3 text-gray-400">
                        <li><a href="#" class="hover:text-primary-400 transition-colors">About</a></li>
                        <li><a href="#" class="hover:text-primary-400 transition-colors">Blog</a></li>
                        <li><a href="#" class="hover:text-primary-400 transition-colors">Contact</a></li>
                    </ul>
                </div>
            </div>
            <div class="border-t border-white/5 pt-8 flex flex-col md:flex-row justify-between items-center gap-4">
                <p class="text-gray-500 text-sm">© 2026 Shomotion AI. All rights reserved.</p>
                <div class="flex items-center gap-4 mt-2">
                    <a href="/terms" class="text-gray-600 hover:text-gray-400 text-xs transition-colors">Terms of Service</a>
                    <a href="/privacy" class="text-gray-600 hover:text-gray-400 text-xs transition-colors">Privacy Policy</a>
                    <a href="/refund" class="text-gray-600 hover:text-gray-400 text-xs transition-colors">Refund Policy</a>
                </div>
                <div class="flex gap-6">
                    <a href="#" class="text-gray-400 hover:text-white transition-colors">
                        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z"/></svg>
                    </a>
                    <a href="#" class="text-gray-400 hover:text-white transition-colors">
                        <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                    </a>
                </div>
            </div>
        </div>
    </footer>

    <!-- Processing Overlay -->
    <div class="processing-overlay" id="processing">
        <div class="spinner mb-8"></div>
        <h3 class="text-2xl font-semibold text-white mb-2" id="processing-text">Your video is generating...</h3>
        <p class="text-gray-400" id="processing-detail">This may take a minute</p>
        <div class="mt-6 w-64 h-1 bg-white/10 rounded-full overflow-hidden">
            <div class="h-full bg-violet-500 w-0 transition-all duration-500" id="progress-bar"></div>
        </div>
        <p class="mt-4 text-sm text-gray-500" id="progress-text">0%</p>
    </div>

    <!-- Result Page -->
    <div class="result-modal" id="result">
        <!-- Top Bar -->
        <div class="result-topbar">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-500 to-violet-700 flex items-center justify-center">
                    <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="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>
                </div>
                <span class="text-white font-semibold">Shomotion <span class="text-violet-400">AI</span></span>
            </div>
            <div class="flex items-center gap-3">
                <span class="text-xs text-green-400 flex items-center gap-1.5">
                    <span class="w-1.5 h-1.5 rounded-full bg-green-400 animate-pulse inline-block"></span>
                    Ready
                </span>
                <button onclick="openReportModal()" style="padding:6px 12px;background:rgba(220,38,38,0.15);border:1px solid rgba(220,38,38,0.3);border-radius:8px;color:#fca5a5;font-size:0.75rem;cursor:pointer;font-weight:500;">
                    ⚠ Report Issue
                </button>
                <button class="close-btn" onclick="closeResult()" title="Back to templates">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
        </div>

        <!-- Main Content -->
        <div class="result-content">

            <!-- Video Stage -->
            <div class="video-stage">
                <div class="video-glow"></div>
                <div class="video-wrapper">
                    <video id="result-video" autoplay loop playsinline>
                        <source src="" type="video/mp4">
                    </video>
                    <!-- Custom Controls -->
                    <div class="video-controls" id="video-controls">
                        <div class="progress-track" id="progress-track">
                            <div class="progress-fill" id="progress-fill"></div>
                        </div>
                        <div class="controls-row">
                            <button class="ctrl-btn" id="play-btn" onclick="togglePlay()">
                                <svg id="play-icon" class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                                    <path d="M6 4l14 8-14 8V4z"/>
                                </svg>
                            </button>
                            <button class="ctrl-btn" onclick="toggleMute()">
                                <svg id="mute-icon" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.536 8.464a5 5 0 010 7.072M12 6v12m0 0l-4-4m4 4l4-4M9 9H5a1 1 0 00-1 1v4a1 1 0 001 1h4l4 4V5L9 9z"/>
                                </svg>
                            </button>
                            <span class="time-display" id="time-display">0:00 / 0:00</span>
                            <button class="ctrl-btn" onclick="toggleFullscreen()" style="margin-left: 8px;">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-5h-4m4 0v4m0-4l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"/>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="result-actions">
                <button class="action-btn primary" onclick="download()">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                    </svg>
                    Download MP4
                </button>
                <button class="action-btn secondary" onclick="closeResult()">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4l16 16M4 20L20 4"/>
                    </svg>
                    New Video
                </button>
            </div>

            <!-- Meta Info -->
            <div class="result-meta">
                <div class="meta-item">
                    <span class="meta-label">Template</span>
                    <span class="meta-value" id="result-template">—</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Processing Time</span>
                    <span class="meta-value" id="result-info">—</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Status</span>
                    <span class="meta-value" style="color: #4ade80;">✓ Completed</span>
                </div>
            </div>

        </div>
    </div>

    <!-- Quality Selector Modal -->
    <!-- Report Issue Modal -->
    <div id="report-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.8);backdrop-filter:blur(8px);z-index:200;align-items:center;justify-content:center;">
        <div style="background:#0f0f12;border:1px solid rgba(255,255,255,0.08);border-radius:24px;padding:28px;max-width:380px;width:92%;">
            <h3 style="font-family:'Space Grotesk',sans-serif;font-weight:700;font-size:1.1rem;color:white;margin:0 0 6px;">Report an Issue</h3>
            <p style="color:rgba(255,255,255,0.4);font-size:0.82rem;margin:0 0 20px;">Tell us what went wrong and we'll review your request.</p>
            <div style="display:flex;flex-direction:column;gap:8px;margin-bottom:16px;">
                <label style="color:rgba(255,255,255,0.5);font-size:0.8rem;">What was the issue?</label>
                <select id="report-reason" style="background:#1a1a2e;border:1px solid rgba(255,255,255,0.1);border-radius:10px;padding:10px 12px;color:white;font-size:0.85rem;outline:none;">
                    <option value="poor_quality">Poor video quality</option>
                    <option value="logo_not_visible">Logo not visible</option>
                    <option value="wrong_colors">Wrong colors</option>
                    <option value="generation_failed">Generation failed/corrupted</option>
                    <option value="other">Other issue</option>
                </select>
            </div>
            <div id="report-result" style="display:none;padding:10px 14px;border-radius:10px;font-size:0.82rem;margin-bottom:16px;"></div>
            <div style="display:flex;gap:8px;">
                <button onclick="closeReportModal()" style="flex:1;padding:11px;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.08);border-radius:12px;color:rgba(255,255,255,0.5);cursor:pointer;font-size:0.9rem;">Cancel</button>
                <button onclick="submitReport()" id="report-submit-btn" style="flex:2;padding:11px;background:linear-gradient(135deg,#dc2626,#b91c1c);border:none;border-radius:12px;color:white;cursor:pointer;font-weight:700;font-size:0.9rem;">Submit Report</button>
            </div>
        </div>
    </div>

    <div id="quality-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.8);backdrop-filter:blur(8px);z-index:150;align-items:center;justify-content:center;">
        <div style="background:#0f0f12;border:1px solid rgba(255,255,255,0.08);border-radius:24px;padding:28px;max-width:400px;width:92%;box-shadow:0 40px 80px rgba(0,0,0,0.6);">
            <div style="margin-bottom:20px;">
                <h3 style="font-family:'Space Grotesk',sans-serif;font-size:1.25rem;font-weight:700;color:white;margin:0 0 4px;">Choose Quality</h3>
                <p style="color:rgba(255,255,255,0.35);font-size:0.8rem;margin:0;">Select the resolution for your video</p>
            </div>
            <div id="quality-buttons-container" style="display:flex;flex-direction:column;gap:8px;margin-bottom:20px;"></div>
            <!-- Aspect Ratio -->
            <div style="margin-bottom:16px;">
                <div style="color:rgba(255,255,255,0.5);font-size:0.82rem;margin-bottom:8px;">Aspect Ratio</div>
                <div style="display:flex;gap:8px;">
                    <div onclick="selectRatio('16:9',this)" data-ratio="16:9" style="flex:1;padding:10px 6px;border-radius:10px;cursor:pointer;text-align:center;border:1px solid rgba(255,255,255,0.08);background:rgba(255,255,255,0.03);transition:all 0.2s;">
                        <div style="display:flex;align-items:center;justify-content:center;margin-bottom:5px;">
                            <div style="width:22px;height:14px;border:1.5px solid currentColor;border-radius:2px;"></div>
                        </div>
                        <div style="font-size:0.72rem;font-weight:600;color:white;">16:9</div>
                    </div>
                    <div onclick="selectRatio('9:16',this)" data-ratio="9:16" style="flex:1;padding:10px 6px;border-radius:10px;cursor:pointer;text-align:center;border:1px solid rgba(255,255,255,0.08);background:rgba(255,255,255,0.03);transition:all 0.2s;">
                        <div style="display:flex;align-items:center;justify-content:center;margin-bottom:5px;">
                            <div style="width:11px;height:18px;border:1.5px solid currentColor;border-radius:2px;"></div>
                        </div>
                        <div style="font-size:0.72rem;font-weight:600;color:white;">9:16</div>
                    </div>
                    <div onclick="selectRatio('1:1',this)" data-ratio="1:1" style="flex:1;padding:10px 6px;border-radius:10px;cursor:pointer;text-align:center;border:1px solid rgba(255,255,255,0.08);background:rgba(255,255,255,0.03);transition:all 0.2s;">
                        <div style="display:flex;align-items:center;justify-content:center;margin-bottom:5px;">
                            <div style="width:16px;height:16px;border:1.5px solid currentColor;border-radius:2px;"></div>
                        </div>
                        <div style="font-size:0.72rem;font-weight:600;color:white;">1:1</div>
                    </div>
                    <div onclick="selectRatio('3:4',this)" data-ratio="3:4" style="flex:1;padding:10px 6px;border-radius:10px;cursor:pointer;text-align:center;border:1px solid rgba(255,255,255,0.08);background:rgba(255,255,255,0.03);transition:all 0.2s;">
                        <div style="display:flex;align-items:center;justify-content:center;margin-bottom:5px;">
                            <div style="width:13px;height:17px;border:1.5px solid currentColor;border-radius:2px;"></div>
                        </div>
                        <div style="font-size:0.72rem;font-weight:600;color:white;">3:4</div>
                    </div>
                </div>
            </div>

            <div style="background:rgba(139,92,246,0.08);border:1px solid rgba(139,92,246,0.15);border-radius:12px;padding:12px 16px;display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
                <span style="color:rgba(255,255,255,0.5);font-size:0.82rem;">Your balance</span>
                <span id="modal-points" style="color:#a78bfa;font-weight:700;font-size:0.95rem;">— pts</span>
            </div>

            <!-- Color Controls - بيتظهر بس لو التمبليت عنده controls -->
            <div id="color-controls-section" style="display:none;margin-bottom:16px;">
                <div style="color:rgba(255,255,255,0.5);font-size:0.82rem;margin-bottom:8px;">Customize</div>
                <div id="color-controls-list" style="display:flex;flex-direction:column;gap:8px;"></div>
            </div>
            <div style="display:flex;gap:8px;">
                <button onclick="closeQualityModal()" style="flex:1;padding:12px;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.08);border-radius:12px;color:rgba(255,255,255,0.5);cursor:pointer;font-size:0.9rem;font-weight:500;">Cancel</button>
                <button onclick="confirmGenerate()" id="confirm-gen-btn" style="flex:2;padding:12px;background:linear-gradient(135deg,#7c3aed,#6d28d9);border:none;border-radius:12px;color:white;cursor:pointer;font-weight:700;font-size:0.9rem;box-shadow:0 4px 20px rgba(124,58,237,0.35);">Generate Video</button>
            </div>
        </div>
    </div>

    <input type="file" id="file-input" accept=".png,.jpg,.jpeg,.webp" class="hidden" onchange="handleFile(event)">

    <script>
        // ✅ غيّر هذا لو رفعت السيرفر على domain حقيقي
        const API_URL = window.location.origin.includes('localhost') 
            ? 'http://localhost:3000' 
            : window.location.origin;
        
        let selectedTemplate = null;
        let currentTemplateDuration = 5;
        let currentTemplateTier = 'standard';
        let currentJob = null;
        let ws = null;
        let pollingInterval = null;

        let templates = []; // هتتملى من الـ API

        function buildHeroCard(t, i) {
            const glow = (i % 7 === 3) ? ' glow-card' : '';
            const poster = t && t.img; // only ever real template thumbnails, no stock imagery
            const videoSrc = t && (t.preview_video || (t.id ? `/workflows/${t.id}.preview.mp4` : null));
            const label = (t && (t.name || t.id)) || 'template';

            if (videoSrc) {
                const bg = poster ? ` style="background-image:url('${poster}')"` : '';
                return `<div class="hero-card${glow}"${bg}>
                    <video src="${videoSrc}" autoplay muted loop playsinline preload="auto"
                           onerror="this.style.display='none'"></video>
                </div>`;
            }
            if (poster) {
                return `<div class="hero-card${glow}">
                    <img src="${poster}" alt="${label}" loading="lazy" onerror="this.style.display='none'">
                </div>`;
            }
            // No template data yet — stays a plain black card, no placeholder imagery.
            return `<div class="hero-card${glow}"></div>`;
        }

        // ── Live coverflow effect ─────────────────────────────────────
        // Each card's size/rotation is recomputed every frame from its actual
        // on-screen position: cards shrink as they approach the center of the
        // rail and grow again as they near either edge — independent of the
        // CSS animation that scrolls the track itself.
        function updateCoverflow() {
            const carousel = document.querySelector('.hero-carousel');
            if (carousel) {
                const rect = carousel.getBoundingClientRect();
                const centerX = rect.left + rect.width / 2;
                const halfWidth = rect.width / 2 || 1;

                document.querySelectorAll('.hero-card').forEach(card => {
                    const cardRect = card.getBoundingClientRect();
                    const cardCenter = cardRect.left + cardRect.width / 2;
                    let dx = (cardCenter - centerX) / halfWidth; // -1 left edge … 0 center … 1 right edge
                    dx = Math.max(-1, Math.min(1, dx));
                    const distFromCenter = Math.abs(dx);

                    const angle = -dx * 42;                         // rotate inward, facing toward center
                    const scale = 0.62 + distFromCenter * 0.42;     // smallest at center, biggest at the edges
                    const depth = -(1 - distFromCenter) * 70;       // center recedes slightly
                    const brightness = 0.72 + distFromCenter * 0.28;

                    card.style.transform = `rotateY(${angle.toFixed(1)}deg) translateZ(${depth.toFixed(0)}px) scale(${scale.toFixed(3)})`;
                    card.style.filter = `brightness(${brightness.toFixed(2)})`;

                    // Scaling shrinks each card's rendered width from both sides, which would
                    // otherwise open up a bigger visual gap around smaller cards. Pull neighbors
                    // in with a compensating negative margin so the on-screen spacing stays fixed.
                    const baseWidth = card.offsetWidth; // layout width, unaffected by the transform above
                    const shrink = baseWidth * (1 - scale);
                    card.style.marginLeft = `${(-shrink / 2).toFixed(1)}px`;
                    card.style.marginRight = `${(-shrink / 2).toFixed(1)}px`;
                });
            }
            requestAnimationFrame(updateCoverflow);
        }
        requestAnimationFrame(updateCoverflow);

        function buildHeroCarousel(list) {
            const track = document.getElementById('hero-track');
            if (!track) return;
            const set = (list && list.length) ? list.slice(0, 10) : Array(8).fill(null);
            const doubled = set.concat(set); // duplicate for seamless infinite loop
            track.innerHTML = doubled.map((t, i) => buildHeroCard(t, i)).join('');
        }
        buildHeroCarousel([]); // placeholder rail while templates load

        // ── بناء كارد واحد ─────────────────────────────────────────────
        function buildCard(t, i) {
            const popularBadge = t.popular 
                ? '<div class="absolute top-4 left-4 z-10 bg-violet-500 text-white text-xs font-bold px-3 py-1 rounded-full">POPULAR</div>' 
                : '';
            const tags = (t.tags || [])
                .map(tag => `<span class="px-2 py-1 rounded-full bg-white/5 text-xs text-gray-300">${tag}</span>`)
                .join('');
            const imgSrc = t.img || `https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=600&h=360&fit=crop`;
            const previewSrc = t.preview_video || `/workflows/${t.id}.preview.mp4`;
            const cardVidId = `prev-vid-${i}`;
            const previewVideo = `<video id="${cardVidId}" class="card-preview-video" src="${previewSrc}" loop playsinline preload="none" onerror="this.style.display='none'"></video>`;

            return `
                <div class="template-card glass-panel rounded-2xl border border-white/10 cursor-pointer"
                     id="tcard-${i}"
                     onmouseenter="hoverCard('${cardVidId}', 'tcard-${i}')"
                     onmouseleave="unhoverCard('${cardVidId}', 'tcard-${i}')"
                     onclick="selectCard('${t.id}', 'tcard-${i}')">
                    ${popularBadge}
                    <div class="card-media-wrap">
                        <img id="thumb-${cardVidId}" src="${imgSrc}" class="card-image"
                             onerror="this.src='https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=600&h=360&fit=crop'">
                        ${previewVideo}
                        <div class="upload-overlay" id="overlay-${cardVidId}">
                            <div class="upload-icon">
                                <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
                                </svg>
                            </div>
                            <p class="upload-text">Upload Logo</p>
                            <p class="upload-hint">PNG with transparency</p>
                        </div>
                        <div class="card-play-hint">
                            <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
                            Preview
                        </div>
                    </div>
                    <div class="p-5 border-t border-white/5">
                        <h3 class="text-lg font-semibold text-white mb-1">${t.name || t.id}</h3>
                        <p class="text-sm text-gray-400 mb-3">${t.desc || ''}</p>
                        <div class="flex flex-wrap gap-2">${tags}</div>
                    </div>
                </div>`;
        }

        // ── Skeleton loaders أثناء التحميل ──────────────────────────────
        function showSkeletons(count = 3) {
            const grid = document.getElementById('templates-grid');
            grid.innerHTML = Array(count).fill(0).map(() => `
                <div class="glass-panel rounded-2xl border border-white/10 animate-pulse">
                    <div style="aspect-ratio:16/9" class="bg-white/5 rounded-t-2xl"></div>
                    <div class="p-5 space-y-3">
                        <div class="h-4 bg-white/5 rounded w-1/2"></div>
                        <div class="h-3 bg-white/5 rounded w-3/4"></div>
                        <div class="flex gap-2">
                            <div class="h-5 bg-white/5 rounded-full w-12"></div>
                            <div class="h-5 bg-white/5 rounded-full w-16"></div>
                        </div>
                    </div>
                </div>`).join('');
        }

        // ── Quality Selection ────────────────────────────────────────
        let selectedQualityValue = '480p';
        let pendingFile = null;

        // الجودات المتاحة لكل plan
        const PLAN_ALLOWED_QUALITIES = {
            free:          ['480p'],
            basic:         ['480p', '720p'],
            standard:      ['480p', '720p', '1080p'],
            pro:           ['480p', '720p', '1080p', '4K'],
            basic_annual:    ['480p', '720p'],
            standard_annual: ['480p', '720p', '1080p'],
            pro_annual:      ['480p', '720p', '1080p', '4K'],
        };

        const QUALITY_COSTS = { '480p': 50, '720p': 88, '1080p': 194, '4K': 194 };
        const QUALITY_LABELS = { '480p': '480p', '720p': '720p HD', '1080p': '1080p Full HD', '4K': '4K Ultra HD' };
        const PLAN_UPGRADE_FOR = { '720p': 'basic', '1080p': 'standard', '4K': 'pro' };

        function getUserPlan() {
            const user = localStorage.getItem('gl_user') ? JSON.parse(localStorage.getItem('gl_user')) : null;
            return (user?.plan || 'free').toLowerCase();
        }

        function selectRatio(ratio, btn) {
            selectedRatio = ratio;
            document.querySelectorAll('[data-ratio]').forEach(b => {
                b.style.background = 'rgba(255,255,255,0.03)';
                b.style.borderColor = 'rgba(255,255,255,0.08)';
                const icon = b.querySelector('div > div');
                const label = b.querySelector('div:last-child');
                if (icon) icon.style.borderColor = 'rgba(255,255,255,0.5)';
                if (label) label.style.color = 'white';
            });
            btn.style.background = 'rgba(139,92,246,0.15)';
            btn.style.borderColor = 'rgba(139,92,246,0.6)';
            const icon = btn.querySelector('div > div');
            const label = btn.querySelector('div:last-child');
            if (icon) icon.style.borderColor = '#a78bfa';
            if (label) label.style.color = '#a78bfa';
        }

        function selectQuality(q, btn) {
            const user = localStorage.getItem('gl_user') ? JSON.parse(localStorage.getItem('gl_user')) : null;
            const pts = user?.credits || 0;
            const allowed = PLAN_ALLOWED_QUALITIES[getUserPlan()] || ['480p'];
            if (!allowed.includes(q)) return;

            selectedQualityValue = q;
            // reset all
            document.querySelectorAll('#quality-buttons-container > div').forEach(b => {
                b.style.background = 'rgba(255,255,255,0.03)';
                b.style.borderColor = 'rgba(255,255,255,0.08)';
            });
            // highlight selected
            btn.style.background = 'rgba(139,92,246,0.15)';
            btn.style.borderColor = 'rgba(139,92,246,0.5)';

            const cost = calcDynamicCost(q);
            const confirmBtn = document.getElementById('confirm-gen-btn');
            if (pts < cost) {
                confirmBtn.style.opacity = '0.5';
                confirmBtn.style.cursor = 'not-allowed';
                confirmBtn.textContent = 'Not enough points';
            } else {
                confirmBtn.style.opacity = '1';
                confirmBtn.style.cursor = 'pointer';
                confirmBtn.textContent = 'Generate Video';
            }
        }

        function calcDynamicCost(quality) {
            const ptsPerSec = window._pricingData?.pts_per_second || {'480p':7,'720p':11,'1080p':27,'4K':27};
            const premPtsPerSec = window._pricingData?.premium_pts_per_second || {'480p':11,'720p':17,'1080p':41};
            const isPrem = currentTemplateTier === 'premium';
            const rates = isPrem ? premPtsPerSec : ptsPerSec;
            return Math.round((currentTemplateDuration || 5) * (rates[quality] || 11));
        }

        async function openQualityModal(file) {
            pendingFile = file;

            // Sync user data from server first
            const token = localStorage.getItem('gl_token');
            if (token) {
                try {
                    const r = await fetch(`${API_URL}/auth/me`, { headers: { Authorization: 'Bearer ' + token } });
                    if (r.ok) {
                        const d = await r.json();
                        if (d.user) localStorage.setItem('gl_user', JSON.stringify(d.user));
                    }
                } catch(e) {}
            }

            const user = localStorage.getItem('gl_user') ? JSON.parse(localStorage.getItem('gl_user')) : null;
            const pts = user?.credits || 0;
            const plan = getUserPlan();
            const allowed = PLAN_ALLOWED_QUALITIES[plan] || ['480p'];

            // جيب template duration & tier & color_controls
            try {
                const r = await fetch(`${API_URL}/api/template/${typeof selectedTemplate === 'object' ? selectedTemplate?.id : selectedTemplate}/info`);
                if (r.ok) {
                    const info = await r.json();
                    currentTemplateDuration = info.duration || 5;
                    currentTemplateTier = info.tier || 'standard';

                    // Color Controls
                    const controls = info.color_controls || [];
                    const section = document.getElementById('color-controls-section');
                    const list = document.getElementById('color-controls-list');
                    if (controls.length > 0) {
                        list.innerHTML = controls.map(c => {
                            const ctrlId = c.placeholder.replace(/[\[\]]/g,'');
                            const defaultVal = c.default || '';

                            // لو فيه options → dropdown
                            if (c.options && c.options.length > 0) {
                                return `<div>
                                    <div style="color:rgba(255,255,255,0.5);font-size:0.78rem;margin-bottom:6px;">${c.label}</div>
                                    <select id="ctrl-select-${ctrlId}"
                                        data-placeholder="${c.placeholder}"
                                        onchange="document.getElementById('ctrl-name-${ctrlId}').dataset.value=this.value;document.getElementById('ctrl-name-${ctrlId}').textContent=this.value;"
                                        style="width:100%;background:#1a1a2e;border:1px solid rgba(255,255,255,0.1);border-radius:10px;padding:10px 12px;color:white;font-size:0.82rem;outline:none;cursor:pointer;">
                                        ${c.options.map(opt => `<option value="${opt}" ${opt === defaultVal ? 'selected' : ''}>${opt}</option>`).join('')}
                                    </select>
                                    <span id="ctrl-name-${ctrlId}" style="display:none;"
                                        data-placeholder="${c.placeholder}"
                                        data-value="${defaultVal}">${defaultVal}</span>
                                </div>`;
                            }

                            // لو مفيش options → color picker
                            const colorMap = {
                                'white':'#ffffff','black':'#000000','red':'#ef4444','blue':'#3b82f6',
                                'green':'#22c55e','yellow':'#eab308','orange':'#f97316','purple':'#a855f7',
                                'pink':'#ec4899','gray':'#6b7280','grey':'#6b7280','navy':'#1e3a5f',
                                'brown':'#92400e','gold':'#d97706','silver':'#9ca3af','beige':'#d4b896'
                            };
                            const defaultHex = colorMap[defaultVal.toLowerCase()] || '#ffffff';
                            return `<div>
                                <div style="color:rgba(255,255,255,0.5);font-size:0.78rem;margin-bottom:6px;">${c.label}</div>
                                <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                                    <input type="color" id="ctrl-picker-${ctrlId}" value="${defaultHex}"
                                        style="width:40px;height:40px;border:none;border-radius:8px;cursor:pointer;background:none;padding:0;"
                                        oninput="updateColorName('${ctrlId}', this.value)"
                                        data-placeholder="${c.placeholder}">
                                    <span id="ctrl-name-${ctrlId}"
                                        style="font-size:0.85rem;font-weight:600;color:white;min-width:60px;"
                                        data-placeholder="${c.placeholder}"
                                        data-value="${defaultVal}">${defaultVal}</span>
                                    <div style="display:flex;gap:4px;flex-wrap:wrap;">
                                        ${['white','black','red','blue','green','yellow','orange','purple','pink','navy'].map(col =>
                                            `<div onclick="setColor('${ctrlId}','${col}')"
                                                style="width:22px;height:22px;border-radius:4px;cursor:pointer;background:${colorMap[col]||col};border:1.5px solid rgba(255,255,255,0.2);transition:transform 0.15s;"
                                                title="${col}"></div>`
                                        ).join('')}
                                    </div>
                                </div>
                            </div>`;
                        }).join('');
                        section.style.display = 'block';
                    } else {
                        section.style.display = 'none';
                    }
                }
            } catch(e) {}

            document.getElementById('modal-points').textContent = pts + ' pts';

            const qlabels = {'480p':'480p','720p':'720p HD','1080p':'1080p Full HD','4K':'4K Ultra HD'};
            const qdescs = {'480p':'Standard quality · Fast generation','720p':'HD quality · Great for social media','1080p':'Full HD · Maximum quality','4K':'4K Ultra HD · Pro exclusive ✨'};
            const ptsPerSec = window._pricingData?.pts_per_second || {'480p':7,'720p':11,'1080p':27,'4K':27};

            const container = document.getElementById('quality-buttons-container');
            container.innerHTML = ['480p','720p','1080p','4K'].map(q => {
                const isAllowed = allowed.includes(q);
                const cost = calcDynamicCost(q);
                const canAfford = pts >= cost;
                const rate = ptsPerSec[q] || 11;
                if (isAllowed) {
                    return `<div onclick="selectQuality('${q}',this)" data-quality="${q}" style="display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-radius:12px;cursor:pointer;border:1px solid rgba(255,255,255,0.08);background:rgba(255,255,255,0.03);transition:all 0.2s;${!canAfford?'opacity:0.5;':''}">
                        <div>
                            <div style="font-weight:700;color:white;font-size:0.95rem;">${qlabels[q]}</div>
                            <div style="color:rgba(255,255,255,0.35);font-size:0.72rem;margin-top:2px;">${currentTemplateDuration}s × ${rate} pts/s${currentTemplateTier==='premium'?' (Premium)':''}</div>
                        </div>
                        <div style="text-align:right;flex-shrink:0;">
                            <div style="color:#a78bfa;font-weight:700;font-size:0.95rem;">${cost} pts</div>
                            ${!canAfford?'<div style="color:#ef4444;font-size:0.7rem;">Not enough</div>':''}
                        </div>
                    </div>`;
                } else {
                    return `<div style="display:flex;align-items:center;justify-content:space-between;padding:14px 16px;border-radius:12px;border:1px solid rgba(255,255,255,0.05);background:rgba(255,255,255,0.01);opacity:0.4;cursor:not-allowed;">
                        <div>
                            <div style="font-weight:700;color:white;font-size:0.95rem;">${qlabels[q]} <span style="font-size:0.7rem;color:#f59e0b;">🔒 Upgrade to unlock</span></div>
                            <div style="color:rgba(255,255,255,0.3);font-size:0.72rem;margin-top:2px;">${qdescs[q]}</div>
                        </div>
                        <div style="color:#6b7280;font-weight:700;font-size:0.95rem;">${cost} pts</div>
                    </div>`;
                }
            }).join('');

            document.getElementById('quality-modal').style.display = 'flex';

            // auto-select 16:9 ratio
            selectedRatio = '16:9';
            setTimeout(() => {
                const defaultRatioBtn = document.querySelector('[data-ratio="16:9"]');
                if (defaultRatioBtn) selectRatio('16:9', defaultRatioBtn);
            }, 50);

            // auto-select أعلى جودة متاحة ومدفوعة
            const affordable = allowed.filter(q => pts >= calcDynamicCost(q));
            const best = affordable[affordable.length-1] || allowed[0];
            const bestBtn = container.querySelector(`[data-quality="${best}"]`);
            if (bestBtn) selectQuality(best, bestBtn);
            else selectedQualityValue = best;
        }

        function closeQualityModal() {
            document.getElementById('quality-modal').style.display = 'none';
            pendingFile = null;
            // reset file input عشان يشتغل تاني
            const fi = document.getElementById('file-input');
            if (fi) {
                fi.value = '';
                // Force reset بطريقة تانية للـ browsers اللي مش بتسمع
                const newFi = fi.cloneNode(true);
                fi.parentNode.replaceChild(newFi, fi);
                newFi.addEventListener('change', handleFile);
            }
        }

        async function confirmGenerate() {
            if (!pendingFile) return;
            document.getElementById('quality-modal').style.display = 'none';
            await startProcessing(pendingFile);
            pendingFile = null;
        }

        // ── Template card logic ───────────────────────────────────────
        let activeOverlay = null;

        function hoverCard(vidId, cardId) {
            const v = document.getElementById(vidId);
            if (!v || v.style.display === 'none') return;
            v.currentTime = 0;
            v.muted = !window._userInteracted;
            v.play().catch(() => { v.muted = true; v.play().catch(() => {}); });
            v.classList.add('playing');
            const img = document.getElementById('thumb-' + vidId);
            if (img) img.classList.add('hidden-by-video');
        }

        function unhoverCard(vidId, cardId) {
            const v = document.getElementById(vidId);
            if (!v) return;
            v.pause();
            v.currentTime = 0;
            v.classList.remove('playing');
            const img = document.getElementById('thumb-' + vidId);
            if (img) img.classList.remove('hidden-by-video');
        }

        function selectCard(templateId, cardId) {
            // لو فيه overlay تاني مفتوح اقفله
            if (activeOverlay && activeOverlay !== 'overlay-prev-vid-' + cardId.replace('tcard-','')) {
                document.getElementById(activeOverlay)?.classList.remove('visible');
            }
            // افتح الـ overlay بتاع الكارت ده
            const overlayId = 'overlay-prev-vid-' + cardId.replace('tcard-', '');
            const overlay = document.getElementById(overlayId);
            if (overlay) {
                overlay.classList.add('visible');
                activeOverlay = overlayId;
                // لما تضغط على الـ overlay نفسه افتح الـ file input
                overlay.onclick = (e) => {
                    e.stopPropagation();
                    select(templateId);
                };
            } else {
                // لو مفيش preview video، افتح الـ upload مباشرة
                select(templateId);
            }
        }

        // اقفل أي overlay لو ضغط برا
        document.addEventListener('click', (e) => {
            if (activeOverlay && !e.target.closest('.template-card')) {
                document.getElementById(activeOverlay)?.classList.remove('visible');
                activeOverlay = null;
            }
        });

        // ── Generate thumbnail from video midpoint ────────────────────
        function generateCardThumbnail(vidId, thumbTime) {
            const v = document.getElementById(vidId);
            if (!v) return;

            function doSeek() {
                const dur = v.duration;
                if (!dur || isNaN(dur)) return;
                const seekTo = (thumbTime !== undefined && thumbTime !== null && thumbTime > 0)
                    ? Math.min(thumbTime, dur - 0.1)
                    : dur / 2;
                v.currentTime = seekTo;
            }

            function captureFrame() {
                try {
                    if (v.videoWidth === 0 || v.readyState < 2) {
                        // مش جاهز — جرب تاني بعد شوية
                        setTimeout(captureFrame, 200);
                        return;
                    }
                    const canvas = document.createElement('canvas');
                    canvas.width = v.videoWidth || 640;
                    canvas.height = v.videoHeight || 360;
                    canvas.getContext('2d').drawImage(v, 0, 0, canvas.width, canvas.height);
                    const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
                    const placeholder = document.getElementById('thumb-' + vidId);
                    if (placeholder) {
                        if (placeholder.tagName === 'IMG') {
                            placeholder.src = dataUrl;
                        } else {
                            const img = document.createElement('img');
                            img.src = dataUrl;
                            img.id = 'thumb-' + vidId;
                            img.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:cover;';
                            placeholder.replaceWith(img);
                        }
                    }
                } catch(e) {}
            }

            function onReady() {
                doSeek();
                v.addEventListener('seeked', captureFrame, { once: true });
                // fallback لو الـ seeked مش بيطلع
                setTimeout(() => captureFrame(), 800);
            }

            if (v.readyState >= 2) {
                onReady();
            } else if (v.readyState >= 1) {
                // metadata جاهزة بس data لسه مش
                v.addEventListener('canplay', onReady, { once: true });
                v.preload = 'auto';
                v.load();
            } else {
                v.addEventListener('loadedmetadata', () => {
                    v.addEventListener('canplay', onReady, { once: true });
                }, { once: true });
                v.preload = 'auto';
                v.load();
            }
        }

        // ── جيب القوالب من الـ API وابني الكروت ─────────────────────────
        async function init() {
            const grid = document.getElementById('templates-grid');
            showSkeletons(3);

            try {
                const res = await fetch(`${API_URL}/api/templates`);
                const data = await res.json();
                templates = data.templates || [];
                buildHeroCarousel(templates);

                if (templates.length === 0) {
                    grid.innerHTML = `
                        <div class="col-span-3 text-center py-20">
                            <p class="text-gray-400 text-lg">No templates found.</p>
                            <p class="text-gray-600 text-sm mt-2">Add <code>.json</code> + <code>.meta.json</code> files to <code>backend/workflows/</code></p>
                        </div>`;
                    return;
                }

                grid.innerHTML = templates.map((t, i) => buildCard(t, i)).join('');
                // اعمل thumbnail لكل كارت من الـ thumbnail_time أو منتص الفيديو
                templates.forEach((t, i) => {
                    setTimeout(() => generateCardThumbnail(`prev-vid-${i}`, t.thumbnail_time), i * 300);
                });

            } catch (e) {
                console.error('Failed to load templates:', e);
                grid.innerHTML = `
                    <div class="col-span-3 text-center py-20">
                        <p class="text-red-400 text-lg">⚠️ Could not connect to server.</p>
                        <p class="text-gray-500 text-sm mt-2">Make sure the backend is running on <code>${API_URL}</code></p>
                    </div>`;
            }
        }

        function select(id) {
            selectedTemplate = id;
            document.getElementById('file-input').click();
        }

        async function handleFile(e) {
            const file = e.target.files[0];
            if (!file) return;
            const token = localStorage.getItem('gl_token');
            if (!token) { window.location.href = '/login'; return; }
            if (!selectedTemplate) { alert('Please select a template first'); return; }
            openQualityModal(file);
            return;
        }

        async function startProcessing(file) {
            document.getElementById('processing').classList.add('active');
            document.getElementById('processing-text').textContent = 'Your video is generating...';
            fakeProgress = 0;
            startFakeProgress();
            const form = new FormData();
            form.append('logo', file);
            // جمع الـ color controls من الـ spans والـ selects
            const colorSpans = document.querySelectorAll('#color-controls-list span[data-placeholder]');
            const colorSelects = document.querySelectorAll('#color-controls-list select[data-placeholder]');
            const allControls = [...colorSpans, ...colorSelects];
            if (allControls.length > 0) {
                const colorControls = {};
                colorSpans.forEach(span => {
                    const val = span.dataset.value || span.textContent.trim();
                    if (val) colorControls[span.dataset.placeholder] = val;
                });
                colorSelects.forEach(sel => {
                    if (sel.value) colorControls[sel.dataset.placeholder] = sel.value;
                });
                if (Object.keys(colorControls).length > 0) {
                    form.append('color_controls', JSON.stringify(colorControls));
                }
            }

            try {
                const token = localStorage.getItem('gl_token');
                if (!token) { window.location.href = '/login'; return; }

                form.append('quality', selectedQualityValue);
                form.append('aspect_ratio', selectedRatio || '16:9');
                const res = await fetch(`${API_URL}/api/process/${selectedTemplate}`, {
                    method: 'POST',
                    headers: { 'Authorization': 'Bearer ' + token },
                    body: form
                });
                
                const data = await res.json();
                if (res.status === 402 || data.code === 'NO_CREDITS' || data.code === 'NO_POINTS') {
                    stopFakeProgress();
                    document.getElementById('processing').classList.remove('active');
                    const needed = data.required || 0;
                    const have = data.available || 0;
                    if (confirm(`❌ Not enough points!\n\nNeed: ${needed} pts | Have: ${have} pts\n\nBuy more points?`)) {
                        window.location.href = '/dashboard';
                    }
                    return;
                }
                if (!data.success) throw new Error(data.error);

                currentJob = data.jobId;
                
                // حاول WebSocket أولاً، لو فشل استخدم polling
                tryConnectWS(data.jobId);

            } catch (err) {
                if (err.message && err.message.toLowerCase().includes('token')) {
                    localStorage.removeItem('gl_token');
                    localStorage.removeItem('gl_user');
                    window.location.href = '/login';
                } else {
                    showToast('❌ ' + err.message, 'error');
                }
                document.getElementById('processing').classList.remove('active');
            }
        }

        function tryConnectWS(jobId) {
            const wsUrl = `${API_URL.replace('http', 'ws')}/ws`;
            try {
                ws = new WebSocket(wsUrl);
                let wsConnected = false;

                ws.onopen = () => {
                    wsConnected = true;
                    ws.send(JSON.stringify({ type: 'subscribe', jobId }));
                    console.log('✅ WebSocket connected');
                };

                ws.onmessage = (e) => {
                    const msg = JSON.parse(e.data);
                    if (msg.type === 'update') updateProgress(msg.job);
                    else if (msg.type === 'completed') {
                        if (msg.videoId) window._lastVideoId = msg.videoId;
                        showResult(msg);
                        addNotif('video', '✅ Video Ready!', 'Your logo animation is ready to download.');
                    }
                    else if (msg.type === 'videoSaved') {
                        window._lastVideoId = msg.videoId;
                    }
                    else if (msg.type === 'error') {
                        if (msg.message && msg.message.toLowerCase().includes('token')) {
                        localStorage.removeItem('gl_token');
                        localStorage.removeItem('gl_user');
                        window.location.href = '/login';
                    } else {
                        showToast('❌ ' + (msg.message || 'Generation failed'), 'error');
                    }
                        document.getElementById('processing').classList.remove('active');
                    }
                };

                ws.onerror = () => {
                    if (!wsConnected) {
                        console.warn('⚠️ WS failed, switching to polling...');
                        startPolling(jobId);
                    }
                };

                ws.onclose = () => {
                    if (currentJob === jobId) {
                        // WS انقطع، نرجع للـ polling
                        startPolling(jobId);
                    }
                };

            } catch (e) {
                console.warn('WS not available, using polling');
                startPolling(jobId);
            }
        }

        // Polling fallback
        function startPolling(jobId) {
            if (pollingInterval) clearInterval(pollingInterval);
            pollingInterval = setInterval(async () => {
                try {
                    const res = await fetch(`${API_URL}/api/status/${jobId}`);
                    const job = await res.json();
                    
                    updateProgress(job);
                    
                    if (job.status === 'completed') {
                        clearInterval(pollingInterval);
                        const url = job.localUrl || job.outputUrl;
                        showResult({ 
                            outputVideoUrl: url,
                            outputUrl: url,
                            processingTime: job.processingTime,
                            videoId: job.videoId
                        });
                    } else if (job.status === 'error') {
                        clearInterval(pollingInterval);
                        showToast('❌ Error processing your logo. Please try again.', 'error');
                        document.getElementById('processing').classList.remove('active');
                    }
                } catch (e) {
                    console.error('Polling error:', e);
                }
            }, 5000); // كل 5 ثواني
        }

        function connectWS(jobId) {
            tryConnectWS(jobId);
        }

        // Timer-based progress — أكثر واقعية
        let progressTimer = null;
        let fakeProgress = 0;

        function startFakeProgress() {
            fakeProgress = 0;
            if (progressTimer) clearInterval(progressTimer);
            progressTimer = setInterval(() => {
                if (fakeProgress < 90) {
                    const increment = fakeProgress < 30 ? 1.2 : fakeProgress < 60 ? 0.6 : 0.2;
                    fakeProgress = Math.min(fakeProgress + increment, 90);
                    document.getElementById('progress-bar').style.width = fakeProgress.toFixed(1) + '%';
                    document.getElementById('progress-text').textContent = Math.round(fakeProgress) + '%';
                }
            }, 1000);
        }

        function stopFakeProgress() {
            if (progressTimer) clearInterval(progressTimer);
            progressTimer = null;
            document.getElementById('progress-bar').style.transition = 'width 0.8s ease';
            document.getElementById('progress-bar').style.width = '100%';
            document.getElementById('progress-text').textContent = '100%';
        }

        const stageMessages = [
            { at: 0,  text: 'Your video is generating...' },
            { at: 15, text: 'Uploading your logo...' },
            { at: 30, text: 'Building 3D structure...' },
            { at: 50, text: 'Applying materials & lighting...' },
            { at: 65, text: 'Rendering frames...' },
            { at: 80, text: 'Animating touch effect...' },
            { at: 88, text: 'Encoding your video...' },
        ];

        function updateProgress(job) {
            let msg = stageMessages[0].text;
            for (const s of stageMessages) {
                if (fakeProgress >= s.at) msg = s.text;
            }
            document.getElementById('processing-text').textContent = msg;
        }

        function showResult(data) {
            stopFakeProgress();
            document.getElementById('processing').classList.remove('active');
            document.getElementById('result').classList.add('active');
            
            const url = data.outputVideoUrl || data.outputUrl || data.videoUrl;
            if (!url) {
                console.error('❌ No video URL in message:', data);
                alert('Video generation failed - no output URL');
                document.getElementById('processing').classList.remove('active');
                return;
            }
            window.outputUrl = url;

            const video = document.getElementById('result-video');
            video.src = url;
            video.play();

            // meta info
            document.getElementById('result-info').textContent = data.processingTime ? `${data.processingTime}s` : '—';
            document.getElementById('result-template').textContent = selectedTemplate || '—';

            // setup custom controls
            setupVideoControls(video);
        }

        function setupVideoControls(video) {
            const fill = document.getElementById('progress-fill');
            const time = document.getElementById('time-display');
            const playIcon = document.getElementById('play-icon');
            const track = document.getElementById('progress-track');

            const fmt = t => {
                const m = Math.floor(t / 60);
                const s = Math.floor(t % 60).toString().padStart(2, '0');
                return `${m}:${s}`;
            };

            video.addEventListener('timeupdate', () => {
                if (!video.duration) return;
                const pct = (video.currentTime / video.duration) * 100;
                fill.style.width = pct + '%';
                time.textContent = `${fmt(video.currentTime)} / ${fmt(video.duration)}`;
            });

            video.addEventListener('play', () => {
                playIcon.innerHTML = '<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>';
            });
            video.addEventListener('pause', () => {
                playIcon.innerHTML = '<path d="M6 4l14 8-14 8V4z"/>';
            });

            track.addEventListener('click', (e) => {
                const rect = track.getBoundingClientRect();
                const pct = (e.clientX - rect.left) / rect.width;
                video.currentTime = pct * video.duration;
            });
        }

        function togglePlay() {
            const v = document.getElementById('result-video');
            v.paused ? v.play() : v.pause();
        }

        function toggleMute() {
            const v = document.getElementById('result-video');
            v.muted = !v.muted;
            const icon = document.getElementById('mute-icon');
            icon.style.opacity = v.muted ? '0.4' : '1';
        }

        function toggleFullscreen() {
            const wrapper = document.querySelector('.video-wrapper');
            if (!document.fullscreenElement) {
                wrapper.requestFullscreen();
            } else {
                document.exitFullscreen();
            }
        }

        function closeResult() {
            // أخفي الـ result
            document.getElementById('result').classList.remove('active');
            const rv = document.getElementById('result-video');
            if (rv) { rv.pause(); rv.src = ''; }

            // أخفي الـ processing
            document.getElementById('processing').classList.remove('active');

            // reset الـ state كامل
            selectedTemplate = null;
            pendingFile = null;
            currentJob = null;
            window.outputUrl = null;
            window._lastVideoId = null;

            if (pollingInterval) clearInterval(pollingInterval);
            if (ws) { try { ws.close(); } catch(e) {} ws = null; }

            // reset الـ result topbar
            const topbar = document.getElementById('result-topbar');
            if (topbar) topbar.style.display = 'none';

            // reset file input
            const fi = document.getElementById('file-input');
            if (fi) {
                fi.value = '';
                const newFi = fi.cloneNode(true);
                fi.parentNode.replaceChild(newFi, fi);
                newFi.addEventListener('change', handleFile);
            }

            // deselect all template cards
            document.querySelectorAll('.template-card').forEach(c => {
                c.style.borderColor = '';
            });
        }

        function download() {
            if (window.outputUrl) {
                const a = document.createElement('a');
                a.href = window.outputUrl;
                a.download = `touchreveal-${Date.now()}.mp4`;
                a.click();
            }
        }

        init();
    </script>
    <script>
        // ── Pricing ────────────────────────────────────────────────
        let landingPricingData = null;
        let landingPricingCycle = 'monthly';
        const PLAN_QUALITIES = {
            free: ['480p'], basic: ['480p','720p'],
            standard: ['480p','720p','1080p'], pro: ['480p','720p','1080p','4K'],
        };

        async function loadLandingPricing() {
            const DEFAULT = {
                plans: {
                    free:     { label: 'Free',     price: 0,  points: 100  },
                    basic:    { label: 'Basic',    price: 9,  points: 1500 },
                    standard: { label: 'Standard', price: 19, points: 4000 },
                    pro:      { label: 'Pro',      price: 29, points: 7000 },
                },
                annual_plans: {
                    basic:    { price: 77  },
                    standard: { price: 162 },
                    pro:      { price: 247 },
                },
                pts_per_second: { '480p': 7, '720p': 11, '1080p': 27 },
                annual_discount_percent: 27
            };
            try {
                const res = await fetch('/api/plans');
                if (res.ok) {
                    landingPricingData = await res.json();
                } else {
                    landingPricingData = DEFAULT;
                }
            } catch(e) {
                landingPricingData = DEFAULT;
            }
            window._pricingData = landingPricingData;
            const disc = landingPricingData.annual_discount_percent || 27;
            // حدّث الـ discount badge في الـ nav
            if (disc > 0) {
                const badge = document.getElementById('nav-discount-badge');
                const mobileBadge = document.getElementById('mobile-discount-badge');
                const text = disc + '% OFF';
                if (badge) { badge.textContent = text; badge.style.display = 'inline-block'; }
                if (mobileBadge) { mobileBadge.textContent = text; mobileBadge.style.display = 'inline-block'; }
            }
            const badge = document.getElementById('annual-discount-badge');
            if (badge) badge.textContent = 'Save ' + disc + '%';
            renderPricingCards();
        }

        function setPricingCycle(cycle) {
            landingPricingCycle = cycle;
            const mBtn = document.getElementById('price-btn-monthly');
            const aBtn = document.getElementById('price-btn-annual');
            if (mBtn) { mBtn.style.background = cycle==='monthly' ? '#7c3aed' : 'rgba(255,255,255,0.06)'; mBtn.style.color = cycle==='monthly' ? 'white' : '#9ca3af'; }
            if (aBtn) { aBtn.style.background = cycle==='annual' ? '#7c3aed' : 'rgba(255,255,255,0.06)'; aBtn.style.color = cycle==='annual' ? 'white' : '#9ca3af'; }
            renderPricingCards();
        }

        function renderPricingCards() {
            if (!landingPricingData) return;
            const grid = document.getElementById('pricing-grid');
            if (!grid) return;
            const plans = landingPricingData.plans || {};
            const annualPlans = landingPricingData.annual_plans || {};
            const ptsPerSec = landingPricingData.pts_per_second || {'480p':7,'720p':11,'1080p':27};
            const isAnnual = landingPricingCycle === 'annual';

            function calcVids(pts, q) {
                const ptsMap = { '480p': 7, '720p': 11, '1080p': 27, '4K': 27 };
                const cost = (ptsPerSec[q] || ptsMap[q] || 11) * 5;
                return Math.floor(pts / cost);
            }

            const planDescs = { free: 'Try it out', basic: 'For individuals', standard: 'For designers', pro: 'For agencies' };
            const popularPlan = 'standard';

            grid.innerHTML = Object.entries(plans).filter(([id]) => !(isAnnual && id === 'free')).map(([id, p]) => {
                // price دايماً شهري
                const monthlyPrice = p.price || 0;
                const annualMonthly = isAnnual && annualPlans[id] ? annualPlans[id].price : monthlyPrice;
                const annualTotal = Math.round(annualMonthly * 12);
                const displayPrice = isAnnual ? annualMonthly : monthlyPrice;
                const pts = p.points || 0;
                const ptsDisplay = isAnnual && pts > 0 ? (pts*12).toLocaleString() + ' pts/yr' : pts.toLocaleString() + ' pts/mo';
                const ptsSub = isAnnual && pts > 0 ? `(${pts.toLocaleString()} pts/mo)` : '';
                const allowed = PLAN_QUALITIES[id] || ['480p'];
                const mult = isAnnual ? 12 : 1;
                const unit = isAnnual ? 'yr' : 'mo';
                const isPopular = id === popularPlan;

                const qualityRows = allowed.map(q => {
                    const vids = calcVids(pts, q) * mult;
                    return `<li style="display:flex;justify-content:space-between;align-items:center;padding:5px 0;border-bottom:1px solid rgba(255,255,255,0.05);">
                        <span style="font-weight:600;color:white;font-size:0.85rem;">${QUALITY_LABELS[q]}</span>
                        <span style="color:#a78bfa;font-size:0.8rem;">up to ${vids}/${unit}</span>
                    </li>`;
                }).join('');

                const noWatermark = id !== 'free' ? `<li class="flex items-center gap-2 text-gray-300 text-sm" style="padding:5px 0;">✓ No watermark</li>` : `<li class="flex items-center gap-2 text-sm" style="padding:5px 0;color:#6b7280;">✗ Watermark on export</li>`;
                const priority = id === 'pro' ? `<li class="flex items-center gap-2 text-gray-300 text-sm" style="padding:5px 0;">✓ Priority processing</li>` : '';

                const btnStyle = isPopular
                    ? 'background:#7c3aed;color:white;border:none;'
                    : 'background:transparent;color:white;border:1px solid rgba(255,255,255,0.1);';
                const btnText = id === 'free' ? 'Get Started' : isAnnual ? `Get ${p.label} Annual` : 'Get Started';

                return `<div class="pricing-card glass-panel rounded-3xl p-7 border ${isPopular?'border-primary-500/50 glow-purple':'border-white/5'} relative overflow-hidden" style="display:flex;flex-direction:column;${isPopular?'transform:scale(1.04);':''}">
                    ${isPopular ? '<div class="absolute top-0 right-0 bg-primary-500 text-white text-xs font-bold px-4 py-1 rounded-bl-xl">POPULAR</div>' : ''}
                    <h3 class="text-lg font-semibold text-white mb-1">${p.label}</h3>
                    <p class="text-sm mb-5" style="color:#6b7280;">${planDescs[id]||''}</p>
                    <div class="mb-2">
                        <span class="text-4xl font-bold text-white">$${displayPrice}</span>
                        <span class="text-gray-400 text-sm">/mo${isAnnual && displayPrice > 0 ? ` · $${annualTotal}/yr` : ''}</span>
                    </div>
                    <div class="text-violet-400 text-sm font-semibold mb-1">${ptsDisplay}</div>
                    ${ptsSub ? `<div class="text-xs mb-4" style="color:#4b5563;">${ptsSub}</div>` : '<div class="mb-4"></div>'}
                    <ul style="list-style:none;flex:1;margin-bottom:20px;">${qualityRows}${noWatermark}${priority}</ul>
                    <button onclick="window.location='/register'" style="width:100%;padding:11px;border-radius:10px;font-weight:600;font-size:0.9rem;cursor:pointer;transition:all 0.2s;${btnStyle}">${btnText}</button>
                </div>`;
            }).join('');
        }

        loadLandingPricing();

        // ── Report Issue ───────────────────────────────────────────
        let currentReportVideoId = null;

        function openReportModal(videoId) {
            currentReportVideoId = videoId || window._lastVideoId || null;
            const resultEl = document.getElementById('report-result');
            if (resultEl) resultEl.style.display = 'none';
            const submitBtn = document.getElementById('report-submit-btn');
            if (submitBtn) { submitBtn.textContent = 'Submit Report'; submitBtn.disabled = false; }
            document.getElementById('report-modal').style.display = 'flex';
        }

        function closeReportModal() {
            document.getElementById('report-modal').style.display = 'none';
        }

        async function submitReport() {
            const reason = document.getElementById('report-reason').value;
            const resultEl = document.getElementById('report-result');
            const submitBtn = document.getElementById('report-submit-btn');
            submitBtn.textContent = 'Submitting...';
            submitBtn.disabled = true;

            try {
                const res = await fetch('/api/report', {
                    method: 'POST',
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('gl_token'), 'Content-Type': 'application/json' },
                    body: JSON.stringify({ videoId: currentReportVideoId, reason })
                });
                const data = await res.json();
                resultEl.style.display = 'block';
                if (res.ok) {
                    resultEl.style.background = 'rgba(16,185,129,0.1)';
                    resultEl.style.border = '1px solid rgba(16,185,129,0.3)';
                    resultEl.style.color = '#6ee7b7';
                    resultEl.textContent = '✅ Report submitted! We\'ll review and refund your points if applicable.';
                    submitBtn.textContent = 'Submitted';
                } else {
                    resultEl.style.background = 'rgba(239,68,68,0.1)';
                    resultEl.style.border = '1px solid rgba(239,68,68,0.3)';
                    resultEl.style.color = '#fca5a5';
                    resultEl.textContent = '❌ ' + (data.error || 'Failed to submit report');
                    submitBtn.textContent = 'Try Again';
                    submitBtn.disabled = false;
                }
            } catch(e) {
                resultEl.style.display = 'block';
                resultEl.textContent = '❌ Network error. Please try again.';
                submitBtn.textContent = 'Try Again';
                submitBtn.disabled = false;
            }
        }

        // ── Auth State ──────────────────────────────────────────
        (function() {
            const token = localStorage.getItem('gl_token');
            const userStr = localStorage.getItem('gl_user');

            if (token && userStr) {
                try {
                    const user = JSON.parse(userStr);
                    // Show user nav
                    document.getElementById('nav-auth-guest').style.display = 'none';
            const mg = document.getElementById('mobile-nav-guest'); if(mg) mg.style.display='none';
            const mu = document.getElementById('mobile-nav-user'); if(mu) mu.style.display='block';
                    const userNav = document.getElementById('nav-auth-user');
                    userNav.style.removeProperty('display');
                    userNav.style.display = 'flex';
                    document.getElementById('nav-credits').textContent = (user.credits || 0) + ' credits';
                    document.getElementById('nav-avatar').textContent = (user.name || 'U')[0].toUpperCase();

                    // Refresh user data silently
                    fetch('/auth/me', { headers: { 'Authorization': 'Bearer ' + token } })
                        .then(r => r.ok ? r.json() : null)
                        .then(data => {
                            if (data) {
                                localStorage.setItem('gl_user', JSON.stringify(data.user));
                                document.getElementById('nav-credits').textContent = (data.user.credits || 0) + ' credits';
                            }
                        }).catch(() => {});
                } catch(e) {}
            }
        })();

        // ── Color Controls Helpers ─────────────────────────────────
        const HEX_TO_NAME = {
            '#ffffff':'white','#000000':'black','#ef4444':'red','#3b82f6':'blue',
            '#22c55e':'green','#eab308':'yellow','#f97316':'orange','#a855f7':'purple',
            '#ec4899':'pink','#6b7280':'gray','#1e3a5f':'navy','#92400e':'brown',
            '#d97706':'gold','#9ca3af':'silver','#d4b896':'beige'
        };

        function hexToColorName(hex) {
            return HEX_TO_NAME[hex.toLowerCase()] || hex;
        }

        function updateColorName(ctrlId, hexValue) {
            const nameEl = document.getElementById('ctrl-name-' + ctrlId);
            if (nameEl) {
                const name = hexToColorName(hexValue);
                nameEl.textContent = name;
                nameEl.dataset.value = name;
            }
        }

        function updateColorPicker(ctrlId, colorName) {
            const picker = document.getElementById('ctrl-picker-' + ctrlId);
            if (!picker) return;
            const colorMap = {
                'white':'#ffffff','black':'#000000','red':'#ef4444','blue':'#3b82f6',
                'green':'#22c55e','yellow':'#eab308','orange':'#f97316','purple':'#a855f7',
                'pink':'#ec4899','gray':'#6b7280','grey':'#6b7280','navy':'#1e3a5f',
                'brown':'#92400e','gold':'#d97706','silver':'#9ca3af','beige':'#d4b896'
            };
            if (colorMap[colorName.toLowerCase()]) picker.value = colorMap[colorName.toLowerCase()];
        }

        function setColor(ctrlId, colorName) {
            updateColorPicker(ctrlId, colorName);
            const nameEl = document.getElementById('ctrl-name-' + ctrlId);
            if (nameEl) { nameEl.textContent = colorName; nameEl.dataset.value = colorName; }
        }

        // ── Color Controls Helpers End ─────────────────────────────
        let notifications = JSON.parse(localStorage.getItem('shomotion_notifs') || '[]');

        function saveNotifs() { localStorage.setItem('shomotion_notifs', JSON.stringify(notifications.slice(0,20))); }

        function addNotif(type, title, body) {
            notifications.unshift({ id: Date.now(), type, title, body, read: false, time: new Date().toISOString() });
            saveNotifs(); renderNotifs(); updateBadge();
        }

        function renderNotifs() {
            const list = document.getElementById('notif-list');
            if (!list) return;
            if (!notifications.length) { list.innerHTML = '<div class="notif-empty">No notifications yet</div>'; return; }
            const icons = { video:{bg:'rgba(124,58,237,0.2)',emoji:'🎬'}, refund:{bg:'rgba(16,185,129,0.2)',emoji:'💰'}, error:{bg:'rgba(239,68,68,0.2)',emoji:'❌'} };
            list.innerHTML = notifications.slice(0,10).map(n => {
                const ic = icons[n.type] || {bg:'rgba(255,255,255,0.1)',emoji:'🔔'};
                const time = new Date(n.time).toLocaleTimeString('en-US',{hour:'2-digit',minute:'2-digit'});
                return `<div class="notif-item ${n.read?'':'unread'}" onclick="markRead(${n.id})">
                    <div class="notif-icon" style="background:${ic.bg};">${ic.emoji}</div>
                    <div style="flex:1;">
                        <div style="font-weight:600;color:white;font-size:0.82rem;margin-bottom:2px;">${n.title}</div>
                        <div style="color:#9ca3af;font-size:0.76rem;">${n.body}</div>
                        <div style="color:#4b5563;font-size:0.68rem;margin-top:3px;">${time}</div>
                    </div>
                </div>`;
            }).join('');
        }

        function updateBadge() {
            const unread = notifications.filter(n=>!n.read).length;
            const badge = document.getElementById('notif-badge');
            if (!badge) return;
            if (unread > 0) { badge.textContent = unread>9?'9+':unread; badge.classList.add('show'); }
            else badge.classList.remove('show');
        }

        function markRead(id) {
            notifications = notifications.map(n => n.id===id?{...n,read:true}:n);
            saveNotifs(); renderNotifs(); updateBadge();
        }

        function clearAllNotifs() {
            notifications=[]; saveNotifs(); renderNotifs(); updateBadge();
            document.getElementById('notif-dropdown')?.classList.remove('open');
        }

        function toggleNotif(e) {
            e.stopPropagation();
            const dd = document.getElementById('notif-dropdown');
            dd.classList.toggle('open');
            if (dd.classList.contains('open')) {
                notifications=notifications.map(n=>({...n,read:true}));
                saveNotifs(); updateBadge();
            }
        }

        document.addEventListener('click', ()=>document.getElementById('notif-dropdown')?.classList.remove('open'));
        renderNotifs(); updateBadge();

        // ── Mobile Menu ────────────────────────────────────────────
        let mobileMenuOpen = false;
        function toggleMobileMenu() {
            mobileMenuOpen = !mobileMenuOpen;
            const menu = document.getElementById('mobile-menu');
            menu.style.display = mobileMenuOpen ? 'flex' : 'none';
            // animate hamburger
            document.getElementById('ham-1').style.transform = mobileMenuOpen ? 'rotate(45deg) translate(4px,4px)' : '';
            document.getElementById('ham-2').style.opacity = mobileMenuOpen ? '0' : '1';
            document.getElementById('ham-3').style.transform = mobileMenuOpen ? 'rotate(-45deg) translate(4px,-4px)' : '';
        }
        function closeMobileMenu() {
            mobileMenuOpen = false;
            document.getElementById('mobile-menu').style.display = 'none';
            document.getElementById('ham-1').style.transform = '';
            document.getElementById('ham-2').style.opacity = '1';
            document.getElementById('ham-3').style.transform = '';
        }

        // تتبع تفاعل اليوزر عشان نسمح بالصوت
        window._userInteracted = false;
        document.addEventListener('click', () => { window._userInteracted = true; }, { once: true });

        // ── Add auth header to fetch requests ──────────────────
        const _origFetch = window.fetch;
        // Patch process endpoint to add auth
        const _origUpload = window.uploadAndProcess;
        if (window.uploadAndProcess) {
            window.uploadAndProcess = async function(file, template) {
                const token = localStorage.getItem('gl_token');
                if (!token) { window.location.href = '/login'; return; }
                return _origUpload.call(this, file, template);
            };
        }
    </script>
</body>
</html>