<?php
// Verhindert hartnäckiges Browser-Caching
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

session_set_cookie_params(60 * 60 * 24 * 365 * 10);
session_start();

// ==========================================
// 🔒 DEINE KONFIGURATION (HIER ÄNDERN!)
// ==========================================
$PASSWORD = 'U7NFvWp6Q9R0B2K5jsJA56LvOGR'; 
$dataFile = 'data.json';
// ==========================================

$loginError = false;
if (isset($_POST['password'])) {
    if ($_POST['password'] === $PASSWORD) {
        $_SESSION['logged_in'] = true;
        header("Location: index.php"); 
        exit;
    } else {
        $loginError = true;
    }
}

// Sichere API mit Validierung
if (isset($_GET['api'])) {
    if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
        http_response_code(401);
        echo json_encode(['error' => 'Nicht autorisiert.']);
        exit;
    }

    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = file_get_contents('php://input');
        
        // Nur prüfen, ob es valides JSON ist
        json_decode($input);
        
        if (json_last_error() === JSON_ERROR_NONE) {
            file_put_contents($dataFile, $input);
            echo json_encode(['status' => 'success']);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'Datenstruktur fehlerhaft']);
        }
    } else {
        if (!file_exists($dataFile)) {
            $initialData = '{"📥 Sammelliste":[],"Mein Supermarkt":[],"_memory":{},"_archive":[],"_settings":{"darkMode":false,"hideCompleted":false}}';
            file_put_contents($dataFile, $initialData);
        }
        echo file_get_contents($dataFile);
    }
    exit;
}

$svgLogo = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cdefs%3E%3ClinearGradient id='g' x1='0%25' y1='0%25' x2='100%25' y2='100%25'%3E%3Cstop offset='0%25' stop-color='%2300c6ff' /%3E%3Cstop offset='100%25' stop-color='%230072ff' /%3E%3C/linearGradient%3E%3C/defs%3E%3Crect width='100' height='100' rx='25' fill='url(%23g)' /%3E%3Cpath d='M25 30 h10 l10 30 h30 l8 -20 h-40' fill='none' stroke='%23fff' stroke-width='7' stroke-linecap='round' stroke-linejoin='round'/%3E%3Ccircle cx='45' cy='75' r='6' fill='%23fff' /%3E%3Ccircle cx='65' cy='75' r='6' fill='%23fff' /%3E%3Cpath d='M45 45 l10 10 l20 -20' fill='none' stroke='%23fff' stroke-width='7' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E";

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    ?>
    <!DOCTYPE html>
    <html lang="de">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Login - Einkaufsliste</title>
        <link rel="icon" type="image/svg+xml" href="<?php echo $svgLogo; ?>">
        <link rel="apple-touch-icon" href="<?php echo $svgLogo; ?>">
        <style>
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background-color: #f4f4f9; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
            .login-box { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); width: 100%; max-width: 350px; text-align: center; }
            .logo-preview { width: 80px; height: 80px; margin-bottom: 15px; border-radius: 20px; box-shadow: 0 4px 10px rgba(0,114,255,0.3); }
            h1 { margin-top: 0; color: #2c3e50; font-size: 24px; }
            input { width: 100%; padding: 12px; margin: 15px 0; border: 1px solid #ccc; border-radius: 5px; box-sizing: border-box; font-size: 16px; }
            button { width: 100%; padding: 12px; background-color: #3498db; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; font-weight: bold; }
            button:hover { background-color: #2980b9; }
            .error { color: #e74c3c; background: #fadbd8; padding: 10px; border-radius: 5px; margin-bottom: 15px; font-size: 14px; }
        </style>
    </head>
    <body>
        <div class="login-box">
            <img src="<?php echo $svgLogo; ?>" alt="Logo" class="logo-preview">
            <h1>Einkaufsliste Pro</h1>
            <?php if ($loginError): ?>
                <div class="error">Das Passwort ist leider falsch.</div>
            <?php endif; ?>
            <form method="POST">
                <input type="password" name="password" placeholder="Passwort eingeben" required autofocus>
                <button type="submit">Anmelden</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit; 
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Meine Einkaufslisten Pro</title>
    <link rel="icon" type="image/svg+xml" href="<?php echo $svgLogo; ?>">
    <link rel="apple-touch-icon" href="<?php echo $svgLogo; ?>">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --bg-color: #f4f4f9; --text-color: #333; --card-bg: #ffffff;
            --border-color: #eee; --primary: #3498db; --primary-hover: #2980b9;
            --success: #2ecc71; --success-hover: #27ae60; --danger: #e74c3c;
            --warning: #f1c40f; --move: #f39c12; --cat-header: #ecf0f1;
            --total-bg: #2c3e50; --total-text: #ffffff; --input-border: #ccc;
        }
        [data-theme="dark"] {
            --bg-color: #121212; --text-color: #e0e0e0; --card-bg: #1e1e1e;
            --border-color: #333; --primary: #2980b9; --primary-hover: #3498db;
            --success: #27ae60; --success-hover: #2ecc71; --danger: #c0392b;
            --warning: #f39c12; --move: #d35400; --cat-header: #2c3e50;
            --total-bg: #000000; --total-text: #2ecc71; --input-border: #444;
        }

        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif; background-color: var(--bg-color); color: var(--text-color); margin: 0; padding: 10px; transition: background-color 0.3s, color 0.3s;}
        .container { max-width: 700px; margin: 0 auto; background: var(--card-bg); padding: 15px; border-radius: 10px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); transition: background-color 0.3s;}
        
        .header-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; position: relative;}
        h1 { margin: 0; font-size: 20px; color: var(--text-color); display: flex; align-items: center; gap: 10px;}
        .header-logo { height: 32px; width: 32px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,114,255,0.3);}
        
        .hamburger-btn { background: none; border: none; font-size: 28px; color: var(--text-color); cursor: pointer; padding: 0 5px; width: auto; transition: color 0.2s;}
        .hamburger-btn:hover { color: var(--primary); background: none;}
        
        .dropdown-menu { display: none; position: absolute; right: 0; top: 100%; background: var(--card-bg); box-shadow: 0 8px 20px rgba(0,0,0,0.15); border-radius: 8px; border: 1px solid var(--border-color); z-index: 1000; min-width: 180px; overflow: hidden; margin-top: 5px;}
        .dropdown-menu.show { display: block; }
        
        .menu-btn { display: block; width: 100%; text-align: left; padding: 12px 15px; background: none; border: none; border-bottom: 1px solid var(--border-color); color: var(--text-color); font-size: 16px; border-radius: 0; cursor: pointer;}
        .menu-btn:last-child { border-bottom: none; }
        .menu-btn:hover { background-color: var(--bg-color); color: var(--primary);}
        
        .row { display: flex; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; }
        .row > * { flex: 1; min-width: 120px; }
        
        input, select, button { padding: 8px; border: 1px solid var(--input-border); border-radius: 5px; box-sizing: border-box; font-size: 15px; width: 100%; background: var(--card-bg); color: var(--text-color);}
        button { background-color: var(--primary); color: white; border: none; cursor: pointer; font-weight: bold; transition: background-color 0.2s; }
        button:hover { background-color: var(--primary-hover); }
        .btn-green { background-color: var(--success); color: white; }
        .btn-green:hover { background-color: var(--success-hover); }
        
        .btn-red { background-color: var(--danger); color: white; width: 32px; flex: none; padding: 6px 0; text-align: center; font-size: 13px;}
        .btn-edit { background-color: var(--warning); color: white; width: 32px; flex: none; padding: 6px 0; text-align: center; font-size: 13px;}
        .btn-move { background-color: var(--move); color: white; width: 36px; flex: none; padding: 6px 0; font-size: 13px;}
        
        .btn-finish { background-color: var(--success); color: white; width: auto; padding: 8px 15px; font-size: 15px; margin-top: 10px;}
        .btn-suggest { background-color: #8e44ad; color: white; margin-bottom: 10px; font-size: 14px; padding: 8px;}
        
        .item { display: flex; justify-content: space-between; align-items: center; padding: 8px 5px; border-bottom: 1px solid var(--border-color); gap: 8px; flex-wrap: wrap;}
        .item.done { opacity: 0.5; }
        .item.done .item-details { text-decoration: line-through; }
        
        .item-content { flex-grow: 1; display: flex; flex-direction: column; cursor: pointer; min-width: 120px;}
        .item-title { font-weight: bold; font-size: 15px; color: var(--text-color);}
        .item-meta { font-size: 13px; color: #888; margin-top: 2px; display: flex; align-items: center; gap: 8px;}
        .item-price { font-weight: bold; color: var(--text-color); text-align: right; min-width: 65px; font-size: 14px;}
        
        .qty-controls { display: flex; align-items: center; gap: 3px; background: var(--border-color); border-radius: 4px; padding: 2px;}
        .qty-controls button { background: transparent; color: var(--text-color); padding: 2px 6px; font-size: 14px; width: auto; border: none; }
        
        .category-header { background-color: var(--cat-header); padding: 6px 8px; margin-top: 15px; border-radius: 5px; font-weight: bold; color: var(--text-color); border-left: 4px solid var(--primary); font-size: 15px;}
        
        .total-box { margin-top: 25px; padding: 12px; background-color: var(--total-bg); color: var(--total-text); border-radius: 8px; font-size: 18px; font-weight: bold; display: flex; justify-content: space-between; flex-wrap: wrap; align-items: center; gap: 10px;}
        .total-amount { display: flex; flex-direction: column; }
        .total-amount span:last-child { font-size: 20px; color: var(--success); }
        
        .checkbox-custom { width: 22px; height: 22px; border: 2px solid var(--primary); border-radius: 4px; display: inline-block; text-align: center; line-height: 22px; font-weight: bold; color: transparent; flex-shrink: 0; transition: 0.2s; font-size: 14px;}
        .item.done .checkbox-custom { background-color: var(--primary); color: white; }

        .assign-box { display: flex; gap: 6px; width: 100%; margin-top: 5px; align-items: center;}
        .assign-box select, .assign-box input { padding: 6px; font-size: 13px; }
        
        #mainView, #managementView, #statsView { display: none; }
        #mainView.active, #managementView.active, #statsView.active { display: block; }
        
        .mgmt-section { margin-bottom: 25px; background: var(--bg-color); padding: 12px; border-radius: 8px; border: 1px solid var(--border-color);}
        .mgmt-list-item { display: flex; justify-content: space-between; align-items: center; padding: 8px; border-bottom: 1px solid var(--border-color); margin-bottom: 4px; border-radius: 4px; font-size: 15px;}
        
        .options-bar { display: flex; justify-content: flex-end; margin-bottom: 8px; font-size: 13px; color: var(--text-color);}
        .options-bar label { display: flex; align-items: center; gap: 5px; cursor: pointer; }
        
        .stat-card { background: var(--bg-color); padding: 12px; border-radius: 8px; margin-bottom: 15px; text-align: center; border: 1px solid var(--border-color);}
        .stat-value { font-size: 24px; font-weight: bold; color: var(--primary); margin-top: 8px;}
        .chart-container { position: relative; height: 250px; width: 100%; margin-bottom: 25px;}
        
        .edit-mode-container { width: 100%; display: flex; flex-direction: column; gap: 8px; background: var(--bg-color); padding: 8px; border-radius: 5px; border: 1px dashed var(--border-color);}
        .edit-row { display: flex; gap: 8px; flex-wrap: wrap; }
        .edit-row > * { flex: 1; min-width: 90px; }
    </style>
</head>
<body>

<div class="container">
    <div class="header-bar">
        <h1><img src="<?php echo $svgLogo; ?>" alt="Logo" class="header-logo"> Einkaufsliste <span style="color:var(--primary)">Pro</span></h1>
        
        <div>
            <button class="hamburger-btn" onclick="toggleMenu()" title="Menü">☰</button>
            <div id="hamburgerMenu" class="dropdown-menu">
                <button class="menu-btn" onclick="switchView('mainView'); toggleMenu();">🛒 Einkaufen</button>
                <button class="menu-btn" onclick="switchView('statsView'); toggleMenu();">📊 Statistiken</button>
                <button class="menu-btn" onclick="switchView('managementView'); toggleMenu();">⚙️ Verwaltung</button>
                <button class="menu-btn" onclick="toggleTheme(); toggleMenu();">🌓 Dark Mode</button>
            </div>
        </div>
    </div>
    
    <div id="mainView" class="active">
        <div class="row" style="align-items: center;">
            <div style="flex: 3;">
                <select id="storeSelect" onchange="renderList()"></select>
            </div>
            <div style="flex: 1; min-width: auto;">
                <button class="btn-green" onclick="addStore()">+ Laden</button>
            </div>
        </div>
        
        <div id="optionsBarContainer" class="options-bar">
            <label><input type="checkbox" id="hideCompleted" onchange="toggleHideCompleted()"> Erledigte ausblenden</label>
        </div>

        <button id="btnSuggestions" class="btn-suggest" style="display:none;" onclick="showSuggestions()">💡 Smarte Vorschläge aus Historie laden</button>
        <div id="suggestionsContainer" style="display:none; margin-bottom:15px; background:var(--bg-color); padding:10px; border-radius:5px; border:1px solid var(--border-color);"></div>

        <div class="row">
            <input type="text" id="itemName" list="productOptions" placeholder="Produktname (z.B. Milch)" style="flex: 2; min-width: 200px;" oninput="handleItemNameInput()">
            <datalist id="productOptions"></datalist>
            
            <div id="categoryContainer" style="flex: 1;">
                <input type="text" id="itemCategory" list="categoryOptions" placeholder="Kategorie (z.B. Kühlregal)">
            </div>
            <datalist id="categoryOptions"></datalist>
        </div>
        <div class="row">
            <input type="number" id="itemQty" placeholder="Stückzahl" value="1" min="0.1" step="any" style="flex: 1;">
            <input type="number" id="itemPrice" placeholder="Einzelpreis (€)" step="0.01" min="0" style="flex: 1;">
            <button onclick="addItem()" style="flex: 1;">Hinzufügen</button>
        </div>

        <div id="listContainer"></div>
        
        <div class="total-box" id="totalBox">
            <div class="total-amount">
                <span style="font-size: 13px; font-weight: normal;">Gesamtsumme:</span>
                <span id="grandTotal">0.00 €</span>
            </div>
            <button class="btn-finish" onclick="finishShopping()">✅ Einkauf erledigt</button>
        </div>
    </div>

    <div id="statsView">
        <h2 style="margin-top: 0; font-size: 18px;">Dein Dashboard</h2>
        <div class="row">
            <div class="stat-card">
                <div style="font-size: 14px;">Ausgaben dieser Monat</div>
                <div class="stat-value" id="statThisMonth">0.00 €</div>
            </div>
            <div class="stat-card">
                <div style="font-size: 14px;">Ausgaben letzter Monat</div>
                <div class="stat-value" id="statLastMonth" style="color: #7f8c8d;">0.00 €</div>
            </div>
        </div>
        <h3 style="font-size: 16px;">Ausgaben nach Kategorie</h3>
        <div class="chart-container"><canvas id="categoryChart"></canvas></div>
        <h3 style="font-size: 16px;">Ausgaben nach Laden</h3>
        <div class="chart-container"><canvas id="storeChart"></canvas></div>
    </div>

    <div id="managementView">
        <div class="mgmt-section">
            <h2 style="margin-top: 0; font-size: 18px;">🏪 Läden verwalten</h2>
            <div id="mgmtStoreList"></div>
        </div>
        <div class="mgmt-section">
            <h2 style="margin-top: 0; font-size: 18px;">🏷️ Kategorien verwalten</h2>
            <div id="mgmtCategoryList"></div>
        </div>
        <div class="mgmt-section">
            <h2 style="margin-top: 0; font-size: 18px;">📦 Produkte verwalten</h2>
            <div id="mgmtProductList"></div>
        </div>
    </div>
</div>

<script>
    let appData = {};
    const INBOX_NAME = '📥 Sammelliste';
    let charts = {};

    function toggleMenu() { document.getElementById("hamburgerMenu").classList.toggle("show"); }

    window.onclick = function(event) {
        if (!event.target.matches('.hamburger-btn')) {
            var dropdowns = document.getElementsByClassName("dropdown-menu");
            for (var i = 0; i < dropdowns.length; i++) {
                if (dropdowns[i].classList.contains('show')) dropdowns[i].classList.remove('show');
            }
        }
    }

    function sanitizeData() {
        let needsSave = false;
        
        if (!appData[INBOX_NAME]) { appData[INBOX_NAME] = []; needsSave = true; }
        if (!appData['_memory'] || Array.isArray(appData['_memory'])) { appData['_memory'] = {}; needsSave = true; }
        if (!appData['_archive']) { appData['_archive'] = []; needsSave = true; }
        if (!appData['_settings']) { appData['_settings'] = { darkMode: false, hideCompleted: false }; needsSave = true; }

        for (let key in appData['_memory']) {
            if (!key || key.trim() === '') { delete appData['_memory'][key]; needsSave = true; continue; }
            let mem = appData['_memory'][key];

            if (mem.prices !== undefined) {
                let newStores = {};
                for (let s in mem.prices) {
                    newStores[s] = { price: parseFloat(mem.prices[s]) || 0, category: mem.category || 'Sonstiges' };
                }
                appData['_memory'][key] = { global_category: mem.category || 'Sonstiges', stores: newStores };
                mem = appData['_memory'][key];
                needsSave = true;
            }

            if (!mem.stores || typeof mem.stores !== 'object' || Array.isArray(mem.stores)) { mem.stores = {}; needsSave = true; }
            if (!mem.global_category) { mem.global_category = 'Sonstiges'; needsSave = true; }

            for (let store in mem.stores) {
                if (!appData[store] && store !== INBOX_NAME) { delete mem.stores[store]; needsSave = true; continue; }
                if (typeof mem.stores[store].price !== 'number') { mem.stores[store].price = parseFloat(mem.stores[store].price) || 0; needsSave = true; }
                if (!mem.stores[store].category) { mem.stores[store].category = 'Sonstiges'; needsSave = true; }
            }
        }

        for (let store in appData) {
            if (store.startsWith('_')) continue;
            if (!Array.isArray(appData[store])) { appData[store] = []; needsSave = true; }
            
            let cleanList = [];
            appData[store].forEach(item => {
                if (item && typeof item === 'object' && item.name && item.name.trim() !== '') {
                    cleanList.push({
                        name: item.name.trim(),
                        category: item.category || 'Sonstiges',
                        qty: parseFloat(item.qty) || 1,
                        price: parseFloat(item.price) || 0,
                        done: !!item.done
                    });
                } else {
                    needsSave = true;
                }
            });
            if(appData[store].length !== cleanList.length) {
                appData[store] = cleanList;
                needsSave = true;
            }
        }
        return needsSave;
    }

    async function loadData() {
        try {
            const fetchUrl = '?api=true&t=' + new Date().getTime();
            const response = await fetch(fetchUrl);
            if (response.status === 401) { window.location.reload(); return; }
            appData = await response.json();
            
            if (sanitizeData()) {
                await fetch('?api=true', { method: 'POST', body: JSON.stringify(appData), headers: { 'Content-Type': 'application/json' } });
            }
        } catch (e) {
            console.error("Daten-Ladefehler", e);
            return;
        }
        
        if(appData['_settings'].darkMode) document.documentElement.setAttribute('data-theme', 'dark');
        document.getElementById('hideCompleted').checked = appData['_settings'].hideCompleted;
        
        updateStoreSelect(); updateCategoryDatalist(); updateProductDatalist(); renderList();
    }

    async function saveData() {
        for (let store in appData) {
            if (store.startsWith('_')) continue;
            appData[store].forEach(item => delete item.isEditing);
        }
        
        sanitizeData();
        
        const response = await fetch('?api=true', { method: 'POST', body: JSON.stringify(appData), headers: { 'Content-Type': 'application/json' } });
        if (response.status === 401) { window.location.reload(); return; }
        if (!response.ok) { alert("Speicherfehler! Bitte die Seite neu laden."); return; }

        updateCategoryDatalist(); updateProductDatalist(); updateStoreSelect();
        
        if (document.getElementById('managementView').classList.contains('active')) renderManagement();
        if (document.getElementById('statsView').classList.contains('active')) renderStats();
        if (document.getElementById('mainView').classList.contains('active')) renderList();
    }

    function switchView(viewId) {
        document.getElementById('mainView').classList.remove('active');
        document.getElementById('managementView').classList.remove('active');
        document.getElementById('statsView').classList.remove('active');
        document.getElementById(viewId).classList.add('active');
        
        if (viewId === 'mainView') { updateStoreSelect(); renderList(); } 
        else if (viewId === 'managementView') { renderManagement(); } 
        else if (viewId === 'statsView') { renderStats(); }
    }

    function toggleTheme() {
        appData['_settings'].darkMode = !appData['_settings'].darkMode;
        if(appData['_settings'].darkMode) document.documentElement.setAttribute('data-theme', 'dark');
        else document.documentElement.removeAttribute('data-theme');
        saveData();
    }

    function toggleHideCompleted() {
        appData['_settings'].hideCompleted = document.getElementById('hideCompleted').checked;
        saveData();
    }

    function handleItemNameInput() {
        const currentStore = document.getElementById('storeSelect').value;
        if (currentStore === INBOX_NAME) return;
        
        const name = document.getElementById('itemName').value.trim().toLowerCase();
        const mem = appData['_memory'][name];
        
        if (mem && mem.stores && mem.stores[currentStore]) {
            const storeData = mem.stores[currentStore];
            if (storeData.price > 0 && document.getElementById('itemPrice').value === '') document.getElementById('itemPrice').value = storeData.price;
            if (storeData.category && storeData.category !== 'Sonstiges') document.getElementById('itemCategory').value = storeData.category;
        } else if (mem && mem.global_category && mem.global_category !== 'Sonstiges') {
            document.getElementById('itemCategory').value = mem.global_category;
        }
    }

    window.updateEditMask = function(index) {
        const selectedStore = document.getElementById(`editStore_${index}`).value;
        const nameInputStr = document.getElementById(`editName_${index}`).value.trim().toLowerCase();
        const catInput = document.getElementById(`editCat_${index}`);
        const priceInput = document.getElementById(`editPrice_${index}`);
        
        if (selectedStore === INBOX_NAME) { catInput.value = ''; priceInput.value = 0; return; }

        const mem = appData['_memory'][nameInputStr];
        if (mem) {
            if (mem.stores && mem.stores[selectedStore]) {
                catInput.value = mem.stores[selectedStore].category !== 'Sonstiges' ? mem.stores[selectedStore].category : (mem.global_category !== 'Sonstiges' ? mem.global_category : '');
                priceInput.value = mem.stores[selectedStore].price > 0 ? mem.stores[selectedStore].price : 0;
            } else {
                catInput.value = mem.global_category !== 'Sonstiges' ? mem.global_category : '';
                priceInput.value = 0;
            }
        } else { priceInput.value = 0; }
    };

    window.updateAssignCategory = function(index, nameStr) {
        const store = document.getElementById(`assignStore_${index}`).value;
        const mem = appData['_memory'][nameStr.toLowerCase()];
        const catInput = document.getElementById(`assignCat_${index}`);
        
        if (store && mem && mem.stores && mem.stores[store] && mem.stores[store].category !== 'Sonstiges') {
            catInput.value = mem.stores[store].category;
        } else if (mem && mem.global_category !== 'Sonstiges') {
            catInput.value = mem.global_category;
        }
    };

    function showSuggestions() {
        const container = document.getElementById('suggestionsContainer');
        if(container.style.display === 'block') { container.style.display = 'none'; return; }
        container.innerHTML = '<strong>Vorschläge (Oft gekauft):</strong><br>';
        
        const frequencies = {};
        appData['_archive'].forEach(trip => {
            trip.items.forEach(item => { frequencies[item.name.toLowerCase()] = (frequencies[item.name.toLowerCase()] || 0) + 1; });
        });

        const currentItems = new Set();
        for (let store in appData) {
            if (store.startsWith('_')) continue;
            appData[store].forEach(i => currentItems.add(i.name.toLowerCase()));
        }

        const suggestions = Object.keys(frequencies).filter(name => frequencies[name] >= 2 && !currentItems.has(name)).sort((a, b) => frequencies[b] - frequencies[a]).slice(0, 8);
        if(suggestions.length === 0) {
            container.innerHTML += '<span style="font-size:13px; color:#888;">Noch nicht genug Daten im Archiv gesammelt.</span>';
        } else {
            suggestions.forEach(name => {
                const niceName = name.charAt(0).toUpperCase() + name.slice(1);
                container.innerHTML += `<button style="width:auto; margin:4px; padding:4px 10px; font-size:13px; background:var(--primary); color:white; border-radius:15px;" onclick="addSuggestion('${niceName}')">+ ${niceName}</button>`;
            });
        }
        container.style.display = 'block';
    }

    function addSuggestion(name) {
        document.getElementById('itemName').value = name;
        document.getElementById('suggestionsContainer').style.display = 'none';
        document.getElementById('itemName').focus();
    }

    function renderStats() {
        const archive = appData['_archive'] || [];
        const now = new Date();
        const currentYear = now.getFullYear(); const currentMonth = now.getMonth();
        let lastMonth = currentMonth - 1; let lastMonthYear = currentYear;
        if(lastMonth < 0) { lastMonth = 11; lastMonthYear--; }

        let totalThisMonth = 0; let totalLastMonth = 0; let catDataThisMonth = {}; let storeDataThisMonth = {};

        archive.forEach(trip => {
            const tripDate = new Date(trip.date);
            if (tripDate.getFullYear() === currentYear && tripDate.getMonth() === currentMonth) {
                totalThisMonth += trip.total;
                storeDataThisMonth[trip.store] = (storeDataThisMonth[trip.store] || 0) + trip.total;
                trip.items.forEach(item => {
                    const cat = item.category || 'Sonstiges';
                    catDataThisMonth[cat] = (catDataThisMonth[cat] || 0) + (item.qty * item.price);
                });
            } else if (tripDate.getFullYear() === lastMonthYear && tripDate.getMonth() === lastMonth) {
                totalLastMonth += trip.total;
            }
        });

        document.getElementById('statThisMonth').textContent = totalThisMonth.toFixed(2) + ' €';
        document.getElementById('statLastMonth').textContent = totalLastMonth.toFixed(2) + ' €';

        const textColor = appData['_settings'].darkMode ? '#e0e0e0' : '#333';
        if(charts.catChart) charts.catChart.destroy();
        charts.catChart = new Chart(document.getElementById('categoryChart'), {
            type: 'pie',
            data: { labels: Object.keys(catDataThisMonth), datasets: [{ data: Object.values(catDataThisMonth), backgroundColor: ['#3498db', '#e74c3c', '#2ecc71', '#f1c40f', '#9b59b6', '#e67e22', '#1abc9c'] }] },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { labels: { color: textColor } } } }
        });

        if(charts.storeChart) charts.storeChart.destroy();
        charts.storeChart = new Chart(document.getElementById('storeChart'), {
            type: 'bar',
            data: { labels: Object.keys(storeDataThisMonth), datasets: [{ label: 'Ausgaben in €', data: Object.values(storeDataThisMonth), backgroundColor: '#3498db' }] },
            options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: textColor } }, y: { ticks: { color: textColor } } }, plugins: { legend: { display: false } } }
        });
    }

    function updateProductDatalist() {
        const datalist = document.getElementById('productOptions'); datalist.innerHTML = '';
        const productNames = new Set();
        for (const key in appData['_memory']) productNames.add(key.charAt(0).toUpperCase() + key.slice(1));
        Array.from(productNames).sort((a, b) => a.localeCompare(b, 'de')).forEach(name => datalist.appendChild(new Option(name, name)));
    }

    function updateStoreSelect(selectName = null) {
        const select = document.getElementById('storeSelect');
        const currentSelection = selectName || select.value; select.innerHTML = '';
        let storeNames = Object.keys(appData).filter(s => !s.startsWith('_') && s !== INBOX_NAME).sort((a, b) => a.localeCompare(b, 'de'));
        storeNames.unshift(INBOX_NAME);
        storeNames.forEach(storeName => select.appendChild(new Option(storeName, storeName)));
        if (currentSelection && appData[currentSelection]) select.value = currentSelection;
    }

    function updateCategoryDatalist() {
        const datalist = document.getElementById('categoryOptions'); datalist.innerHTML = '';
        const categories = new Set();
        for (const store in appData) {
            if (store.startsWith('_')) continue;
            appData[store].forEach(item => { if(item.category && item.category !== 'Sonstiges') categories.add(item.category); });
        }
        for (const key in appData['_memory']) {
            if(appData['_memory'][key].global_category !== 'Sonstiges') categories.add(appData['_memory'][key].global_category);
            for(let s in appData['_memory'][key].stores) {
                if(appData['_memory'][key].stores[s].category !== 'Sonstiges') categories.add(appData['_memory'][key].stores[s].category);
            }
        }
        Array.from(categories).sort((a, b) => a.localeCompare(b, 'de')).forEach(cat => datalist.appendChild(new Option(cat, cat)));
    }

    function updateMemory(name, category, store, price) {
        const nameKey = name.toLowerCase().trim();
        if (!nameKey) return;
        if (!appData['_memory'][nameKey] || Array.isArray(appData['_memory'][nameKey])) {
            appData['_memory'][nameKey] = { global_category: 'Sonstiges', stores: {} };
        }
        
        if (category && category !== 'Sonstiges' && category.trim() !== '') {
            appData['_memory'][nameKey].global_category = category;
        }
        
        if (store && store !== INBOX_NAME && store.trim() !== '') {
            if (!appData['_memory'][nameKey].stores[store] || Array.isArray(appData['_memory'][nameKey].stores[store])) {
                appData['_memory'][nameKey].stores[store] = { price: 0, category: 'Sonstiges' };
            }
            
            if (price > 0) {
                appData['_memory'][nameKey].stores[store].price = price;
            }
            if (category && category !== 'Sonstiges' && category.trim() !== '') {
                appData['_memory'][nameKey].stores[store].category = category;
            }
        }
    }

    function changeQty(index, amount) {
        const currentStore = document.getElementById('storeSelect').value;
        let newQty = appData[currentStore][index].qty + amount;
        if(newQty > 0) { appData[currentStore][index].qty = newQty; saveData(); }
    }

    function addItem() {
        const currentStore = document.getElementById('storeSelect').value;
        const nameInput = document.getElementById('itemName');
        const categoryInput = document.getElementById('itemCategory');
        const qtyInput = document.getElementById('itemQty');
        const priceInput = document.getElementById('itemPrice');

        const name = nameInput.value.trim();
        if (name === '') return;

        const qty = parseFloat(qtyInput.value) || 1;
        let price = parseFloat(priceInput.value.replace(',', '.')) || 0;
        
        if (price === 0 && currentStore !== INBOX_NAME) {
            const mem = appData['_memory'][name.toLowerCase()];
            if (mem && mem.stores && mem.stores[currentStore] && mem.stores[currentStore].price > 0) {
                price = mem.stores[currentStore].price;
            }
        }
        const category = (currentStore === INBOX_NAME) ? 'Sonstiges' : (categoryInput.value.trim() || 'Sonstiges');

        appData[currentStore].push({ name, category, qty, price, done: false });
        updateMemory(name, category, currentStore, price);

        nameInput.value = ''; qtyInput.value = '1'; priceInput.value = '';
        document.getElementById('suggestionsContainer').style.display = 'none';
        nameInput.focus();
        saveData();
    }

    function toggleItem(index) {
        const currentStore = document.getElementById('storeSelect').value;
        if (appData[currentStore][index].isEditing) return;
        appData[currentStore][index].done = !appData[currentStore][index].done;
        saveData();
    }

    function deleteItem(index) {
        const currentStore = document.getElementById('storeSelect').value;
        if(confirm('Wirklich löschen?')) { appData[currentStore].splice(index, 1); saveData(); }
    }

    function moveItem(index) {
        const targetStore = document.getElementById(`assignStore_${index}`).value;
        const targetCategory = document.getElementById(`assignCat_${index}`).value.trim() || 'Sonstiges';
        if (!targetStore) return alert("Bitte wähle einen Ziel-Laden aus!");

        const item = appData[INBOX_NAME][index];
        item.category = targetCategory;

        if (item.price === 0) {
            const mem = appData['_memory'][item.name.toLowerCase()];
            if (mem && mem.stores && mem.stores[targetStore] && mem.stores[targetStore].price > 0) {
                item.price = mem.stores[targetStore].price;
            }
        }

        updateMemory(item.name, targetCategory, targetStore, item.price);
        if (!appData[targetStore]) appData[targetStore] = [];
        appData[targetStore].push(item);
        appData[INBOX_NAME].splice(index, 1);
        saveData();
    }

    function finishShopping() {
        const currentStore = document.getElementById('storeSelect').value;
        if (currentStore === INBOX_NAME) return;

        const checkedCount = appData[currentStore].filter(i => i.done).length;
        if (checkedCount === 0) {
            alert("Bitte hake zuerst die gekauften Artikel ab, bevor du den Einkauf abschließt.");
            return;
        }

        if(!confirm(`Möchtest du den Einkauf abschließen?\nEs werden nur die abgehakten Produkte (${checkedCount} Stück) archiviert und aus der Liste entfernt.`)) return;

        let total = 0; 
        let tripItems = [];
        let remainingItems = [];

        appData[currentStore].forEach(item => {
            if (item.done) {
                updateMemory(item.name, item.category, currentStore, item.price);
                tripItems.push({...item});
                total += (item.qty * item.price);
            } else {
                remainingItems.push(item);
            }
        });

        if(tripItems.length > 0) {
            appData['_archive'].push({ date: new Date().toISOString(), store: currentStore, total: total, items: tripItems });
        }
        
        appData[currentStore] = remainingItems; 
        saveData();
    }

    function addStore() {
        const newStore = prompt("Wie soll der neue Laden heißen?");
        if (newStore && newStore.trim() !== '' && !newStore.startsWith('_') && newStore !== INBOX_NAME) {
            if (!appData[newStore.trim()]) { appData[newStore.trim()] = []; updateStoreSelect(newStore.trim()); saveData(); }
        }
    }

    function renderList() {
        const currentStore = document.getElementById('storeSelect').value;
        const container = document.getElementById('listContainer'); container.innerHTML = '';
        const isInbox = (currentStore === INBOX_NAME);
        
        document.getElementById('categoryContainer').style.display = isInbox ? 'none' : 'block';
        document.getElementById('totalBox').style.display = isInbox ? 'none' : 'flex';
        document.getElementById('optionsBarContainer').style.display = isInbox ? 'none' : 'flex';
        document.getElementById('btnSuggestions').style.display = isInbox ? 'block' : 'none';

        if (!currentStore || !appData[currentStore]) return;

        let items = appData[currentStore]; 
        let grandTotal = 0;

        if (!isInbox && items.length > 0) {
            items.forEach(item => { grandTotal += (item.qty * item.price); });
        }

        if (isInbox) {
            if(items.length === 0) container.innerHTML = '<p style="text-align:center; color:#7f8c8d; font-size:14px;">Die Sammelliste ist leer.</p>';
            let sortedItems = items.map((item, index) => ({...item, originalIndex: index})).sort((a, b) => a.name.localeCompare(b.name, 'de'));

            sortedItems.forEach(item => {
                const itemDiv = document.createElement('div'); itemDiv.className = 'item'; itemDiv.style.flexDirection = 'column'; itemDiv.style.alignItems = 'flex-start';
                const positionTotal = item.qty * item.price;
                const detailText = `<div class="qty-controls" onclick="event.stopPropagation()"><button onclick="changeQty(${item.originalIndex}, -1)">-</button><span>${item.qty}</span><button onclick="changeQty(${item.originalIndex}, 1)">+</button></div>` + (item.price > 0 ? ` à ${parseFloat(item.price).toFixed(2)} € = ${positionTotal.toFixed(2)} €` : '');

                const memoryData = appData['_memory'][item.name.toLowerCase()];
                let suggestedStore = '', suggestedCat = item.category !== 'Sonstiges' ? item.category : '', minPrice = Infinity;

                if (memoryData) {
                    suggestedCat = memoryData.global_category || suggestedCat;
                    if (memoryData.stores) {
                        for (let store in memoryData.stores) {
                            if (!appData[store]) continue;
                            let p = memoryData.stores[store].price;
                            if (p > 0 && p < minPrice) { minPrice = p; suggestedStore = store; } 
                            else if (suggestedStore === '' && p === 0) suggestedStore = store;
                        }
                    }
                }
                
                if (suggestedStore && memoryData && memoryData.stores[suggestedStore] && memoryData.stores[suggestedStore].category !== 'Sonstiges') {
                    suggestedCat = memoryData.stores[suggestedStore].category;
                }

                let storeOptionsHtml = '<option value="">-- Ziel-Laden --</option>';
                Object.keys(appData).filter(s => !s.startsWith('_') && s !== INBOX_NAME).sort((a, b) => a.localeCompare(b, 'de')).forEach(store => {
                    let pText = (memoryData && memoryData.stores && memoryData.stores[store] && memoryData.stores[store].price > 0) ? ` (${memoryData.stores[store].price.toFixed(2)} €)` : '';
                    storeOptionsHtml += `<option value="${store}" ${(store === suggestedStore)?'selected':''}>${store}${pText}</option>`;
                });

                const safeName = item.name.replace(/'/g, "\\'").replace(/"/g, '&quot;');

                itemDiv.innerHTML = `
                    <div style="display: flex; justify-content: space-between; width: 100%; align-items: center;">
                        <div class="item-title">${item.name} <span class="item-meta">${detailText}</span></div>
                        <button class="btn-red" onclick="deleteItem(${item.originalIndex})">X</button>
                    </div>
                    <div class="assign-box">
                        <select id="assignStore_${item.originalIndex}" onchange="updateAssignCategory(${item.originalIndex}, '${safeName}')" style="flex: 2;">${storeOptionsHtml}</select>
                        <input type="text" id="assignCat_${item.originalIndex}" list="categoryOptions" placeholder="Kategorie" style="flex: 2;" value="${suggestedCat}">
                        <button class="btn-move" onclick="moveItem(${item.originalIndex})">➔</button>
                    </div>`;
                container.appendChild(itemDiv);
            });
            return;
        }

        let storeOptionsHtmlEdit = `<option value="${currentStore}">${currentStore}</option>`;
        Object.keys(appData).filter(s => !s.startsWith('_') && s !== INBOX_NAME && s !== currentStore).sort((a,b)=>a.localeCompare(b,'de')).forEach(store => {
            storeOptionsHtmlEdit += `<option value="${store}">${store}</option>`;
        });

        const grouped = {};
        items.forEach((item, index) => {
            if (item.done && appData['_settings'].hideCompleted) return;
            const cat = item.category || 'Sonstiges';
            if (!grouped[cat]) grouped[cat] = [];
            grouped[cat].push({ ...item, originalIndex: index }); 
        });

        Object.keys(grouped).sort((a, b) => a.localeCompare(b, 'de')).forEach(category => {
            const catHeader = document.createElement('div'); catHeader.className = 'category-header'; catHeader.textContent = category;
            container.appendChild(catHeader);

            grouped[category].sort((a, b) => a.name.localeCompare(b.name, 'de')).forEach(item => {
                const positionTotal = item.qty * item.price;
                const itemDiv = document.createElement('div');
                
                if (item.isEditing) {
                    itemDiv.className = 'item';
                    let currentStoreOptions = storeOptionsHtmlEdit.replace(`value="${currentStore}"`, `value="${currentStore}" selected`);
                    
                    itemDiv.innerHTML = `
                        <div class="edit-mode-container" onclick="event.stopPropagation()">
                            <div class="edit-row">
                                <input type="text" id="editName_${item.originalIndex}" value="${item.name.replace(/"/g, '&quot;')}" placeholder="Name">
                                <input type="text" id="editCat_${item.originalIndex}" list="categoryOptions" value="${item.category.replace(/"/g, '&quot;')}" placeholder="Kategorie">
                                <select id="editStore_${item.originalIndex}" title="In anderen Laden verschieben" onchange="updateEditMask(${item.originalIndex})">${currentStoreOptions}</select>
                            </div>
                            <div class="edit-row" style="align-items: center;">
                                <input type="number" id="editQty_${item.originalIndex}" value="${item.qty}" step="any" placeholder="Menge">
                                <input type="number" id="editPrice_${item.originalIndex}" value="${item.price}" step="0.01" placeholder="Preis (€)">
                                <button class="btn-green" onclick="saveEdit(${item.originalIndex})" style="padding: 10px;">💾</button>
                                <button class="btn-red" onclick="cancelEdit(${item.originalIndex})">X</button>
                            </div>
                        </div>
                    `;
                } else {
                    itemDiv.className = `item ${item.done ? 'done' : ''}`;
                    const priceFormatted = positionTotal > 0 ? positionTotal.toFixed(2) + ' €' : '';
                    const qtyHtml = `<div class="qty-controls" onclick="event.stopPropagation()"><button onclick="changeQty(${item.originalIndex}, -1)">-</button><span style="min-width:20px; text-align:center;">${item.qty}</span><button onclick="changeQty(${item.originalIndex}, 1)">+</button></div>`;
                    const detailText = `${qtyHtml} ${item.price > 0 ? ` à ${parseFloat(item.price).toFixed(2)} €` : ''}`;

                    itemDiv.innerHTML = `
                        <div class="checkbox-custom" onclick="toggleItem(${item.originalIndex})">${item.done ? '✓' : ''}</div>
                        <div class="item-content item-details" onclick="toggleItem(${item.originalIndex})">
                            <div class="item-title">${item.name}</div>
                            <div class="item-meta">${detailText}</div>
                        </div>
                        <div class="item-price item-details">${priceFormatted}</div>
                        <div style="display: flex; gap: 4px;">
                            <button class="btn-edit" onclick="event.stopPropagation(); editItem(${item.originalIndex})" title="Bearbeiten">✏️</button>
                            <button class="btn-red" onclick="event.stopPropagation(); deleteItem(${item.originalIndex})" title="Löschen">X</button>
                        </div>
                    `;
                }
                container.appendChild(itemDiv);
            });
        });
        document.getElementById('grandTotal').textContent = grandTotal.toFixed(2) + ' €';
    }

    function editItem(index) {
        const currentStore = document.getElementById('storeSelect').value;
        appData[currentStore][index].isEditing = true;
        renderList();
    }

    function cancelEdit(index) {
        const currentStore = document.getElementById('storeSelect').value;
        appData[currentStore][index].isEditing = false;
        renderList();
    }

    function saveEdit(index) {
        const currentStore = document.getElementById('storeSelect').value;
        const name = document.getElementById(`editName_${index}`).value.trim();
        const cat = document.getElementById(`editCat_${index}`).value.trim() || 'Sonstiges';
        const qty = parseFloat(document.getElementById(`editQty_${index}`).value) || 1;
        const price = parseFloat(document.getElementById(`editPrice_${index}`).value.replace(',', '.')) || 0;
        const newStore = document.getElementById(`editStore_${index}`).value;

        if (name !== '') {
            appData[currentStore][index].name = name;
            appData[currentStore][index].category = cat;
            appData[currentStore][index].qty = qty;
            appData[currentStore][index].price = price;
            
            updateMemory(name, cat, currentStore, price);

            if (newStore && newStore !== currentStore) {
                const itemToMove = appData[currentStore][index];
                delete itemToMove.isEditing; 
                appData[currentStore].splice(index, 1);
                
                if (!appData[newStore]) appData[newStore] = [];
                
                const mem = appData['_memory'][name.toLowerCase()];
                if (mem && mem.stores && mem.stores[newStore] && mem.stores[newStore].price > 0) {
                    itemToMove.price = mem.stores[newStore].price;
                    itemToMove.category = mem.stores[newStore].category;
                }
                
                appData[newStore].push(itemToMove);
            } else {
                appData[currentStore][index].isEditing = false;
            }
        } else {
            appData[currentStore][index].isEditing = false;
        }
        
        saveData();
    }

    function renderManagement() {
        const sDiv = document.getElementById('mgmtStoreList'); sDiv.innerHTML = '';
        Object.keys(appData).filter(s => !s.startsWith('_') && s !== INBOX_NAME).sort((a,b)=>a.localeCompare(b,'de')).forEach(store => {
            sDiv.innerHTML += `<div class="mgmt-list-item"><span>${store}</span><div style="display:flex;gap:5px;"><button class="btn-edit" onclick="mgmtRenameStore('${store.replace(/'/g, "\\'")}')">✏️</button><button class="btn-red" onclick="mgmtDeleteStore('${store.replace(/'/g, "\\'")}')">🗑️</button></div></div>`;
        });

        const categories = new Set();
        for (let s in appData) { if(!s.startsWith('_')) appData[s].forEach(i => { if(i.category !== 'Sonstiges') categories.add(i.category); }); }
        for (let k in appData['_memory']) {
            if(appData['_memory'][k].global_category !== 'Sonstiges') categories.add(appData['_memory'][k].global_category);
            for(let s in appData['_memory'][k].stores) { if(appData['_memory'][k].stores[s].category !== 'Sonstiges') categories.add(appData['_memory'][k].stores[s].category); }
        }
        const cDiv = document.getElementById('mgmtCategoryList'); cDiv.innerHTML = '';
        Array.from(categories).sort((a,b)=>a.localeCompare(b,'de')).forEach(cat => {
            cDiv.innerHTML += `<div class="mgmt-list-item"><span>${cat}</span><div style="display:flex;gap:5px;"><button class="btn-edit" onclick="mgmtRenameCategory('${cat.replace(/'/g, "\\'")}')">✏️</button><button class="btn-red" onclick="mgmtDeleteCategory('${cat.replace(/'/g, "\\'")}')">🗑️</button></div></div>`;
        });

        const pDiv = document.getElementById('mgmtProductList'); pDiv.innerHTML = '';
        let allProducts = Object.keys(appData['_memory']).sort((a,b)=>a.localeCompare(b,'de'));
        if(allProducts.length === 0) pDiv.innerHTML = '<p style="color:#999; font-size:14px;">Noch keine Produkte erfasst.</p>';
        allProducts.forEach(prodKey => {
            const niceName = prodKey.charAt(0).toUpperCase() + prodKey.slice(1);
            pDiv.innerHTML += `
                <div class="mgmt-list-item">
                    <span>${niceName}</span>
                    <div style="display:flex;gap:4px;">
                        <button class="btn-edit" onclick="mgmtRenameProduct('${prodKey.replace(/'/g, "\\'")}')">✏️</button>
                        <button class="btn-red" onclick="mgmtDeleteProduct('${prodKey.replace(/'/g, "\\'")}')">🗑️</button>
                    </div>
                </div>`;
        });
    }

    window.mgmtRenameStore = function(oldName) {
        const newName = prompt(`Neuer Name für Laden '${oldName}':`, oldName);
        if (!newName || newName.trim() === '' || newName === oldName || appData[newName]) return;
        
        appData[newName] = appData[oldName];
        delete appData[oldName];
        
        for (let k in appData['_memory']) {
            if (appData['_memory'][k].stores && appData['_memory'][k].stores[oldName]) {
                appData['_memory'][k].stores[newName] = appData['_memory'][k].stores[oldName];
                delete appData['_memory'][k].stores[oldName];
            }
        }
        
        appData['_archive'].forEach(trip => {
            if (trip.store === oldName) trip.store = newName;
        });
        
        saveData();
    };

    window.mgmtRenameCategory = function(oldCat) {
        const newCat = prompt(`Neuer Name für Kategorie '${oldCat}':`, oldCat);
        if (!newCat || newCat.trim() === '' || newCat === oldCat) return;
        
        for (let s in appData) {
            if (!s.startsWith('_')) {
                appData[s].forEach(item => {
                    if (item.category === oldCat) item.category = newCat;
                });
            }
        }
        
        for (let k in appData['_memory']) {
            if (appData['_memory'][k].global_category === oldCat) {
                appData['_memory'][k].global_category = newCat;
            }
            if (appData['_memory'][k].stores) {
                for (let s in appData['_memory'][k].stores) {
                    if (appData['_memory'][k].stores[s].category === oldCat) {
                        appData['_memory'][k].stores[s].category = newCat;
                    }
                }
            }
        }
        saveData();
    };

    window.mgmtRenameProduct = function(oldKey) {
        const niceName = oldKey.charAt(0).toUpperCase() + oldKey.slice(1);
        const newName = prompt(`Neuer Name für Produkt '${niceName}':`, niceName);
        if (!newName || newName.trim() === '') return;
        
        const newKey = newName.trim().toLowerCase();
        if (newKey === oldKey) return;
        
        appData['_memory'][newKey] = appData['_memory'][oldKey];
        delete appData['_memory'][oldKey];
        
        for (let s in appData) {
            if(!s.startsWith('_')) {
                appData[s].forEach(item => {
                    if (item.name.toLowerCase() === oldKey) item.name = newName.trim();
                });
            }
        }
        saveData();
    };

    window.mgmtDeleteProduct = function(key) {
        const niceName = key.charAt(0).toUpperCase() + key.slice(1);
        if(!confirm(`Produkt '${niceName}' wirklich aus der Verwaltung löschen?`)) return;
        
        delete appData['_memory'][key];
        
        if(confirm(`Sollen auch alle aktuellen Einträge von '${niceName}' aus deinen Einkaufslisten gelöscht werden?`)) {
            for (let s in appData) {
                if(!s.startsWith('_')) {
                    appData[s] = appData[s].filter(item => item.name.toLowerCase() !== key);
                }
            }
        }
        saveData();
    };

    function mgmtDeleteStore(store) {
        if(!confirm(`Laden '${store}' löschen?`)) return;
        delete appData[store];
        for (let k in appData['_memory']) if(appData['_memory'][k].stores) delete appData['_memory'][k].stores[store];
        saveData();
    }

    function mgmtDeleteCategory(cat) {
        if(!confirm(`Kategorie '${cat}' löschen?`)) return;
        for (let s in appData) if(!s.startsWith('_')) appData[s].forEach(i => { if(i.category===cat) i.category='Sonstiges'; });
        for (let k in appData['_memory']) {
            if (appData['_memory'][k].global_category === cat) appData['_memory'][k].global_category = 'Sonstiges';
            for (let s in appData['_memory'][k].stores) {
                if (appData['_memory'][k].stores[s].category === cat) appData['_memory'][k].stores[s].category = 'Sonstiges';
            }
        }
        saveData();
    }

    loadData();
</script>

</body>
</html>