<!DOCTYPE html>
<html lang="hr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Editor - TapTap Card</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: #f5f7fa;
            overflow-x: hidden;
        }
        
        /* Header */
        .header {
            background: white;
            border-bottom: 1px solid #e5e7eb;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .header h1 {
            font-size: 20px;
            color: #111827;
        }
        .header-actions {
            display: flex;
            gap: 10px;
        }
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.2s;
        }
        .btn-primary {
            background: #2563eb;
            color: white;
        }
        .btn-primary:hover { background: #1d4ed8; }
        .btn-secondary {
            background: white;
            border: 1px solid #e5e7eb;
            color: #374151;
        }
        .btn-secondary:hover { background: #f9fafb; }
        
        /* Main Layout */
        .container {
            display: flex;
            height: calc(100vh - 62px);
        }
        
        /* Sidebar (Lijevo - Daljinski) */
        .sidebar {
            width: 450px;
            background: white;
            border-right: 1px solid #e5e7eb;
            overflow-y: auto;
            padding: 30px;
        }
        
        /* Tabs */
        .tabs {
            display: flex;
            gap: 5px;
            margin-bottom: 30px;
            border-bottom: 2px solid #f3f4f6;
        }
        .tab {
            padding: 12px 20px;
            cursor: pointer;
            color: #6b7280;
            font-weight: 500;
            border-bottom: 2px solid transparent;
            margin-bottom: -2px;
            transition: all 0.2s;
        }
        .tab:hover { color: #374151; }
        .tab.active {
            color: #2563eb;
            border-bottom-color: #2563eb;
        }
        
        /* Add Content Button */
        .add-content-btn {
            width: 100%;
            padding: 16px;
            background: #2563eb;
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: 600;
            font-size: 15px;
            margin-bottom: 20px;
            transition: background 0.2s;
        }
        .add-content-btn:hover { background: #1d4ed8; }
        
        /* Module Item */
        .module-item {
            background: #f9fafb;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 16px;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
            cursor: grab;
            transition: all 0.2s;
        }
        .module-item:hover {
            border-color: #2563eb;
            box-shadow: 0 2px 8px rgba(37, 99, 235, 0.1);
        }
        .module-item.dragging {
            opacity: 0.5;
            cursor: grabbing;
        }
        .module-item.locked {
            cursor: default;
            opacity: 0.6;
        }
        .module-item.locked:hover {
            border-color: #e5e7eb;
            box-shadow: none;
        }
        
        .drag-handle {
            font-size: 20px;
            color: #9ca3af;
            cursor: grab;
        }
        .module-item.locked .drag-handle {
            cursor: not-allowed;
        }
        
        .module-icon {
            width: 40px;
            height: 40px;
            background: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }
        
        .module-info {
            flex: 1;
        }
        .module-info h4 {
            font-size: 15px;
            color: #111827;
            margin-bottom: 3px;
        }
        .module-info p {
            font-size: 13px;
            color: #6b7280;
        }
        
        .module-badge {
            background: #ef4444;
            color: white;
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 600;
        }
        
        /* Config Form (kad se klikne modul) */
        .config-form {
            background: white;
            border: 2px solid #2563eb;
            border-radius: 10px;
            padding: 20px;
            margin-top: 10px;
        }
        .config-form h4 {
            font-size: 16px;
            margin-bottom: 15px;
            color: #111827;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            color: #374151;
            font-size: 13px;
            font-weight: 500;
        }
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            font-size: 14px;
        }
        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #2563eb;
        }
        .config-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        .btn-save {
            flex: 1;
            background: #10b981;
            color: white;
        }
        .btn-save:hover { background: #059669; }
        .btn-cancel {
            flex: 1;
            background: #f3f4f6;
            color: #374151;
        }
        .btn-cancel:hover { background: #e5e7eb; }
        
        /* Preview (Desno - Televizor) */
        .preview-area {
            flex: 1;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
        }
        
        /* Phone Mockup */
        .phone-mockup {
            width: 375px;
            height: 667px;
            background: black;
            border-radius: 40px;
            padding: 12px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
            position: relative;
        }
        .phone-notch {
            position: absolute;
            top: 12px;
            left: 50%;
            transform: translateX(-50%);
            width: 150px;
            height: 25px;
            background: black;
            border-radius: 0 0 20px 20px;
            z-index: 10;
        }
        .phone-screen {
            width: 100%;
            height: 100%;
            background: white;
            border-radius: 28px;
            overflow: hidden;
        }
        .phone-screen iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
        
        /* Mobile responsiveness */
        @media (max-width: 768px) {
            .preview-area {
                display: none;
            }
            .sidebar {
                width: 100%;
            }
        }
        
        /* Loading */
        .loading {
            text-align: center;
            padding: 40px;
            color: #6b7280;
        }
        
        /* Empty state */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #9ca3af;
        }
        .empty-state svg {
            width: 80px;
            height: 80px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <h1>✨ Live Editor</h1>
        <div class="header-actions">
            <button class="btn btn-secondary" onclick="window.location.href='user-panel.php'">← Natrag</button>
            <button class="btn btn-primary" onclick="saveOrder()">💾 Spremi redoslijed</button>
        </div>
    </div>
    
    <!-- Main Layout -->
    <div class="container">
        <!-- Sidebar (Daljinski) -->
        <div class="sidebar">
            <!-- Tabs -->
            <div class="tabs">
                <div class="tab active" data-tab="content">🔗 Content</div>
                <div class="tab" data-tab="about">👤 About</div>
                <div class="tab" data-tab="appearance">🎨 Appearance</div>
            </div>
            
            <!-- Content Tab -->
            <div id="content-tab" class="tab-content">
                <button class="add-content-btn">➕ Add Content</button>
                
                <div id="modulesContainer">
                    <div class="loading">Učitavam module...</div>
                </div>
            </div>
            
            <!-- About Tab -->
            <div id="about-tab" class="tab-content" style="display: none;">
                <div class="empty-state">
                    <p>Ovdje će biti postavke profila</p>
                </div>
            </div>
            
            <!-- Appearance Tab -->
            <div id="appearance-tab" class="tab-content" style="display: none;">
                <div class="empty-state">
                    <p>Ovdje će biti postavke izgleda</p>
                </div>
            </div>
        </div>
        
        <!-- Preview (Televizor) -->
        <div class="preview-area">
            <div class="phone-mockup">
                <div class="phone-notch"></div>
                <div class="phone-screen">
                    <iframe id="previewFrame" src="about:blank"></iframe>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let userData = null;
        let modules = [];
        let availableModules = [
            { name: 'vcard', icon: '📇', title: 'vCard', desc: 'Download contact', enabled: true },
            { name: 'qr_code', icon: '📱', title: 'QR Code', desc: 'Share with QR', enabled: true },
            { name: 'mapa', icon: '🗺️', title: 'Maps', desc: 'Show location', enabled: true },
            { name: 'text_block', icon: '📝', title: 'About Me', desc: 'Custom text', enabled: true },
            { name: 'working_hours', icon: '🕐', title: 'Working Hours', desc: 'Business hours', enabled: true },
            { name: 'instagram_feed', icon: '📸', title: 'Instagram', desc: 'Feed gallery', enabled: false, pro: true },
            { name: 'google_reviews', icon: '⭐', title: 'Reviews', desc: 'Google ratings', enabled: false, pro: true },
            { name: 'gallery', icon: '🖼️', title: 'Images', desc: 'Photo gallery', enabled: false, pro: true },
            { name: 'team', icon: '👥', title: 'Team Members', desc: 'Show your team', enabled: false, pro: true },
            { name: 'files', icon: '📁', title: 'Files', desc: 'Upload files', enabled: false, pro: true }
        ];
        
        let draggedElement = null;
        let editingModule = null;
        
        // Check auth
        async function checkAuth() {
            const token = localStorage.getItem('user_token');
            if (!token) {
                window.location.href = 'user-login.php';
                return;
            }
            
            try {
                const response = await fetch('/api.php/user/me', {
                    headers: { 'Authorization': 'Bearer ' + token }
                });
                
                if (!response.ok) throw new Error('Unauthorized');
                
                userData = await response.json();
                modules = userData.modules || [];
                loadPreview();
                renderModules();
            } catch (error) {
                localStorage.removeItem('user_token');
                window.location.href = 'user-login.php';
            }
        }
        
        // Render modules
        function renderModules() {
            const container = document.getElementById('modulesContainer');
            container.innerHTML = '';
            
            // Sort by sort_order
            const sortedModules = [...modules].sort((a, b) => a.sort_order - b.sort_order);
            
            sortedModules.forEach(module => {
                const info = availableModules.find(m => m.name === module.modul_name);
                if (!info) return;
                
                const div = document.createElement('div');
                div.className = 'module-item' + (info.pro && !info.enabled ? ' locked' : '');
                div.draggable = !info.pro;
                div.dataset.moduleId = module.id;
                div.dataset.moduleName = module.modul_name;
                
                div.innerHTML = `
                    <div class="drag-handle">☰</div>
                    <div class="module-icon">${info.icon}</div>
                    <div class="module-info">
                        <h4>${info.title}</h4>
                        <p>${info.desc}</p>
                    </div>
                    ${info.pro && !info.enabled ? '<span class="module-badge">🔒 PRO</span>' : ''}
                `;
                
                // Click to edit
                if (!info.pro) {
                    div.addEventListener('click', () => showConfig(module));
                }
                
                // Drag events
                if (!info.pro) {
                    div.addEventListener('dragstart', handleDragStart);
                    div.addEventListener('dragover', handleDragOver);
                    div.addEventListener('drop', handleDrop);
                    div.addEventListener('dragend', handleDragEnd);
                }
                
                container.appendChild(div);
                
                // Show config if editing
                if (editingModule && editingModule.id === module.id) {
                    showConfigForm(div, module);
                }
            });
        }
        
        // Drag & Drop handlers
        function handleDragStart(e) {
            draggedElement = e.currentTarget;
            e.currentTarget.classList.add('dragging');
        }
        
        function handleDragOver(e) {
            e.preventDefault();
            const afterElement = getDragAfterElement(e.currentTarget.parentElement, e.clientY);
            if (afterElement == null) {
                e.currentTarget.parentElement.appendChild(draggedElement);
            } else {
                e.currentTarget.parentElement.insertBefore(draggedElement, afterElement);
            }
        }
        
        function handleDrop(e) {
            e.preventDefault();
        }
        
        function handleDragEnd(e) {
            e.currentTarget.classList.remove('dragging');
            updateModuleOrder();
        }
        
        function getDragAfterElement(container, y) {
            const draggableElements = [...container.querySelectorAll('.module-item:not(.dragging)')];
            
            return draggableElements.reduce((closest, child) => {
                const box = child.getBoundingClientRect();
                const offset = y - box.top - box.height / 2;
                
                if (offset < 0 && offset > closest.offset) {
                    return { offset: offset, element: child };
                } else {
                    return closest;
                }
            }, { offset: Number.NEGATIVE_INFINITY }).element;
        }
        
        // Update order after drag
        function updateModuleOrder() {
            const items = document.querySelectorAll('.module-item');
            items.forEach((item, index) => {
                const moduleId = item.dataset.moduleId;
                const module = modules.find(m => m.id == moduleId);
                if (module) {
                    module.sort_order = index;
                }
            });
        }
        
        // Save order to server
        async function saveOrder() {
            const token = localStorage.getItem('user_token');
            const orderData = modules.map(m => ({ id: m.id, sort_order: m.sort_order }));
            
            const response = await fetch('/api.php/user/modules/order', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ order: orderData })
            });
            
            if (response.ok) {
                alert('✅ Redoslijed spremljen!');
                loadPreview(); // Reload preview
            } else {
                alert('❌ Greška pri spremanju');
            }
        }
        
        // Show config form
        function showConfig(module) {
            editingModule = module;
            renderModules(); // Re-render to show form
        }
        
        function showConfigForm(parentDiv, module) {
            const info = availableModules.find(m => m.name === module.modul_name);
            
            const form = document.createElement('div');
            form.className = 'config-form';
            
            let formHTML = `<h4>⚙️ ${info.title} postavke</h4>`;
            
            // Different forms for different modules
            if (module.modul_name === 'mapa') {
                formHTML += `
                    <div class="form-group">
                        <label>Naslov sekcije</label>
                        <input type="text" id="config_title" value="${module.config?.title || ''}" placeholder="Pronađi nas">
                    </div>
                    <div class="form-group">
                        <label>Ulica</label>
                        <input type="text" id="config_street" value="${module.config?.street || ''}" placeholder="Ulica 123">
                    </div>
                    <div class="form-group">
                        <label>Grad</label>
                        <input type="text" id="config_city" value="${module.config?.city || ''}" placeholder="Zagreb">
                    </div>
                    <div class="form-group">
                        <label>Google Maps link (ili naziv mjesta)</label>
                        <input type="text" id="config_link" value="${module.config?.link || ''}" placeholder="https://maps.app.goo.gl/...">
                    </div>
                `;
            } else if (module.modul_name === 'text_block') {
                formHTML += `
                    <div class="form-group">
                        <label>Naslov sekcije</label>
                        <input type="text" id="config_title" value="${module.config?.title || ''}" placeholder="O meni">
                    </div>
                    <div class="form-group">
                        <label>Tekst (max 19/5000)</label>
                        <textarea id="config_text" rows="6" maxlength="5000">${module.config?.text || ''}</textarea>
                    </div>
                `;
            } else if (module.modul_name === 'working_hours') {
                const config = module.config || {};
                formHTML += `
                    <div class="form-group">
                        <label>Radnim danom</label>
                        <input type="text" id="config_weekday" value="${config.weekday || ''}" placeholder="08:00 - 16:00">
                    </div>
                    <div class="form-group">
                        <label>Subotom</label>
                        <input type="text" id="config_saturday" value="${config.saturday || ''}" placeholder="Ne radimo">
                    </div>
                    <div class="form-group">
                        <label>Nedjeljom</label>
                        <input type="text" id="config_sunday" value="${config.sunday || ''}" placeholder="Ne radimo">
                    </div>
                `;
            }
            
            formHTML += `
                <div class="config-actions">
                    <button class="btn btn-save" onclick="saveConfig(${module.id})">💾 Spremi</button>
                    <button class="btn btn-cancel" onclick="cancelConfig()">✖️ Odustani</button>
                </div>
            `;
            
            form.innerHTML = formHTML;
            parentDiv.appendChild(form);
        }
        
        async function saveConfig(moduleId) {
            const module = modules.find(m => m.id === moduleId);
            let config = {};
            
            if (module.modul_name === 'mapa') {
                config = {
                    title: document.getElementById('config_title')?.value || '',
                    street: document.getElementById('config_street')?.value || '',
                    city: document.getElementById('config_city')?.value || '',
                    link: document.getElementById('config_link')?.value || ''
                };
            } else if (module.modul_name === 'text_block') {
                config = {
                    title: document.getElementById('config_title')?.value || '',
                    text: document.getElementById('config_text')?.value || ''
                };
            } else if (module.modul_name === 'working_hours') {
                config = {
                    type: 'weekday_weekend',
                    weekday: document.getElementById('config_weekday')?.value || '',
                    saturday: document.getElementById('config_saturday')?.value || '',
                    sunday: document.getElementById('config_sunday')?.value || ''
                };
            }
            
            const token = localStorage.getItem('user_token');
            const response = await fetch('/api.php/user/module', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ module_name: module.modul_name, config })
            });
            
            if (response.ok) {
                editingModule = null;
                await loadModules();
                loadPreview(); // Live update!
            } else {
                alert('❌ Greška pri spremanju');
            }
        }
        
        function cancelConfig() {
            editingModule = null;
            renderModules();
        }
        
        // Load preview
        function loadPreview() {
            if (!userData) return;
            const iframe = document.getElementById('previewFrame');
            iframe.src = `/card.php?slug=${userData.slug}&preview=1&t=${Date.now()}`;
        }
        
        // Tabs
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                
                document.querySelectorAll('.tab-content').forEach(c => c.style.display = 'none');
                document.getElementById(tab.dataset.tab + '-tab').style.display = 'block';
            });
        });
        
        // Init
        checkAuth();
    </script>
</body>
</html>
