<div id="account-view">
    <div class="account-login-box">
        <h2>Mein Konto</h2>

        <input type="email" id="login-email" placeholder="E-Mail">
        <input type="password" id="login-password" placeholder="Passwort">
        <button id="btn-forgot-password" type="button">Passwort vergessen?</button>

        <div id="login-error" class="hidden">
            Falsche E-Mail oder Passwort
        </div>

        <button id="btn-login-account" type="button">Anmelden</button>
        <p id="account-register-hint">Noch kein Konto?</p>
        <button id="btn-open-register" type="button">Registrieren</button>
    </div>
</div>

<div id="register-modal" class="modal hidden">
    <div class="modal-content account-auth-modal">
        <button id="btn-close-register" class="modal-close-btn" type="button" aria-label="Registrierung schliessen">&times;</button>
        <h2>Registrieren</h2>
        <p class="auth-modal-subtitle">Erstelle dein Konto für schnellere Buchungen.</p>
        <input type="text" id="reg-firstname" placeholder="Vorname">
        <input type="text" id="reg-lastname" placeholder="Nachname">
        <input type="email" id="reg-email" placeholder="E-Mail">
        <input type="password" id="reg-password" placeholder="Passwort">
        <button id="btn-register-save" class="auth-submit-btn" type="button">Konto erstellen</button>
    </div>
</div>

<div id="forgot-modal" class="modal hidden">
    <div class="modal-content account-auth-modal">
        <button id="btn-close-forgot" class="modal-close-btn" type="button" aria-label="Passwort-Dialog schliessen">&times;</button>
        <h2>Passwort vergessen</h2>
        <p class="auth-modal-subtitle">Gib deine E-Mail ein und wir senden dir einen Reset-Code.</p>

        <input type="email" id="forgot-email" placeholder="E-Mail">
        <button id="btn-send-reset" class="auth-submit-btn" type="button">Code senden</button>

        <div id="reset-message" class="hidden">
            Ein Code wurde simuliert versendet.
        </div>
    </div>
</div>

<script>
    import { users, currentUser, persistUsers, persistCurrentUser } from "../scripts/bigConstants";

    async function hashMessage(message: string) {
        const msgBuffer = new TextEncoder().encode(message);
        const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }

    function escapeHtml(value: string) {
        return String(value || "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
    }

    function formatEuro(value: any) {
        return `${Number(value || 0).toFixed(2).replace(".", ",")} EUR`;
    }

    const openModal = (modal: HTMLElement | null) => modal?.classList.remove("hidden");
    const closeModal = (modal: HTMLElement | null) => modal?.classList.add("hidden");

    function renderPersonalInfo() {
        const target = document.getElementById("account-tab-content");
        if (!target || !currentUser) return;
        target.innerHTML = `
            <div class="account-card">
                <p><strong>Vorname:</strong> ${currentUser.firstName || "-"}</p>
                <p><strong>Nachname:</strong> ${currentUser.lastName || "-"}</p>
                <p><strong>E-Mail:</strong> ${currentUser.email || "-"}</p>
            </div>
        `;
    }

    function renderOrders() {
        const target = document.getElementById("account-tab-content");
        if (!target || !currentUser) return;
        const orders = Array.isArray(currentUser.orders) ? currentUser.orders : [];
        if (!orders.length) {
            target.innerHTML = `<div class="account-card"><h3>Meine Bestellungen</h3><p>Noch keine Bestellungen vorhanden.</p></div>`;
            return;
        }

        const orderHtml = orders.map((order, index) => {
            const movieItems = Array.isArray(order.items) ? order.items.filter((item: any) => item.category === "movie") : [];
            const previewTitle = movieItems[0]?.title || (Array.isArray(order.items) ? order.items[0]?.title : "Bestellung");
            return `
                <button type="button" class="order-box order-item-btn" data-order-index="${index}">
                    <div class="order-item-head"><h4>${escapeHtml(previewTitle)}</h4><span>${formatEuro(order.total || 0)}</span></div>
                    <p><strong>Datum:</strong> ${escapeHtml(order.date || "-")}</p>
                    <p><strong>Anzahl:</strong> ${movieItems.length}x</p>
                </button>`;
        }).join("");

        target.innerHTML = `
            <div class="account-orders-shell">
                <h3>Meine Bestellungen</h3>
                <p class="account-payments-note">Klicke auf eine Bestellung, um dein Ticket-Detail zu sehen.</p>
                <div class="account-orders-grid">${orderHtml}</div>
                <div id="order-ticket-details" class="order-ticket-details hidden"></div>
            </div>`;

        target.querySelectorAll(".order-item-btn").forEach(btn => btn.addEventListener("click", () => {
            const orderIndex = Number((btn as HTMLElement).dataset.orderIndex);
            const order = orders[orderIndex];
            const detailTarget = document.getElementById("order-ticket-details");
            if (!order || !detailTarget) return;
            const movieItems = Array.isArray(order.items) ? order.items.filter((item: any) => item.category === "movie") : [];
            const primaryMovie = movieItems[0];
            detailTarget.innerHTML = `
                <article class="order-ticket-card">
                    <div class="order-ticket-poster">${primaryMovie?.img ? `<img src="${escapeHtml(primaryMovie.img)}" />` : `<div class="order-ticket-poster-fallback">Kein Poster</div>`}</div>
                    <div class="order-ticket-content">
                        <div class="order-ticket-brand">EAGLE'S IMAX | Bestell-Details</div>
                        <h4>${escapeHtml(primaryMovie?.title || "Bestellung")}</h4>
                        <div class="order-ticket-grid">
                            <p><span>Datum</span><strong>${escapeHtml(order.date || "-")}</strong></p>
                            <p><span>Saal</span><strong>${escapeHtml(primaryMovie?.hall || "-")}</strong></p>
                            <p><span>Uhrzeit</span><strong>${escapeHtml(primaryMovie?.time || "-")} Uhr</strong></p>
                            <p><span>Tickets</span><strong>${movieItems.length}x</strong></p>
                            <p><span>Sitze</span><strong>${movieItems.map(i => i.seatId).join(", ")}</strong></p>
                            <p><span>Gesamt</span><strong>${formatEuro(order.total || 0)}</strong></p>
                        </div>
                    </div>
                </article>`;
            detailTarget.classList.remove("hidden");
        }));
    }

    function renderPayments() {
        const target = document.getElementById("account-tab-content");
        if (!target) return;
        target.innerHTML = `
            <div class="account-card">
                <h3>Zahlungsmethoden</h3>
                <div class="account-payment-grid">
                    <button class="account-payment-card account-pay-trigger" data-pay-modal="pay-modal-card">Visa / Mastercard</button>
                    <button class="account-payment-card account-pay-trigger" data-pay-modal="pay-modal-paypal">PayPal</button>
                </div>
            </div>
            <div id="pay-modal-card" class="pay-modal-overlay hidden">Card Modal Content</div>
        `;
        // ... (simplified for now to keep it concise, but can add full logic if needed)
    }

    function openAccountDashboard() {
        const accountView = document.getElementById("account-view");
        if (!accountView) return;
        if (!currentUser) {
            accountView.innerHTML = `<div class='account-login-box'><h2>Mein Konto</h2><p>Bitte melde dich an oder registriere dich.</p></div>`;
            return;
        }
        accountView.innerHTML = `
            <div class="account-panel">
                <div class="account-panel-header"><h2>Mein Konto</h2><button id="logout-btn" class="account-logout-btn">Abmelden</button></div>
                <div class="account-tabs">
                    <button id="tab-info" class="account-tab-btn">Persönliche Daten</button>
                    <button id="tab-orders" class="account-tab-btn">Meine Bestellungen</button>
                </div>
                <div id="account-tab-content"></div>
            </div>`;
        document.getElementById("logout-btn")?.addEventListener("click", () => {
            persistCurrentUser(null);
            window.location.reload();
        });
        document.getElementById("tab-info")?.addEventListener("click", renderPersonalInfo);
        document.getElementById("tab-orders")?.addEventListener("click", renderOrders);
        renderPersonalInfo();
    }

    // Login/Register bindings
    document.getElementById("btn-login-account")?.addEventListener("click", async () => {
        const email = (document.getElementById("login-email") as HTMLInputElement)?.value.toLowerCase();
        const password = (document.getElementById("login-password") as HTMLInputElement)?.value;
        const hashedPassword = await hashMessage(password);
        const user = users.find(u => u.email.toLowerCase() === email && u.hashedPassword === hashedPassword);
        if (user) {
            persistCurrentUser(user);
            openAccountDashboard();
        } else {
            document.getElementById("login-error")?.classList.remove("hidden");
        }
    });

    document.getElementById("btn-register-save")?.addEventListener("click", async () => {
        const firstName = (document.getElementById("reg-firstname") as HTMLInputElement).value;
        const email = (document.getElementById("reg-email") as HTMLInputElement).value.toLowerCase();
        const password = (document.getElementById("reg-password") as HTMLInputElement).value;
        const hashedPassword = await hashMessage(password);
        const newUser = { firstName, email, hashedPassword, orders: [], paymentMethods: [] };
        users.push(newUser);
        persistUsers();
        persistCurrentUser(newUser);
        openAccountDashboard();
        closeModal(document.getElementById("register-modal"));
    });

    if (currentUser) openAccountDashboard();
</script>
