// QUEEN Florist - Simple Version JavaScript

// Data produk
let products = [
    {
        id: 1,
        name: 'Standing Flower Premium',
        category: 'standing-flower',
        categoryName: 'Standing Flower',
        description: 'Standing flower mewah dengan bunga segar pilihan',
        image: 'assets/images/standing-flower-1.jpg',
        bestSeller: true
    },
    {
        id: 2,
        name: 'Paper Flower Art',
        category: 'paper-flower',
        categoryName: 'Paper Flower',
        description: 'Karya seni bunga kertas handmade',
        image: 'assets/images/paper-flower-1.jpg',
        bestSeller: true
    },
    {
        id: 3,
        name: 'Duka Cita Elegan',
        category: 'duka-cita',
        categoryName: 'Duka Cita',
        description: 'Rangkaian bunga untuk ucapan duka cita',
        image: 'assets/images/duka-cita-1.jpg',
        bestSeller: true
    },
    {
        id: 4,
        name: 'Bouquet Love',
        category: 'bouquet',
        categoryName: 'Bouquet',
        description: 'Buket bunga romantis untuk orang tersayang',
        image: 'assets/images/bouquet-1.jpg',
        bestSeller: true
    },
    {
        id: 5,
        name: 'Wedding Car Royal',
        category: 'wedding-car',
        categoryName: 'Wedding Car',
        description: 'Dekorasi mobil pengantin tema royal',
        image: 'assets/images/wedding-car-1.jpg',
        bestSeller: true
    },
    {
        id: 6,
        name: 'Balloon Decoration Party',
        category: 'balloon-decoration',
        categoryName: 'Balloon Decoration',
        description: 'Dekorasi balon untuk pesta ulang tahun',
        image: 'assets/images/balloon-decoration-1.jpg',
        bestSeller: true
    },
    {
        id: 7,
        name: 'Kado Rustic Classic',
        category: 'kado-rustic',
        categoryName: 'Kado Rustic',
        description: 'Kado unik dengan gaya rustic',
        image: 'assets/images/kado-rustic-1.jpg',
        bestSeller: true
    },
    {
        id: 8,
        name: 'Balloon Parcel Happy',
        category: 'balloon-parcel',
        categoryName: 'Balloon Parcel',
        description: 'Parcel balon untuk berbagai kesempatan',
        image: 'assets/images/balloon-parcel-1.jpg',
        bestSeller: true
    },
    {
        id: 9,
        name: 'Snack Bouquet Deluxe',
        category: 'snack-bouquet',
        categoryName: 'Snack Bouquet',
        description: 'Buket snack premium',
        image: 'assets/images/snack-bouquet-1.jpg',
        bestSeller: true
    },
    {
        id: 10,
        name: 'Tart Snack Sweet',
        category: 'tart-snack',
        categoryName: 'Tart Snack',
        description: 'Tart snack mini manis dan lucu',
        image: 'assets/images/tart-snack-1.jpg',
        bestSeller: true
    }
];

// Global variables
let currentCategory = 'all';
let selectedProduct = null;
let isAdminLoggedIn = false;

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    loadProducts();
    setupEventListeners();
    loadProductsFromStorage();
});

// Setup event listeners
function setupEventListeners() {
    // Category buttons
    document.querySelectorAll('[data-category]').forEach(button => {
        button.addEventListener('click', function() {
            filterProducts(this.dataset.category);
            
            // Update active state
            document.querySelectorAll('[data-category]').forEach(btn => {
                btn.classList.remove('active');
            });
            this.classList.add('active');
        });
    });

    // Order form
    document.getElementById('orderForm').addEventListener('submit', function(e) {
        e.preventDefault();
        submitOrder();
    });

    // Admin login form
    document.getElementById('adminLoginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        adminLogin();
    });

    // New product form
    document.getElementById('newProductForm').addEventListener('submit', function(e) {
        e.preventDefault();
        addNewProduct();
    });
}

// Load products from localStorage
function loadProductsFromStorage() {
    const savedProducts = localStorage.getItem('queenFloristProducts');
    if (savedProducts) {
        products = JSON.parse(savedProducts);
        loadProducts();
    }
}

// Save products to localStorage
function saveProductsToStorage() {
    localStorage.setItem('queenFloristProducts', JSON.stringify(products));
}

// Load and display products
function loadProducts() {
    const grid = document.getElementById('productsGrid');
    const filteredProducts = currentCategory === 'all' 
        ? products.filter(p => p.bestSeller)
        : products.filter(p => p.category === currentCategory && p.bestSeller);

    if (filteredProducts.length === 0) {
        grid.innerHTML = `
            <div class="col-12">
                <div class="empty-state">
                    <i class="fas fa-spa"></i>
                    <h5>Belum ada produk untuk kategori ini</h5>
                    <p>Silakan pilih kategori lain atau tambahkan produk baru</p>
                </div>
            </div>
        `;
        return;
    }

    grid.innerHTML = filteredProducts.map(product => `
        <div class="product-card fade-in" onclick="openOrderModal(${product.id})">
            <div class="product-image">
                ${product.image ? `<img src="${product.image}" alt="${product.name}" onerror="this.style.display='none'; this.parentElement.innerHTML='🌸';">` : '🌸'}
                ${product.bestSeller ? '<span class="best-seller">⭐ Best Seller</span>' : ''}
            </div>
            <div class="product-info">
                <h5 class="product-title">${product.name}</h5>
                <p class="product-category">${product.categoryName}</p>
                <p class="product-description">${product.description}</p>
                <button class="btn btn-success btn-sm w-100">
                    <i class="fab fa-whatsapp me-2"></i>Order via WhatsApp
                </button>
            </div>
        </div>
    `).join('');
}

// Filter products by category
function filterProducts(category) {
    currentCategory = category;
    loadProducts();
}

// Open order modal
function openOrderModal(productId) {
    selectedProduct = products.find(p => p.id === productId);
    if (!selectedProduct) return;

    document.getElementById('modalProductImage').src = selectedProduct.image || '';
    document.getElementById('modalProductName').textContent = selectedProduct.name;
    document.getElementById('modalProductCategory').textContent = selectedProduct.categoryName;
    document.getElementById('modalProductDescription').textContent = selectedProduct.description;

    const modal = new bootstrap.Modal(document.getElementById('orderModal'));
    modal.show();
}

// Submit order to WhatsApp
function submitOrder() {
    const name = document.getElementById('customerName').value.trim();
    const note = document.getElementById('customerNote').value.trim();

    if (!name) {
        alert('Mohon isi nama Anda terlebih dahulu');
        return;
    }

    const message = `Halo Queen Florist, saya ingin memesan:\n\n` +
        `Produk: ${selectedProduct.name}\n` +
        `Kategori: ${selectedProduct.categoryName}\n` +
        `Nama: ${name}\n` +
        `Catatan: ${note || '-'}\n\n` +
        `Mohon informasikan ketersediaan dan detail pemesanannya. Terima kasih!`;

    const whatsappUrl = `https://wa.me/6281223968122?text=${encodeURIComponent(message)}`;
    
    // Open WhatsApp
    window.open(whatsappUrl, '_blank');

    // Reset form and close modal
    document.getElementById('customerName').value = '';
    document.getElementById('customerNote').value = '';
    
    const modal = bootstrap.Modal.getInstance(document.getElementById('orderModal'));
    modal.hide();

    // Show success message
    setTimeout(() => {
        alert('Terima kasih! Jika WhatsApp tidak terbuka otomatis, silakan hubungi langsung: +62812-2396-8122');
    }, 1000);
}

// Admin functions
function showAdminModal() {
    const modal = new bootstrap.Modal(document.getElementById('adminModal'));
    modal.show();
}

function adminLogin() {
    const username = document.getElementById('adminUsername').value;
    const password = document.getElementById('adminPassword').value;

    // Simple authentication (in production, use proper authentication)
    if (username === 'queenflorist' && password === 'password123') {
        isAdminLoggedIn = true;
        
        // Close login modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('adminModal'));
        modal.hide();

        // Show admin panel
        document.getElementById('adminPanel').style.display = 'block';
        document.body.style.overflow = 'hidden'; // Prevent scrolling main page
        
        // Load admin products
        loadAdminProducts();

        // Clear form
        document.getElementById('adminUsername').value = '';
        document.getElementById('adminPassword').value = '';
    } else {
        alert('Username atau password salah!');
    }
}

function adminLogout() {
    isAdminLoggedIn = false;
    document.getElementById('adminPanel').style.display = 'none';
    document.body.style.overflow = 'auto'; // Enable scrolling
}

function showAddProductForm() {
    document.getElementById('addProductForm').style.display = 'block';
}

function hideAddProductForm() {
    document.getElementById('addProductForm').style.display = 'none';
    document.getElementById('newProductForm').reset();
}

function addNewProduct() {
    const name = document.getElementById('newProductName').value;
    const category = document.getElementById('newProductCategory').value;
    const description = document.getElementById('newProductDescription').value;
    const image = document.getElementById('newProductImage').value;
    const bestSeller = document.getElementById('newProductBestSeller').checked;

    if (!name || !category || !description) {
        alert('Mohon lengkapi semua field yang diperlukan');
        return;
    }

    const categoryNames = {
        'standing-flower': 'Standing Flower',
        'paper-flower': 'Paper Flower',
        'duka-cita': 'Duka Cita',
        'bouquet': 'Bouquet',
        'wedding-car': 'Wedding Car',
        'balloon-decoration': 'Balloon Decoration',
        'kado-rustic': 'Kado Rustic',
        'balloon-parcel': 'Balloon Parcel',
        'snack-bouquet': 'Snack Bouquet',
        'tart-snack': 'Tart Snack'
    };

    const newProduct = {
        id: Date.now(),
        name: name,
        category: category,
        categoryName: categoryNames[category],
        description: description,
        image: image || '',
        bestSeller: bestSeller
    };

    products.push(newProduct);
    saveProductsToStorage();
    
    // Reset form
    hideAddProductForm();
    
    // Reload products
    loadAdminProducts();
    loadProducts();
    
    alert('Produk berhasil ditambahkan!');
}

function loadAdminProducts() {
    const grid = document.getElementById('adminProductsGrid');
    
    grid.innerHTML = products.map(product => `
        <div class="admin-product-card">
            <div class="admin-product-image">
                ${product.image ? `<img src="${product.image}" alt="${product.name}" onerror="this.style.display='none'; this.parentElement.innerHTML='🌸';">` : '🌸'}
            </div>
            <div class="admin-product-info">
                <h6>${product.name}</h6>
                <p class="text-muted small">${product.categoryName}</p>
                <p class="small">${product.description}</p>
                ${product.bestSeller ? '<span class="badge bg-warning text-dark">Best Seller</span>' : ''}
                <div class="admin-actions">
                    <button class="btn btn-sm btn-outline-primary" onclick="editProduct(${product.id})">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="deleteProduct(${product.id})">
                        <i class="fas fa-trash"></i> Hapus
                    </button>
                </div>
            </div>
        </div>
    `).join('');
}

function editProduct(productId) {
    const product = products.find(p => p.id === productId);
    if (!product) return;

    const newName = prompt('Nama produk:', product.name);
    if (newName === null) return;

    const newDescription = prompt('Deskripsi produk:', product.description);
    if (newDescription === null) return;

    const newImage = prompt('URL gambar (kosongkan jika tidak ada perubahan):', product.image);
    if (newImage === null) return;

    const newBestSeller = confirm('Best Seller? ' + (product.bestSeller ? 'Saat ini: Ya' : 'Saat ini: Tidak'));

    // Update product
    product.name = newName || product.name;
    product.description = newDescription || product.description;
    if (newImage) product.image = newImage;
    product.bestSeller = newBestSeller;

    saveProductsToStorage();
    loadAdminProducts();
    loadProducts();
    
    alert('Produk berhasil diperbarui!');
}

function deleteProduct(productId) {
    if (!confirm('Apakah Anda yakin ingin menghapus produk ini?')) return;

    products = products.filter(p => p.id !== productId);
    saveProductsToStorage();
    loadAdminProducts();
    loadProducts();
    
    alert('Produk berhasil dihapus!');
}

// Utility functions
function formatCurrency(amount) {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR'
    }).format(amount);
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Smooth scrolling for anchor links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const target = document.querySelector(this.getAttribute('href'));
        if (target) {
            target.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// Add scroll animations
const observerOptions = {
    threshold: 0.1,
    rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver(function(entries) {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.classList.add('fade-in');
        }
    });
}, observerOptions);

// Observe all product cards
document.addEventListener('DOMContentLoaded', function() {
    const productCards = document.querySelectorAll('.product-card');
    productCards.forEach(card => {
        observer.observe(card);
    });
});