<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Portal - GO-ACS</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --secondary: #0ea5e9;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --dark: #1e1b4b;
            --darker: #0f0d24;
            --light: #f8fafc;
            --gray: #64748b;
            --card-bg: rgba(255, 255, 255, 0.05);
            --border: rgba(255, 255, 255, 0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--darker);
            color: var(--light);
            min-height: 100vh;
        }

        .portal-header {
            background: var(--dark);
            padding: 1rem 2rem;
            border-bottom: 1px solid var(--border);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            font-size: 1.25rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo i {
            color: var(--primary);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .user-name {
            font-weight: 500;
        }

        .logout-btn {
            background: none;
            border: none;
            color: var(--gray);
            cursor: pointer;
            padding: 8px;
            border-radius: 8px;
            transition: all 0.2s;
        }

        .logout-btn:hover {
            color: var(--danger);
            background: rgba(239, 68, 68, 0.1);
        }

        .portal-container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }

        .welcome-card {
            background: linear-gradient(135deg, #6366f1, #0ea5e9);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
        }

        .welcome-title {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
        }

        .welcome-subtitle {
            opacity: 0.9;
        }

        .grid-3 {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }

        .card {
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 1.5rem;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .card-title {
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .card-title i {
            color: var(--primary);
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid var(--border);
        }

        .info-row:last-child {
            border-bottom: none;
        }

        .info-label {
            color: var(--gray);
        }

        .info-value {
            font-weight: 500;
        }

        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .status-badge.online {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }

        .status-badge.active {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }

        .status-badge.paid {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }

        .status-badge.pending {
            background: rgba(245, 158, 11, 0.15);
            color: #f59e0b;
        }

        .status-badge.overdue {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
        }

        .status-badge.offline {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
        }

        .status-badge.suspended {
            background: rgba(245, 158, 11, 0.15);
            color: #f59e0b;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 18px;
            border-radius: 10px;
            font-weight: 500;
            font-size: 0.875rem;
            cursor: pointer;
            border: none;
            transition: all 0.2s;
        }

        .btn-primary {
            background: linear-gradient(135deg, #6366f1, #4f46e5);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(99, 102, 241, 0.3);
        }

        .btn-primary:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }

        .btn-secondary {
            background: var(--card-bg);
            color: var(--light);
            border: 1px solid var(--border);
        }

        .wifi-form {
            margin-top: 1rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            color: var(--gray);
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            background: rgba(0, 0, 0, 0.2);
            border: 1px solid var(--border);
            border-radius: 10px;
            color: var(--light);
        }

        .form-group input:focus {
            outline: none;
            border-color: var(--primary);
        }

        .invoice-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .invoice-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            margin-bottom: 0.5rem;
        }

        .invoice-no {
            font-weight: 500;
        }

        .invoice-period {
            font-size: 0.8rem;
            color: var(--gray);
        }

        .invoice-amount {
            font-weight: 600;
            color: var(--primary);
        }

        .package-card {
            background: linear-gradient(135deg, rgba(99, 102, 241, 0.2), rgba(14, 165, 233, 0.1));
            border: 1px solid rgba(99, 102, 241, 0.3);
        }

        .package-name {
            font-size: 1.25rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .package-speed {
            font-size: 2rem;
            font-weight: 800;
            color: var(--primary);
        }

        .package-price {
            color: var(--gray);
            margin-top: 0.5rem;
        }

        .toast {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            background: var(--dark);
            border: 1px solid var(--success);
            border-radius: 12px;
            padding: 1rem 1.5rem;
            display: flex;
            align-items: center;
            gap: 12px;
            transform: translateY(100px);
            opacity: 0;
            transition: all 0.3s;
            z-index: 1000;
        }

        .toast.show {
            transform: translateY(0);
            opacity: 1;
        }

        .toast.error {
            border-color: var(--danger);
        }

        .toast.error i {
            color: var(--danger);
        }

        .toast i {
            color: var(--success);
        }

        /* Connected Devices Styles */
        .connected-devices {
            max-height: 280px;
            overflow-y: auto;
        }

        .device-item {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 0.75rem;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            margin-bottom: 0.5rem;
        }

        .device-item:last-child {
            margin-bottom: 0;
        }

        .device-icon {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }

        .device-icon.phone {
            background: rgba(99, 102, 241, 0.15);
            color: #818cf8;
        }

        .device-icon.laptop {
            background: rgba(14, 165, 233, 0.15);
            color: #0ea5e9;
        }

        .device-icon.tablet {
            background: rgba(245, 158, 11, 0.15);
            color: #f59e0b;
        }

        .device-icon.tv {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }

        .device-icon.unknown {
            background: rgba(100, 116, 139, 0.15);
            color: #64748b;
        }

        .device-info {
            flex: 1;
        }

        .device-name {
            font-weight: 500;
            margin-bottom: 2px;
        }

        .device-mac {
            font-size: 0.7rem;
            color: var(--gray);
            font-family: monospace;
        }

        .device-details {
            text-align: right;
        }

        .device-ip {
            font-size: 0.8rem;
            font-family: monospace;
        }

        .device-signal {
            font-size: 0.7rem;
            color: var(--gray);
            margin-top: 2px;
        }

        .signal-bars {
            display: inline-flex;
            gap: 2px;
            margin-right: 4px;
        }

        .signal-bar {
            width: 3px;
            background: var(--gray);
            border-radius: 1px;
        }

        .signal-bar.active {
            background: var(--success);
        }

        .device-count-badge {
            background: rgba(99, 102, 241, 0.15);
            color: #818cf8;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .loading-placeholder {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 8px;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.5;
            }
        }

        .empty-message {
            text-align: center;
            padding: 2rem;
            color: var(--gray);
        }

        .empty-message i {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            display: block;
        }

        @media(max-width:768px) {
            .grid-3 {
                grid-template-columns: 1fr;
            }

            .card[style*="grid-column:span 2"] {
                grid-column: auto !important;
            }
        }
    </style>
</head>

<body>
    <header class="portal-header">
        <div class="logo"><i class="fas fa-user-circle"></i> Customer Portal</div>
        <div class="user-menu">
            <span class="user-name" id="customerName">Loading...</span>
            <button class="logout-btn" onclick="logout()" title="Logout">
                <i class="fas fa-sign-out-alt"></i>
            </button>
        </div>
    </header>

    <div class="portal-container">
        <div class="welcome-card">
            <h1 class="welcome-title">Welcome back, <span id="welcomeName">Customer</span>! 👋</h1>
            <p class="welcome-subtitle">Manage your internet service and billing information</p>
        </div>

        <div class="grid-3">
            <!-- Connection Status -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-signal"></i> Connection Status</h3>
                    <span class="status-badge" id="connectionStatus">Loading...</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Device</span>
                    <span class="info-value" id="deviceModel">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Serial Number</span>
                    <span class="info-value" id="deviceSerial">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">IP Address</span>
                    <span class="info-value" id="deviceIP">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Last Contact</span>
                    <span class="info-value" id="deviceUptime">-</span>
                </div>
            </div>

            <!-- Current Package -->
            <div class="card package-card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-box"></i> Your Package</h3>
                </div>
                <div class="package-name" id="packageName">-</div>
                <div class="package-speed" id="packageSpeed">-</div>
                <div class="package-price" id="packagePrice">-</div>
                <button class="btn btn-secondary" style="margin-top:1rem;width:100%;"
                    onclick="showToast('Please contact support to upgrade your package')">
                    <i class="fas fa-arrow-up"></i> Upgrade Package
                </button>
            </div>

            <!-- Account Balance -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-wallet"></i> Account</h3>
                </div>
                <div class="info-row">
                    <span class="info-label">Status</span>
                    <span class="status-badge" id="accountStatus">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Customer ID</span>
                    <span class="info-value" id="customerId">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Balance</span>
                    <span class="info-value" id="balance">-</span>
                </div>
                <div class="info-row">
                    <span class="info-label">Joined</span>
                    <span class="info-value" id="joinDate">-</span>
                </div>
            </div>
        </div>

        <div class="grid-3" style="margin-top:1.5rem;">
            <!-- WiFi Settings -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-wifi"></i> WiFi Settings</h3>
                </div>

                <!-- SSID Form -->
                <div class="wifi-setting-item" style="margin-bottom:1rem;">
                    <div class="form-group" style="margin-bottom:0.5rem;">
                        <label>SSID (Network Name)</label>
                        <div style="display:flex;gap:0.5rem;">
                            <input type="text" id="ssid" placeholder="Loading..." style="flex:1;">
                            <button type="button" class="btn btn-primary" onclick="saveSSID()" id="ssidBtn"
                                style="white-space:nowrap;">
                                <i class="fas fa-save"></i> Save
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Password Form -->
                <div class="wifi-setting-item">
                    <div class="form-group" style="margin-bottom:0.5rem;">
                        <label>Password</label>
                        <div style="display:flex;gap:0.5rem;">
                            <input type="password" id="wifiPassword" placeholder="Enter new password" style="flex:1;">
                            <button type="button" class="btn btn-primary" onclick="savePassword()" id="passBtn"
                                style="white-space:nowrap;">
                                <i class="fas fa-save"></i> Save
                            </button>
                        </div>
                    </div>
                </div>

                <p style="font-size:0.75rem;color:var(--gray);margin-top:1rem;">
                    <i class="fas fa-info-circle"></i> Changes will apply when your device next contacts the server
                </p>
            </div>

            <!-- Recent Invoices -->
            <div class="card" style="grid-column:span 2;">
                <div class="card-header">
                    <h3 class="card-title"><i class="fas fa-file-invoice"></i> Recent Invoices</h3>
                    <button class="btn btn-secondary" style="padding:6px 12px;font-size:0.75rem;"
                        onclick="loadInvoices()">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>
                <div class="invoice-list" id="invoiceList">
                    <div class="empty-message">
                        <i class="fas fa-spinner fa-spin"></i>
                        Loading invoices...
                    </div>
                </div>
            </div>
        </div>

        <!-- Support Section -->
        <div class="card" style="margin-top:1.5rem;">
            <div class="card-header" style="display:flex;justify-content:space-between;align-items:center;">
                <h3 class="card-title"><i class="fas fa-headset"></i> Need Help?</h3>
                <button class="btn btn-primary" onclick="showTicketModal()" style="padding:8px 16px;">
                    <i class="fas fa-ticket-alt"></i> Submit Ticket
                </button>
            </div>
            <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:1rem;">
                <div
                    style="display:flex;align-items:center;gap:1rem;padding:1rem;background:rgba(0,0,0,0.2);border-radius:10px;">
                    <i class="fas fa-phone" style="font-size:1.5rem;color:var(--primary);"></i>
                    <div>
                        <div style="font-size:0.75rem;color:var(--gray);">Call Support</div>
                        <div style="font-weight:600;">0812-3456-7890</div>
                    </div>
                </div>
                <div
                    style="display:flex;align-items:center;gap:1rem;padding:1rem;background:rgba(0,0,0,0.2);border-radius:10px;">
                    <i class="fab fa-whatsapp" style="font-size:1.5rem;color:#25d366;"></i>
                    <div>
                        <div style="font-size:0.75rem;color:var(--gray);">WhatsApp</div>
                        <div style="font-weight:600;">0812-3456-7890</div>
                    </div>
                </div>
                <div
                    style="display:flex;align-items:center;gap:1rem;padding:1rem;background:rgba(0,0,0,0.2);border-radius:10px;">
                    <i class="fas fa-envelope" style="font-size:1.5rem;color:var(--secondary);"></i>
                    <div>
                        <div style="font-size:0.75rem;color:var(--gray);">Email</div>
                        <div style="font-weight:600;">support@isp.com</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Submit Ticket Modal -->
    <div class="modal-overlay" id="ticketModal"
        style="position:fixed;inset:0;background:rgba(0,0,0,0.7);display:none;align-items:center;justify-content:center;z-index:1000;">
        <div class="modal"
            style="background:var(--dark);border:1px solid var(--border);border-radius:16px;padding:2rem;max-width:500px;width:90%;">
            <h2 style="margin-bottom:1.5rem;display:flex;align-items:center;gap:10px;">
                <i class="fas fa-ticket-alt" style="color:var(--primary);"></i> Submit Support Ticket
            </h2>
            <form id="ticketForm" onsubmit="submitTicket(event)">
                <div class="form-group" style="margin-bottom:1rem;">
                    <label style="display:block;margin-bottom:0.5rem;font-size:0.875rem;color:var(--gray);">Category
                        *</label>
                    <select id="ticketCategory" required
                        style="width:100%;padding:12px;background:rgba(0,0,0,0.2);border:1px solid var(--border);border-radius:10px;color:var(--light);">
                        <option value="connection">Connection Issue</option>
                        <option value="speed">Speed Issue</option>
                        <option value="billing">Billing</option>
                        <option value="hardware">Hardware/Device</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div class="form-group" style="margin-bottom:1rem;">
                    <label style="display:block;margin-bottom:0.5rem;font-size:0.875rem;color:var(--gray);">Subject
                        *</label>
                    <input type="text" id="ticketSubject" required placeholder="Brief description of your issue"
                        style="width:100%;padding:12px;background:rgba(0,0,0,0.2);border:1px solid var(--border);border-radius:10px;color:var(--light);">
                </div>
                <div class="form-group" style="margin-bottom:1.5rem;">
                    <label style="display:block;margin-bottom:0.5rem;font-size:0.875rem;color:var(--gray);">Description
                        *</label>
                    <textarea id="ticketDescription" required placeholder="Please describe your issue in detail..."
                        style="width:100%;padding:12px;background:rgba(0,0,0,0.2);border:1px solid var(--border);border-radius:10px;color:var(--light);min-height:120px;resize:vertical;"></textarea>
                </div>
                <div style="display:flex;gap:0.75rem;justify-content:flex-end;">
                    <button type="button" class="btn btn-secondary" onclick="closeTicketModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-paper-plane"></i> Submit</button>
                </div>
            </form>
        </div>
    </div>


    <div class="toast" id="toast">
        <i class="fas fa-check-circle"></i>
        <span id="toastMessage">Success!</span>
    </div>

    <script>
        let customerData = null;
        let deviceData = null;
        let packageData = null;

        async function init() {
            // Check authentication
            const token = localStorage.getItem('customerToken');
            if (!token) {
                window.location.href = '/portal/login';
                return;
            }

            await loadDashboard();
            await loadInvoices();
        }

        async function loadDashboard() {
            try {
                const token = localStorage.getItem('customerToken');
                const response = await fetch('/api/portal/dashboard', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    if (response.status === 401) {
                        logout();
                        return;
                    }
                    throw new Error('Failed to load dashboard');
                }

                const data = await response.json();
                customerData = data.customer;
                deviceData = data.device;
                packageData = data.package;

                renderDashboard();
            } catch (error) {
                console.error('Error loading dashboard:', error);
                showToast('Failed to load dashboard data', 'error');
            }
        }

        function renderDashboard() {
            if (!customerData) return;

            // Customer info
            const firstName = customerData.name ? customerData.name.split(' ')[0] : 'Customer';
            document.getElementById('customerName').textContent = customerData.name || 'Customer';
            document.getElementById('welcomeName').textContent = firstName;
            document.getElementById('customerId').textContent = customerData.customerCode || '-';
            document.getElementById('balance').textContent = formatCurrency(customerData.balance || 0);
            document.getElementById('joinDate').textContent = customerData.joinDate ?
                new Date(customerData.joinDate).toLocaleDateString('id-ID', { year: 'numeric', month: 'short', day: 'numeric' }) : '-';

            // Account status
            const statusEl = document.getElementById('accountStatus');
            statusEl.textContent = capitalize(customerData.status || 'active');
            statusEl.className = 'status-badge ' + (customerData.status || 'active');

            // Package info
            if (packageData) {
                document.getElementById('packageName').textContent = packageData.name || '-';
                document.getElementById('packageSpeed').textContent = packageData.downloadSpeed ?
                    `${packageData.downloadSpeed} Mbps` : '-';
                document.getElementById('packagePrice').textContent = packageData.price ?
                    `${formatCurrency(packageData.price)}/month` : '-';
            }

            // Device info
            if (deviceData) {
                document.getElementById('deviceModel').textContent = deviceData.model || 'Unknown Device';
                document.getElementById('deviceSerial').textContent = deviceData.serialNumber || '-';
                document.getElementById('deviceIP').textContent = deviceData.ipAddress || '-';

                const statusBadge = document.getElementById('connectionStatus');
                const isOnline = deviceData.status === 'online';
                statusBadge.textContent = isOnline ? 'Online' : 'Offline';
                statusBadge.className = 'status-badge ' + (isOnline ? 'online' : 'offline');

                if (deviceData.lastContact) {
                    const lastContact = new Date(deviceData.lastContact);
                    document.getElementById('deviceUptime').textContent = formatTimeAgo(lastContact);
                }

                // Load current WiFi SSID if available
                if (deviceData.wifi && deviceData.wifi.ssid) {
                    document.getElementById('ssid').value = deviceData.wifi.ssid;
                }
            } else {
                document.getElementById('connectionStatus').textContent = 'No Device';
                document.getElementById('connectionStatus').className = 'status-badge suspended';
            }
        }

        async function loadInvoices() {
            try {
                const token = localStorage.getItem('customerToken');
                const response = await fetch('/api/portal/invoices', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) throw new Error('Failed to load invoices');

                const data = await response.json();
                renderInvoices(data.invoices || []);
            } catch (error) {
                console.error('Error loading invoices:', error);
                document.getElementById('invoiceList').innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-exclamation-circle"></i>
                        Failed to load invoices
                    </div>`;
            }
        }

        function renderInvoices(invoices) {
            const container = document.getElementById('invoiceList');

            if (!invoices || invoices.length === 0) {
                container.innerHTML = `
                    <div class="empty-message">
                        <i class="fas fa-file-invoice"></i>
                        No invoices yet
                    </div>`;
                return;
            }

            container.innerHTML = invoices.map(invoice => {
                const statusClass = invoice.status === 'paid' ? 'paid' :
                    invoice.status === 'pending' ? 'pending' :
                        invoice.status === 'overdue' ? 'overdue' : '';
                const period = invoice.periodStart ?
                    new Date(invoice.periodStart).toLocaleDateString('id-ID', { month: 'short', year: 'numeric' }) : '-';

                return `
                    <div class="invoice-item">
                        <div>
                            <div class="invoice-no">${invoice.invoiceNo || '-'}</div>
                            <div class="invoice-period">${period}</div>
                        </div>
                        <div style="text-align:right;">
                            <div class="invoice-amount">${formatCurrency(invoice.totalAmount || 0)}</div>
                            <span class="status-badge ${statusClass}">${capitalize(invoice.status || 'pending')}</span>
                        </div>
                    </div>
                `;
            }).join('');
        }

        async function saveSSID() {
            const ssid = document.getElementById('ssid').value.trim();
            if (!ssid) {
                showToast('SSID cannot be empty!', 'error');
                return;
            }

            const btn = document.getElementById('ssidBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

            try {
                const token = localStorage.getItem('customerToken');
                const response = await fetch('/api/portal/wifi/ssid', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ ssid })
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || 'Failed to update SSID');
                }

                showToast('SSID update task created! Changes will apply soon.');
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-save"></i> Save';
            }
        }

        async function savePassword() {
            const password = document.getElementById('wifiPassword').value.trim();
            if (!password) {
                showToast('Please enter a new password!', 'error');
                return;
            }
            if (password.length < 8) {
                showToast('Password must be at least 8 characters!', 'error');
                return;
            }

            const btn = document.getElementById('passBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

            try {
                const token = localStorage.getItem('customerToken');
                const response = await fetch('/api/portal/wifi/password', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ password })
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || 'Failed to update password');
                }

                showToast('WiFi password update task created! Changes will apply soon.');
                document.getElementById('wifiPassword').value = '';
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-save"></i> Save';
            }
        }

        function formatCurrency(amount) {
            return 'Rp ' + amount.toLocaleString('id-ID');
        }

        function capitalize(str) {
            if (!str) return '';
            return str.charAt(0).toUpperCase() + str.slice(1);
        }

        function formatTimeAgo(date) {
            const now = new Date();
            const diff = now - date;
            const minutes = Math.floor(diff / 60000);
            const hours = Math.floor(diff / 3600000);
            const days = Math.floor(diff / 86400000);

            if (minutes < 1) return 'Just now';
            if (minutes < 60) return `${minutes}m ago`;
            if (hours < 24) return `${hours}h ago`;
            return `${days}d ago`;
        }

        function showToast(message, type = 'success') {
            const toast = document.getElementById('toast');
            const icon = toast.querySelector('i');
            document.getElementById('toastMessage').textContent = message;

            toast.classList.remove('error');
            icon.className = 'fas fa-check-circle';

            if (type === 'error') {
                toast.classList.add('error');
                icon.className = 'fas fa-exclamation-circle';
            }

            toast.classList.add('show');
            setTimeout(() => toast.classList.remove('show'), 3000);
        }

        function logout() {
            localStorage.removeItem('customerToken');
            localStorage.removeItem('customerId');
            localStorage.removeItem('customerName');
            window.location.href = '/portal/login';
        }

        function showTicketModal() {
            document.getElementById('ticketForm').reset();
            document.getElementById('ticketModal').style.display = 'flex';
        }

        function closeTicketModal() {
            document.getElementById('ticketModal').style.display = 'none';
        }

        async function submitTicket(e) {
            e.preventDefault();

            const data = {
                customerId: parseInt(localStorage.getItem('customerId')),
                category: document.getElementById('ticketCategory').value,
                subject: document.getElementById('ticketSubject').value,
                description: document.getElementById('ticketDescription').value,
                priority: 'medium',
                status: 'open'
            };

            try {
                const token = localStorage.getItem('customerToken');
                const response = await fetch('/api/portal/tickets', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    showToast('Ticket submitted successfully! We will contact you soon.');
                    closeTicketModal();
                } else {
                    const error = await response.json();
                    showToast(error.error || 'Failed to submit ticket', 'error');
                }
            } catch (error) {
                showToast('Connection error', 'error');
            }
        }

        // Initialize
        init();
    </script>
</body>

</html>