<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Quiz Items - Chan Hall Training</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #2d1f1a 0%, #4a3728 50%, #2d1f1a 100%);
            min-height: 100vh;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
        }

        .card {
            background: linear-gradient(180deg, #faf8f5 0%, #f5f0e8 100%);
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 15px 50px rgba(0, 0, 0, 0.4);
            border: 1px solid rgba(212, 175, 55, 0.3);
        }

        header {
            text-align: center;
            margin-bottom: 25px;
        }

        h1 {
            color: #5c4033;
            font-size: 1.6rem;
            margin-bottom: 5px;
        }

        .subtitle {
            color: #8b7355;
            font-size: 0.95rem;
        }

        .btn-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }

        .btn {
            background: linear-gradient(135deg, #d4af37 0%, #f4d03f 100%);
            color: #3d2914;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(212, 175, 55, 0.3);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #5c4033 0%, #8b7355 100%);
            color: #fff;
        }

        .btn-danger {
            background: linear-gradient(135deg, #c0392b 0%, #e74c3c 100%);
            color: #fff;
        }

        .btn-small {
            padding: 8px 16px;
            font-size: 0.85rem;
        }

        /* Item List */
        .item-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .item-card {
            background: #fff;
            border: 2px solid #e0d5c5;
            border-radius: 12px;
            padding: 20px;
            transition: border-color 0.2s;
        }

        .item-card:hover {
            border-color: #d4af37;
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }

        .item-number {
            background: #d4af37;
            color: #3d2914;
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.9rem;
        }

        .item-actions {
            display: flex;
            gap: 8px;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 15px;
        }

        @media (max-width: 600px) {
            .form-row {
                grid-template-columns: 1fr;
            }
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        label {
            font-size: 0.85rem;
            color: #5c4033;
            margin-bottom: 5px;
            font-weight: 500;
        }

        input, textarea {
            border: 1px solid #d5cbbf;
            border-radius: 6px;
            padding: 10px 12px;
            font-size: 0.95rem;
            transition: border-color 0.2s;
            font-family: inherit;
        }

        input:focus, textarea:focus {
            outline: none;
            border-color: #d4af37;
        }

        textarea {
            resize: vertical;
            min-height: 60px;
        }

        .emoji-input {
            font-size: 1.5rem;
            text-align: center;
            width: 60px;
        }

        /* Image Upload */
        .image-section {
            display: flex;
            gap: 15px;
            align-items: flex-start;
        }

        .image-preview {
            width: 80px;
            height: 80px;
            background: #f5f0e8;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            overflow: hidden;
            flex-shrink: 0;
        }

        .image-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .image-controls {
            flex: 1;
        }

        /* Messages */
        .message {
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: none;
        }

        .message.show {
            display: block;
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* Back link */
        .back-link {
            display: inline-block;
            color: #8b7355;
            text-decoration: none;
            margin-bottom: 20px;
            font-size: 0.95rem;
        }

        .back-link:hover {
            color: #d4af37;
        }

        /* Empty state */
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #8b7355;
        }

        .empty-state p {
            margin-bottom: 20px;
        }

        /* Help text */
        .help-text {
            font-size: 0.8rem;
            color: #8b7355;
            margin-top: 4px;
        }

        footer {
            text-align: center;
            color: rgba(255,255,255,0.6);
            padding: 20px;
            font-size: 0.85rem;
        }

        footer a {
            color: #d4af37;
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="index.html" class="back-link">← Back to Quiz</a>

        <div class="card">
            <header>
                <h1>Edit Quiz Items</h1>
                <p class="subtitle">Customize the Chan Hall Training Quiz</p>
            </header>

            <div class="message" id="message"></div>

            <div class="btn-row">
                <button class="btn" onclick="addNewItem()">+ Add New Item</button>
                <button class="btn btn-secondary" onclick="saveAll()">Save Changes</button>
                <button class="btn btn-danger" onclick="resetToDefaults()">Reset to Defaults</button>
            </div>

            <div class="item-list" id="itemList">
                <!-- Items populated by JavaScript -->
            </div>
        </div>
    </div>

    <footer>
        <p><a href="index.html">Take the Quiz</a> | <a href="/">Home</a></p>
    </footer>

    <script>
        // Default items (same as in main quiz)
        const defaultItems = [
            {
                id: 1,
                name: "Singing Bowl",
                chinese: "引磬",
                pinyin: "yǐn qìng",
                description: "A metal bowl struck with a mallet to mark transitions in ceremony and meditation.",
                emoji: "🔔",
                image: "images/singing-bowl.jpg"
            },
            {
                id: 2,
                name: "Wooden Fish",
                chinese: "木魚",
                pinyin: "mù yú",
                description: "Hollow wooden percussion instrument shaped like a fish, used to keep rhythm during chanting.",
                emoji: "🐟",
                image: "images/wooden-fish.jpg"
            },
            {
                id: 3,
                name: "Incense Burner",
                chinese: "香爐",
                pinyin: "xiāng lú",
                description: "Vessel for burning incense offerings, often placed on the altar.",
                emoji: "🏺",
                image: "images/incense-burner.jpg"
            },
            {
                id: 4,
                name: "Incense Sticks",
                chinese: "香",
                pinyin: "xiāng",
                description: "Fragrant sticks burned as offerings, symbolizing the spreading of dharma.",
                emoji: "🧘",
                image: "images/incense-sticks.jpg"
            },
            {
                id: 5,
                name: "Meditation Cushion",
                chinese: "蒲團",
                pinyin: "pú tuán",
                description: "Round cushion for sitting meditation, elevates hips for proper posture.",
                emoji: "⭕",
                image: "images/meditation-cushion.jpg"
            },
            {
                id: 6,
                name: "Prayer Beads",
                chinese: "念珠",
                pinyin: "niàn zhū",
                description: "String of 108 beads used for counting mantras and prostrations.",
                emoji: "📿",
                image: "images/prayer-beads.jpg"
            },
            {
                id: 7,
                name: "Bell",
                chinese: "鈴",
                pinyin: "líng",
                description: "Handheld bell rung to signal the start and end of meditation periods.",
                emoji: "🔔",
                image: "images/bell.jpg"
            },
            {
                id: 8,
                name: "Dharma Drum",
                chinese: "法鼓",
                pinyin: "fǎ gǔ",
                description: "Large drum used during ceremonies to accompany chanting.",
                emoji: "🥁",
                image: "images/dharma-drum.jpg"
            },
            {
                id: 9,
                name: "Prostration Mat",
                chinese: "拜墊",
                pinyin: "bài diàn",
                description: "Padded mat for performing prostrations (bowing) during ceremonies.",
                emoji: "🧎",
                image: "images/prostration-mat.jpg"
            },
            {
                id: 10,
                name: "Altar Cloth",
                chinese: "桌圍",
                pinyin: "zhuō wéi",
                description: "Decorative cloth covering the altar table, often in traditional colors.",
                emoji: "🎨",
                image: "images/altar-cloth.jpg"
            },
            {
                id: 11,
                name: "Candle Holders",
                chinese: "燭台",
                pinyin: "zhú tái",
                description: "Stands for holding candles on the altar, representing wisdom.",
                emoji: "🕯️",
                image: "images/candle-holders.jpg"
            },
            {
                id: 12,
                name: "Flower Vase",
                chinese: "花瓶",
                pinyin: "huā píng",
                description: "Vessel for fresh flower offerings, symbolizing impermanence.",
                emoji: "💐",
                image: "images/flower-vase.jpg"
            },
            {
                id: 13,
                name: "Sutra Book",
                chinese: "經書",
                pinyin: "jīng shū",
                description: "Buddhist scripture text used for group chanting during services.",
                emoji: "📖",
                image: "images/sutra-book.jpg"
            },
            {
                id: 14,
                name: "Offering Tray",
                chinese: "供盤",
                pinyin: "gōng pán",
                description: "Tray for presenting fruit, tea, or other offerings to the Buddha.",
                emoji: "🍎",
                image: "images/offering-tray.jpg"
            },
            {
                id: 15,
                name: "Keisu",
                chinese: "磬",
                pinyin: "qìng",
                description: "Bowl-shaped gong struck to signal sections of the service.",
                emoji: "🔊",
                image: "images/keisu.jpg"
            }
        ];

        // Load items
        let items = JSON.parse(localStorage.getItem('chanHallItems')) || [...defaultItems];
        let nextId = Math.max(...items.map(i => i.id), 0) + 1;

        function renderItems() {
            const list = document.getElementById('itemList');

            if (items.length === 0) {
                list.innerHTML = `
                    <div class="empty-state">
                        <p>No items yet. Add some items to create your quiz!</p>
                        <button class="btn" onclick="addNewItem()">+ Add First Item</button>
                    </div>
                `;
                return;
            }

            list.innerHTML = items.map((item, index) => `
                <div class="item-card" data-id="${item.id}">
                    <div class="item-header">
                        <span class="item-number">${index + 1}</span>
                        <div class="item-actions">
                            <button class="btn btn-small btn-secondary" onclick="moveItem(${index}, -1)" ${index === 0 ? 'disabled' : ''}>↑</button>
                            <button class="btn btn-small btn-secondary" onclick="moveItem(${index}, 1)" ${index === items.length - 1 ? 'disabled' : ''}>↓</button>
                            <button class="btn btn-small btn-danger" onclick="deleteItem(${item.id})">Delete</button>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Name (English) *</label>
                            <input type="text" value="${escapeHtml(item.name)}" onchange="updateItem(${item.id}, 'name', this.value)" placeholder="e.g., Singing Bowl">
                        </div>
                        <div class="form-group">
                            <label>Chinese Name</label>
                            <input type="text" value="${escapeHtml(item.chinese || '')}" onchange="updateItem(${item.id}, 'chinese', this.value)" placeholder="e.g., 引磬">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>Pinyin</label>
                            <input type="text" value="${escapeHtml(item.pinyin || '')}" onchange="updateItem(${item.id}, 'pinyin', this.value)" placeholder="e.g., yǐn qìng">
                        </div>
                        <div class="form-group">
                            <label>Emoji (for placeholder)</label>
                            <input type="text" class="emoji-input" value="${item.emoji || ''}" onchange="updateItem(${item.id}, 'emoji', this.value)" placeholder="🔔">
                        </div>
                    </div>

                    <div class="form-group full-width">
                        <label>Description *</label>
                        <textarea onchange="updateItem(${item.id}, 'description', this.value)" placeholder="Describe what this item is and how it's used...">${escapeHtml(item.description)}</textarea>
                    </div>

                    <div class="image-section">
                        <div class="image-preview" id="preview-${item.id}">
                            ${item.image ? `<img src="${escapeHtml(item.image)}" alt="${escapeHtml(item.name)}">` : (item.emoji || '📷')}
                        </div>
                        <div class="image-controls">
                            <div class="form-group">
                                <label>Image URL</label>
                                <input type="text" value="${escapeHtml(item.image || '')}" onchange="updateItemImage(${item.id}, this.value)" placeholder="https://example.com/image.jpg">
                                <p class="help-text">Enter a URL to an image, or leave blank to use the emoji placeholder</p>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function updateItem(id, field, value) {
            const item = items.find(i => i.id === id);
            if (item) {
                item[field] = value;
            }
        }

        function updateItemImage(id, url) {
            const item = items.find(i => i.id === id);
            if (item) {
                item.image = url;
                const preview = document.getElementById(`preview-${id}`);
                if (url) {
                    preview.innerHTML = `<img src="${escapeHtml(url)}" alt="${escapeHtml(item.name)}">`;
                } else {
                    preview.innerHTML = item.emoji || '📷';
                }
            }
        }

        function addNewItem() {
            const newItem = {
                id: nextId++,
                name: "",
                chinese: "",
                pinyin: "",
                description: "",
                emoji: "❓",
                image: ""
            };
            items.push(newItem);
            renderItems();

            // Scroll to new item
            setTimeout(() => {
                const newCard = document.querySelector(`[data-id="${newItem.id}"]`);
                if (newCard) {
                    newCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    newCard.querySelector('input').focus();
                }
            }, 100);
        }

        function deleteItem(id) {
            if (confirm('Delete this item?')) {
                items = items.filter(i => i.id !== id);
                renderItems();
                showMessage('Item deleted', 'success');
            }
        }

        function moveItem(index, direction) {
            const newIndex = index + direction;
            if (newIndex < 0 || newIndex >= items.length) return;

            [items[index], items[newIndex]] = [items[newIndex], items[index]];
            renderItems();
        }

        function saveAll() {
            // Validate required fields
            const invalid = items.filter(i => !i.name.trim() || !i.description.trim());
            if (invalid.length > 0) {
                showMessage('Please fill in Name and Description for all items', 'error');
                return;
            }

            localStorage.setItem('chanHallItems', JSON.stringify(items));
            showMessage('Changes saved! Your quiz has been updated.', 'success');
        }

        function resetToDefaults() {
            if (confirm('Reset to default items? This will remove any custom items you\'ve added.')) {
                items = [...defaultItems];
                nextId = Math.max(...items.map(i => i.id), 0) + 1;
                localStorage.setItem('chanHallItems', JSON.stringify(items));
                renderItems();
                showMessage('Reset to default items', 'success');
            }
        }

        function showMessage(text, type) {
            const msg = document.getElementById('message');
            msg.textContent = text;
            msg.className = `message show ${type}`;
            setTimeout(() => {
                msg.classList.remove('show');
            }, 3000);
        }

        // Initial render
        renderItems();
    </script>
</body>
</html>
