<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// === SECURITY: Require admin login (same path/cookie config as index.php) ===
if (session_status() === PHP_SESSION_NONE) {
    $cp = session_get_cookie_params();
    session_set_cookie_params([
        'lifetime' => $cp['lifetime'] ?? 0,
        'path'     => '/',
        'domain'   => $cp['domain'] ?? '',
        'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
    session_name('PHPSESSID');
    session_start();
}
if (empty($_SESSION['admin_logged_in']) || empty($_SESSION['user_id'])) {
    header('Location: index.php');
    exit();
}

define('DATA_DIR', __DIR__ . '/data');
$THEME_FILE = DATA_DIR . '/theme_settings.json';

// =============================================
// Public API endpoint: ?action=get_theme
// (so remote_app.php JS can fetch live settings)
// =============================================
if (isset($_GET['action']) && $_GET['action'] === 'get_theme') {
    header('Content-Type: application/json');
    header('Access-Control-Allow-Origin: *');
    if (file_exists($THEME_FILE)) {
        echo file_get_contents($THEME_FILE);
    } else {
        echo json_encode(['error' => 'theme not configured']);
    }
    exit();
}

// =============================================
// SAVE handler
// =============================================
$flashMsg = '';
$flashType = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_theme') {
    $existing = file_exists($THEME_FILE) ? (json_decode(file_get_contents($THEME_FILE), true) ?: []) : [];

    $bgUrl  = trim($_POST['bg_url'] ?? '');
    $bgType = trim($_POST['bg_type'] ?? 'image');
    if (!in_array($bgType, ['image', 'video'], true)) $bgType = 'image';
    if ($bgUrl === '') $bgUrl = $existing['bg_url'] ?? 'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?w=1920&q=80';

    $newCfg = [
        'bg_url' => $bgUrl,
        'bg_type' => $bgType,
        'blur' => max(0, min(25, (int)($_POST['blur'] ?? 5))),
        'brightness' => max(20, min(120, (int)($_POST['brightness'] ?? 30))),
        'rain' => max(0, min(100, (int)($_POST['rain'] ?? 70))),
        'color' => trim($_POST['color'] ?? 'none'),
        'overlay' => max(0, min(80, (int)($_POST['overlay'] ?? 0))),
        'volume' => max(0, min(100, (int)($_POST['volume'] ?? 50))),
        'show_widgets'        => isset($_POST['show_widgets']),
        'show_sound_btn'      => isset($_POST['show_sound_btn']),
        'show_fullscreen_btn' => isset($_POST['show_fullscreen_btn']),
        'show_share_btn'      => isset($_POST['show_share_btn']),
        'updated_at' => (new DateTime('now', new DateTimeZone('Asia/Jakarta')))->format('Y-m-d H:i:s')
    ];
    file_put_contents($THEME_FILE, json_encode($newCfg, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
    $_SESSION['flash_msg'] = '✅ Tema berhasil disimpan & langsung aktif untuk semua user.';
    $_SESSION['flash_msgType'] = 'success';
    header('Location: theme_admin.php');
    exit();
}

// Reset to defaults
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'reset_theme') {
    $defaults = [
        'bg_url' => 'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?w=1920&q=80',
        'bg_type' => 'image',
        'blur' => 5, 'brightness' => 30, 'rain' => 70,
        'color' => 'none', 'overlay' => 0, 'volume' => 50,
        'show_widgets' => false, 'show_sound_btn' => false,
        'show_fullscreen_btn' => false, 'show_share_btn' => false,
        'updated_at' => (new DateTime('now', new DateTimeZone('Asia/Jakarta')))->format('Y-m-d H:i:s')
    ];
    file_put_contents($THEME_FILE, json_encode($defaults, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
    $_SESSION['flash_msg'] = '🔄 Tema direset ke default.';
    $_SESSION['flash_msgType'] = 'info';
    header('Location: theme_admin.php');
    exit();
}

// Pop flash
if (isset($_SESSION['flash_msg'])) {
    $flashMsg = $_SESSION['flash_msg'];
    $flashType = $_SESSION['flash_msgType'] ?? 'info';
    unset($_SESSION['flash_msg'], $_SESSION['flash_msgType']);
}

// Load current
$cfg = file_exists($THEME_FILE) ? (json_decode(file_get_contents($THEME_FILE), true) ?: []) : [];
$cfg += [
    'bg_url' => 'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?w=1920&q=80',
    'bg_type' => 'image',
    'blur' => 5, 'brightness' => 30, 'rain' => 70,
    'color' => 'none', 'overlay' => 0, 'volume' => 50,
    'show_widgets' => false, 'show_sound_btn' => false,
    'show_fullscreen_btn' => false, 'show_share_btn' => false
];

$PRESETS = [
    ['label' => 'City',     'url' => 'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?w=1920&q=80'],
    ['label' => 'Forest',   'url' => 'https://images.unsplash.com/photo-1448375240586-882707db888b?w=1920&q=80'],
    ['label' => 'Mountain', 'url' => 'https://images.unsplash.com/photo-1464822759023-fed622ff2c3b?w=1920&q=80'],
    ['label' => 'Tokyo',    'url' => 'https://images.unsplash.com/photo-1542931287-023b922fa89b?w=1920&q=80'],
    ['label' => 'Autumn',   'url' => 'https://images.unsplash.com/photo-1507783548227-544c3b8fc065?w=1920&q=80'],
    ['label' => 'Sky',      'url' => 'https://images.unsplash.com/photo-1499346030926-9a72daac6c63?w=1920&q=80'],
    ['label' => 'Hurricane','url' => 'https://images.unsplash.com/photo-1561553873-e8491a564fd0?w=1920&q=80'],
    ['label' => 'River',    'url' => 'https://images.unsplash.com/photo-1437482078695-73f5ca6c96e2?w=1920&q=80'],
    ['label' => 'Beach',    'url' => 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1920&q=80'],
];

$COLORS = [
    ['none',    'None'],
    ['#3498db', 'Blue'],
    ['#9b59b6', 'Purple'],
    ['#e74c3c', 'Red'],
    ['#f39c12', 'Orange'],
    ['#2ecc71', 'Green'],
    ['#1abc9c', 'Turquoise'],
    ['#e91e63', 'Pink'],
];
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>🎨 Pengaturan Tema · Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
*,*::before,*::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif;
    background: linear-gradient(135deg, #020c18 0%, #061e38 100%);
    color: #e8f4ff;
    min-height: 100vh;
    padding: 24px 16px 60px;
}
.wrap { max-width: 1100px; margin: 0 auto; }
.hdr {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 24px; padding-bottom: 16px;
    border-bottom: 1px solid rgba(0,150,255,.18);
    flex-wrap: wrap; gap: 12px;
}
.hdr h1 {
    font-size: 22px; font-weight: 800;
    background: linear-gradient(135deg, #e0f0ff, #4db8ff);
    -webkit-background-clip: text; -webkit-text-fill-color: transparent;
    background-clip: text;
}
.hdr p { font-size: 12px; color: #7aaed4; margin-top: 4px; }
.back-btn {
    background: rgba(0, 150, 255, .12);
    border: 1px solid rgba(0,150,255,.3);
    color: #4db8ff; padding: 8px 14px;
    border-radius: 8px; text-decoration: none;
    font-size: 12px; font-weight: 600;
    transition: all 0.2s;
}
.back-btn:hover { background: rgba(0, 150, 255, .25); transform: translateY(-1px); }
.preview-btn {
    background: linear-gradient(135deg, #00aa55, #00cc66);
    border: none; color: #fff;
    padding: 8px 14px; border-radius: 8px;
    text-decoration: none; font-size: 12px; font-weight: 700;
    margin-left: 8px;
}
.alert {
    padding: 12px 16px; border-radius: 10px; margin-bottom: 20px;
    font-size: 13px; display: flex; align-items: center; gap: 10px;
}
.alert.success { background: rgba(0,230,118,.15); border: 1px solid rgba(0,230,118,.3); color: #00e676; }
.alert.info    { background: rgba(0,150,255,.15); border: 1px solid rgba(0,150,255,.3); color: #4db8ff; }
.alert.error   { background: rgba(255,77,77,.15); border: 1px solid rgba(255,77,77,.3); color: #ff8080; }

.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }

.card {
    background: rgba(4, 22, 48, .85);
    border: 1px solid rgba(0,150,255,.18);
    border-radius: 14px;
    padding: 20px 22px;
    backdrop-filter: blur(20px);
}
.card h3 {
    font-size: 11px; font-weight: 700;
    text-transform: uppercase; letter-spacing: 1.5px;
    color: #4db8ff;
    margin-bottom: 14px;
    border-bottom: 1px solid rgba(0,150,255,.12);
    padding-bottom: 10px;
}
.field { margin-bottom: 14px; }
.field label {
    display: flex; justify-content: space-between; align-items: center;
    font-size: 12px; color: #cfeaff; margin-bottom: 6px;
}
.field label .val { color: #4db8ff; font-weight: 600; font-size: 11px; }
.field input[type="text"], .field input[type="url"], .field select {
    width: 100%;
    background: rgba(0, 30, 70, .5);
    border: 1px solid rgba(0,150,255,.2);
    color: #fff; padding: 10px 12px; border-radius: 8px;
    font-size: 12px; outline: none; font-family: inherit;
}
.field input:focus, .field select:focus { border-color: #4db8ff; box-shadow: 0 0 0 2px rgba(77,184,255,.15); }
.field input[type="range"] {
    width: 100%; height: 5px; border-radius: 3px;
    background: rgba(0,150,255,.15); -webkit-appearance: none;
    outline: none; cursor: pointer;
}
.field input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none; width: 18px; height: 18px;
    background: #4db8ff; border-radius: 50%; cursor: pointer;
    box-shadow: 0 2px 6px rgba(0,0,0,.3);
}

.preset-grid {
    display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px;
    margin-bottom: 14px;
}
.preset-item {
    aspect-ratio: 16/10;
    background-size: cover; background-position: center;
    border-radius: 8px; cursor: pointer;
    border: 2px solid transparent;
    opacity: 0.55; transition: all 0.2s;
    position: relative; overflow: hidden;
    background-color: #0a1a30;
}
.preset-item:hover { opacity: 0.85; transform: scale(1.02); }
.preset-item.active { border-color: #4db8ff; opacity: 1; box-shadow: 0 0 0 2px rgba(0,150,255,.25); }
.preset-item::after {
    content: attr(data-label);
    position: absolute; bottom: 0; left: 0; right: 0;
    padding: 3px;
    background: linear-gradient(transparent, rgba(0,0,0,.85));
    color: #fff; font-size: 9px; text-align: center;
}

.color-row { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 8px; }
.color-btn {
    width: 28px; height: 28px; border-radius: 50%;
    border: 2px solid transparent; cursor: pointer;
    transition: transform 0.2s; padding: 0;
}
.color-btn:hover, .color-btn.active { transform: scale(1.15); border-color: #fff; }
.color-btn.none { background: linear-gradient(135deg, #333 45%, #fff 45%, #fff 55%, #333 55%); }

.toggle-row {
    display: flex; align-items: center; justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px dashed rgba(255,255,255,.05);
}
.toggle-row:last-child { border-bottom: none; }
.toggle-row label { font-size: 12px; color: #cfeaff; cursor: pointer; }
.toggle-row input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; accent-color: #4db8ff; }

.actions {
    display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;
    flex-wrap: wrap;
}
.btn {
    padding: 10px 20px; border-radius: 8px; cursor: pointer;
    font-size: 12px; font-weight: 700; font-family: inherit;
    border: none; transition: all 0.2s;
}
.btn-save { background: linear-gradient(135deg,#0066ff,#0099ff); color: #fff; box-shadow: 0 4px 14px rgba(0,100,255,.4); }
.btn-save:hover { transform: translateY(-1px); box-shadow: 0 6px 20px rgba(0,120,255,.55); }
.btn-reset { background: rgba(255,100,100,.15); color: #ff8080; border: 1px solid rgba(255,100,100,.3); }
.btn-reset:hover { background: rgba(255,100,100,.25); }

#preview-box {
    margin-top: 18px;
    aspect-ratio: 16/9;
    border-radius: 12px;
    background-size: cover; background-position: center;
    position: relative; overflow: hidden;
    border: 1px solid rgba(0,150,255,.2);
    transition: filter 0.3s ease;
}
#preview-overlay {
    position: absolute; inset: 0;
    mix-blend-mode: overlay;
    transition: opacity 0.3s ease, background-color 0.3s ease;
}
#preview-info {
    position: absolute; bottom: 8px; left: 10px; right: 10px;
    background: rgba(0,0,0,.6); backdrop-filter: blur(6px);
    color: #fff; padding: 6px 10px; border-radius: 6px;
    font-size: 10px; line-height: 1.4;
}
.timestamp { font-size: 10px; color: #7aaed4; opacity: 0.7; }
</style>
</head>
<body>
<div class="wrap">
    <div class="hdr">
        <div>
            <h1>🎨 Pengaturan Tema (Rainy Window FX)</h1>
            <p>
                Atur background, hujan, suara, dan tampilan widget untuk semua user di <code style="background:rgba(0,0,0,.3); padding:1px 6px; border-radius:3px;">remote_app.php</code>.
                <?php if (!empty($cfg['updated_at'])): ?>
                    <span class="timestamp">· terakhir update: <?php echo htmlspecialchars($cfg['updated_at']); ?> WIB</span>
                <?php endif; ?>
            </p>
        </div>
        <div>
            <a href="index.php?tab=members" class="back-btn">← Kembali ke Dashboard</a>
            <a href="remote_app.php" target="_blank" class="preview-btn">🚀 Preview Live</a>
        </div>
    </div>

    <?php if ($flashMsg): ?>
        <div class="alert <?php echo htmlspecialchars($flashType); ?>"><?php echo $flashMsg; ?></div>
    <?php endif; ?>

    <form method="POST" id="theme-form">
        <input type="hidden" name="action" value="save_theme">
        <input type="hidden" name="bg_url"  id="bg_url"  value="<?php echo htmlspecialchars($cfg['bg_url']); ?>">
        <input type="hidden" name="bg_type" id="bg_type" value="<?php echo htmlspecialchars($cfg['bg_type']); ?>">
        <input type="hidden" name="color"   id="color_in" value="<?php echo htmlspecialchars($cfg['color']); ?>">

        <div class="grid">
            <!-- LEFT: Background + Visual Effects -->
            <div>
                <div class="card">
                    <h3>🖼️ Background</h3>
                    <div class="preset-grid" id="preset-grid">
                        <?php foreach ($PRESETS as $p): ?>
                            <div class="preset-item <?php echo $p['url'] === $cfg['bg_url'] ? 'active' : ''; ?>"
                                 data-url="<?php echo htmlspecialchars($p['url']); ?>"
                                 data-label="<?php echo htmlspecialchars($p['label']); ?>"
                                 style="background-image:url('<?php echo htmlspecialchars(preg_replace('/&q=80$/','&q=15&w=200',$p['url'])); ?>');"></div>
                        <?php endforeach; ?>
                    </div>
                    <div class="field">
                        <label>URL Custom (Image / Video)</label>
                        <input type="url" id="custom_url_input" placeholder="https://example.com/image.jpg atau .mp4"
                               value="<?php echo htmlspecialchars(in_array($cfg['bg_url'], array_column($PRESETS, 'url'), true) ? '' : $cfg['bg_url']); ?>">
                        <button type="button" id="apply_custom_url" style="margin-top:6px; padding:6px 14px; background:rgba(0,150,255,.2); border:1px solid rgba(0,150,255,.35); color:#4db8ff; border-radius:6px; cursor:pointer; font-size:11px; font-family:inherit;">↗ Terapkan URL</button>
                    </div>
                    <div id="preview-box">
                        <div id="preview-overlay"></div>
                        <div id="preview-info">📷 Live preview · simpan untuk apply ke semua user</div>
                    </div>
                </div>

                <div class="card" style="margin-top:18px;">
                    <h3>🎛️ Visual Effects</h3>
                    <div class="field">
                        <label>Blur <span class="val"><span id="blur_v"><?php echo (int)$cfg['blur']; ?></span>px</span></label>
                        <input type="range" name="blur" id="blur_r" min="0" max="25" value="<?php echo (int)$cfg['blur']; ?>">
                    </div>
                    <div class="field">
                        <label>Brightness <span class="val"><span id="brightness_v"><?php echo (int)$cfg['brightness']; ?></span>%</span></label>
                        <input type="range" name="brightness" id="brightness_r" min="20" max="120" value="<?php echo (int)$cfg['brightness']; ?>">
                    </div>
                    <div class="field">
                        <label>Rain Intensity <span class="val"><span id="rain_v"><?php echo (int)$cfg['rain']; ?></span>%</span></label>
                        <input type="range" name="rain" id="rain_r" min="0" max="100" value="<?php echo (int)$cfg['rain']; ?>">
                    </div>
                </div>
            </div>

            <!-- RIGHT: Hue + Sound + Toggles -->
            <div>
                <div class="card">
                    <h3>🎨 Hue Tint</h3>
                    <div class="color-row" id="color-row">
                        <?php foreach ($COLORS as $c): ?>
                            <button type="button"
                                    class="color-btn <?php echo $c[0] === 'none' ? 'none' : ''; ?> <?php echo $c[0] === $cfg['color'] ? 'active' : ''; ?>"
                                    data-color="<?php echo htmlspecialchars($c[0]); ?>"
                                    title="<?php echo htmlspecialchars($c[1]); ?>"
                                    <?php if ($c[0] !== 'none'): ?>style="background:<?php echo htmlspecialchars($c[0]); ?>;"<?php endif; ?>></button>
                        <?php endforeach; ?>
                    </div>
                    <div class="field">
                        <label>Color Intensity <span class="val"><span id="overlay_v"><?php echo (int)$cfg['overlay']; ?></span>%</span></label>
                        <input type="range" name="overlay" id="overlay_r" min="0" max="80" value="<?php echo (int)$cfg['overlay']; ?>">
                    </div>
                </div>

                <div class="card" style="margin-top:18px;">
                    <h3>🔊 Ambient Sound</h3>
                    <div class="field">
                        <label>Volume Default <span class="val"><span id="volume_v"><?php echo (int)$cfg['volume']; ?></span>%</span></label>
                        <input type="range" name="volume" id="volume_r" min="0" max="100" value="<?php echo (int)$cfg['volume']; ?>">
                        <p style="font-size:10px; color:#7aaed4; margin-top:6px;">User tetap bisa toggle sound on/off via tombol 🔇 di kanan-atas (jika diaktifkan).</p>
                    </div>
                </div>

                <div class="card" style="margin-top:18px;">
                    <h3>👁 Tampilan Widget User</h3>
                    <p style="font-size:11px; color:#7aaed4; margin-bottom:10px;">Pilih elemen apa yang ditampilkan untuk user di halaman <code style="background:rgba(0,0,0,.3); padding:1px 5px; border-radius:3px;">remote_app.php</code>.</p>
                    <div class="toggle-row">
                        <label for="t_widgets">📊 Glassmorph Clock + Weather</label>
                        <input type="checkbox" name="show_widgets" id="t_widgets" <?php echo !empty($cfg['show_widgets']) ? 'checked' : ''; ?>>
                    </div>
                    <div class="toggle-row">
                        <label for="t_sound">🔇 Tombol Toggle Sound</label>
                        <input type="checkbox" name="show_sound_btn" id="t_sound" <?php echo !empty($cfg['show_sound_btn']) ? 'checked' : ''; ?>>
                    </div>
                    <div class="toggle-row">
                        <label for="t_fs">⛶ Tombol Fullscreen</label>
                        <input type="checkbox" name="show_fullscreen_btn" id="t_fs" <?php echo !empty($cfg['show_fullscreen_btn']) ? 'checked' : ''; ?>>
                    </div>
                    <div class="toggle-row">
                        <label for="t_share">🔗 Tombol Share Link</label>
                        <input type="checkbox" name="show_share_btn" id="t_share" <?php echo !empty($cfg['show_share_btn']) ? 'checked' : ''; ?>>
                    </div>
                </div>
            </div>
        </div>

        <div class="actions">
            <button type="submit" formaction="theme_admin.php" form="reset-form" class="btn btn-reset" onclick="return confirm('Reset semua pengaturan tema ke default?');">
                🔄 Reset ke Default
            </button>
            <button type="submit" class="btn btn-save">💾 Simpan & Apply ke Semua User</button>
        </div>
    </form>

    <form id="reset-form" method="POST" style="display:none;">
        <input type="hidden" name="action" value="reset_theme">
    </form>
</div>

<script>
(function() {
    const previewBox     = document.getElementById('preview-box');
    const previewOverlay = document.getElementById('preview-overlay');

    function $(id) { return document.getElementById(id); }
    const state = {
        bg_url:  $('bg_url').value,
        bg_type: $('bg_type').value,
        blur:    +$('blur_r').value,
        brightness: +$('brightness_r').value,
        rain:    +$('rain_r').value,
        color:   $('color_in').value,
        overlay: +$('overlay_r').value,
        volume:  +$('volume_r').value
    };

    function applyPreview() {
        previewBox.style.backgroundImage = `url('${state.bg_url}')`;
        const blur = Math.max(0, state.blur);
        const bright = Math.max(20, state.brightness) / 100;
        previewBox.style.filter = `blur(${blur}px) brightness(${bright})`;
        if (state.color === 'none' || !state.overlay) {
            previewOverlay.style.opacity = '0';
        } else {
            previewOverlay.style.backgroundColor = state.color;
            previewOverlay.style.opacity = (state.overlay / 100).toFixed(2);
        }
    }

    // Sliders
    [['blur','blur_r','blur_v','px'],
     ['brightness','brightness_r','brightness_v','%'],
     ['rain','rain_r','rain_v','%'],
     ['overlay','overlay_r','overlay_v','%'],
     ['volume','volume_r','volume_v','%']].forEach(([key,inp,lbl,unit]) => {
        $(inp).addEventListener('input', e => {
            state[key] = +e.target.value;
            $(lbl).textContent = e.target.value;
            applyPreview();
        });
    });

    // Presets
    document.querySelectorAll('.preset-item').forEach(el => {
        el.addEventListener('click', () => {
            document.querySelectorAll('.preset-item').forEach(p => p.classList.remove('active'));
            el.classList.add('active');
            state.bg_url = el.getAttribute('data-url');
            state.bg_type = 'image';
            $('bg_url').value = state.bg_url;
            $('bg_type').value = 'image';
            $('custom_url_input').value = '';
            applyPreview();
        });
    });

    // Custom URL apply
    $('apply_custom_url').addEventListener('click', () => {
        const url = $('custom_url_input').value.trim();
        if (!url) return;
        const isVideo = /\.(mp4|webm|ogg|mov)(\?|$)/i.test(url);
        state.bg_url = url;
        state.bg_type = isVideo ? 'video' : 'image';
        $('bg_url').value = url;
        $('bg_type').value = state.bg_type;
        document.querySelectorAll('.preset-item').forEach(p => p.classList.remove('active'));
        applyPreview();
    });

    // Color buttons
    document.querySelectorAll('.color-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.color-btn').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.color = btn.getAttribute('data-color');
            $('color_in').value = state.color;
            applyPreview();
        });
    });

    applyPreview();
})();
</script>
</body>
</html>
