<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Worksheets - MySQL to Sheets Sync</title>
    <style>
        :root {
            --primary: #2563eb;
            --primary-hover: #1d4ed8;
            --success: #16a34a;
            --error: #dc2626;
            --warning: #ca8a04;
            --bg: #f8fafc;
            --card-bg: #ffffff;
            --border: #e2e8f0;
            --text: #1e293b;
            --text-muted: #64748b;
        }

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

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            padding: 0;
        }

        nav {
            background: #f8f9fa;
            padding: 0.75rem 2rem;
            border-bottom: 1px solid var(--border);
        }

        nav .nav-links {
            display: flex;
            gap: 1.5rem;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
        }

        nav a {
            text-decoration: none;
            font-size: 0.875rem;
            font-weight: 500;
            transition: color 0.15s ease;
        }

        nav a.active { color: var(--primary); }
        nav a:not(.active) { color: var(--text-muted); }
        nav a:hover { color: var(--primary); }

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

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

        h1 { font-size: 1.5rem; font-weight: 600; }
        .version { color: var(--text-muted); font-size: 0.875rem; }

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

        .card h2 { font-size: 1.125rem; font-weight: 600; margin-bottom: 1rem; }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--card-bg);
            color: var(--text);
            text-decoration: none;
        }

        .btn:hover { background: var(--bg); }
        .btn-primary { background: var(--primary); color: white; border-color: var(--primary); }
        .btn-primary:hover { background: var(--primary-hover); }
        .btn-danger { background: var(--error); color: white; border-color: var(--error); }
        .btn-danger:hover { background: #b91c1c; }
        .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.75rem; }

        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 0.75rem 1rem; text-align: left; border-bottom: 1px solid var(--border); }
        th { font-weight: 500; color: var(--text-muted); font-size: 0.75rem; text-transform: uppercase; }
        tr:hover { background: var(--bg); }

        .badge {
            display: inline-flex;
            padding: 0.25rem 0.5rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .badge-info { background: #dbeafe; color: #1e40af; }
        .badge-muted { background: #f1f5f9; color: #64748b; }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .modal.active { display: flex; }

        .modal-content {
            background: var(--card-bg);
            border-radius: 0.5rem;
            padding: 1.5rem;
            width: 100%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
        }

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

        .modal-header h3 { font-size: 1.125rem; font-weight: 600; }
        .modal-close { cursor: pointer; font-size: 1.5rem; color: var(--text-muted); }

        .form-group { margin-bottom: 1rem; }
        label { display: block; font-size: 0.875rem; font-weight: 500; margin-bottom: 0.25rem; }

        input[type="text"],
        input[type="number"] {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid var(--border);
            border-radius: 0.375rem;
            font-size: 0.875rem;
            font-family: inherit;
        }

        input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .form-row {
            display: flex;
            gap: 1rem;
        }

        .form-row .form-group { flex: 1; }

        .form-actions {
            display: flex;
            gap: 0.5rem;
            justify-content: flex-end;
            margin-top: 1.5rem;
        }

        .empty-state {
            text-align: center;
            padding: 3rem;
            color: var(--text-muted);
        }

        .alert {
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            margin-bottom: 1rem;
        }

        .alert-error { background: #fee2e2; border: 1px solid #fecaca; color: var(--error); }
        .alert-success { background: #dcfce7; border: 1px solid #bbf7d0; color: var(--success); }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            gap: 0.5rem;
        }

        .toolbar-actions {
            display: flex;
            gap: 0.5rem;
        }

        .spreadsheet-info {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
            color: var(--text-muted);
            margin-bottom: 1rem;
            padding: 0.75rem;
            background: var(--bg);
            border-radius: 0.375rem;
        }

        .spreadsheet-info strong {
            color: var(--text);
        }

        .loading {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid #e2e8f0;
            border-top-color: var(--primary);
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .hint {
            font-size: 0.75rem;
            color: var(--text-muted);
            margin-top: 0.25rem;
        }

        .gid-badge {
            font-family: monospace;
            font-size: 0.75rem;
            background: #f1f5f9;
            padding: 0.125rem 0.375rem;
            border-radius: 0.25rem;
        }
    </style>
</head>
<body>
    <nav>
        <div class="nav-links">
            <a href="/">Dashboard</a>
            <a href="/configs">Configs</a>
            <a href="/schedules">Schedules</a>
            <a href="/users">Users</a>
            <a href="/webhooks">Webhooks</a>
            <a href="/favorites">Favorites</a>
            <a href="/worksheets" class="active">Worksheets</a>
            <a href="/health">Health</a>
            <a href="/errors">Errors</a>
            <a href="/setup">Setup</a>
        </div>
    </nav>

    <div class="main-content">
        <div class="container">
            <header>
                <div>
                    <h1>Worksheets</h1>
                    <span class="version">v{{ version }}</span>
                </div>
            </header>

            <div id="alertContainer"></div>

            <div class="card">
                <div class="spreadsheet-info" id="spreadsheetInfo">
                    <span class="loading"></span> Loading spreadsheet info...
                </div>

                <div class="toolbar">
                    <h2>Worksheet Tabs (<span id="worksheetCount">0</span>)</h2>
                    <div class="toolbar-actions">
                        <button class="btn" onclick="loadWorksheets()">Refresh</button>
                        <button class="btn btn-primary" onclick="openCreateModal()">Create Worksheet</button>
                    </div>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>GID</th>
                            <th>Rows</th>
                            <th>Columns</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="worksheetList">
                        <tr>
                            <td colspan="5" class="empty-state">
                                <span class="loading"></span> Loading worksheets...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Create Worksheet Modal -->
    <div class="modal" id="createModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Create New Worksheet</h3>
                <span class="modal-close" onclick="closeModal('createModal')">&times;</span>
            </div>
            <form id="createForm" onsubmit="createWorksheet(event)">
                <div class="form-group">
                    <label for="worksheetTitle">Worksheet Name</label>
                    <input type="text" id="worksheetTitle" name="title" required
                           placeholder="e.g., Sales Data" maxlength="100">
                    <div class="hint">Must be unique within the spreadsheet</div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="worksheetRows">Rows</label>
                        <input type="number" id="worksheetRows" name="rows"
                               value="{{ default_rows }}" min="1" max="10000000">
                        <div class="hint">1 - 10,000,000</div>
                    </div>
                    <div class="form-group">
                        <label for="worksheetCols">Columns</label>
                        <input type="number" id="worksheetCols" name="cols"
                               value="{{ default_cols }}" min="1" max="18278">
                        <div class="hint">1 - 18,278 (A-ZZZ)</div>
                    </div>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn" onclick="closeModal('createModal')">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="createBtn">Create</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const configuredSheetId = "{{ sheet_id or '' }}";
        let currentSpreadsheet = null;

        function showAlert(message, type = 'success') {
            const container = document.getElementById('alertContainer');
            container.innerHTML = `<div class="alert alert-${type}">${message}</div>`;
            setTimeout(() => container.innerHTML = '', 5000);
        }

        function closeModal(id) {
            document.getElementById(id).classList.remove('active');
        }

        function openCreateModal() {
            document.getElementById('createForm').reset();
            document.getElementById('worksheetRows').value = {{ default_rows }};
            document.getElementById('worksheetCols').value = {{ default_cols }};
            document.getElementById('createModal').classList.add('active');
        }

        async function loadWorksheets() {
            const tbody = document.getElementById('worksheetList');
            const countSpan = document.getElementById('worksheetCount');
            const infoDiv = document.getElementById('spreadsheetInfo');

            tbody.innerHTML = '<tr><td colspan="5" class="empty-state"><span class="loading"></span> Loading worksheets...</td></tr>';
            infoDiv.innerHTML = '<span class="loading"></span> Loading spreadsheet info...';

            try {
                const response = await fetch('/api/worksheets');
                const data = await response.json();

                if (data.success) {
                    currentSpreadsheet = {
                        title: data.spreadsheet_title,
                        id: data.spreadsheet_id
                    };

                    // Update spreadsheet info
                    infoDiv.innerHTML = `
                        <strong>Spreadsheet:</strong> ${data.spreadsheet_title}
                        <span class="badge badge-muted" style="margin-left: 0.5rem;">${data.spreadsheet_id}</span>
                    `;

                    countSpan.textContent = data.worksheets.length;

                    if (data.worksheets.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="5" class="empty-state">No worksheets found.</td></tr>';
                        return;
                    }

                    tbody.innerHTML = data.worksheets.map(ws => `
                        <tr>
                            <td><strong>${escapeHtml(ws.title)}</strong></td>
                            <td><span class="gid-badge">${ws.gid}</span></td>
                            <td>${ws.rows.toLocaleString()}</td>
                            <td>${ws.cols}</td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick="deleteWorksheet('${escapeHtml(ws.title)}')">Delete</button>
                            </td>
                        </tr>
                    `).join('');
                } else {
                    infoDiv.innerHTML = `<span style="color: var(--error);">Error: ${data.message}</span>`;
                    tbody.innerHTML = `<tr><td colspan="5" class="empty-state" style="color: var(--error);">${data.message}</td></tr>`;
                }
            } catch (error) {
                infoDiv.innerHTML = `<span style="color: var(--error);">Failed to connect</span>`;
                tbody.innerHTML = `<tr><td colspan="5" class="empty-state" style="color: var(--error);">Failed to load worksheets: ${error.message}</td></tr>`;
            }
        }

        async function createWorksheet(e) {
            e.preventDefault();
            const btn = document.getElementById('createBtn');
            const originalText = btn.textContent;
            btn.disabled = true;
            btn.innerHTML = '<span class="loading"></span> Creating...';

            const title = document.getElementById('worksheetTitle').value.trim();
            const rows = parseInt(document.getElementById('worksheetRows').value);
            const cols = parseInt(document.getElementById('worksheetCols').value);

            try {
                const response = await fetch('/api/worksheets', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ title, rows, cols })
                });

                const data = await response.json();

                if (data.success) {
                    showAlert(`Worksheet "${title}" created successfully!`);
                    closeModal('createModal');
                    loadWorksheets();
                } else {
                    showAlert(data.message || 'Failed to create worksheet', 'error');
                }
            } catch (error) {
                showAlert('Failed to create worksheet: ' + error.message, 'error');
            } finally {
                btn.disabled = false;
                btn.textContent = originalText;
            }
        }

        async function deleteWorksheet(title) {
            if (!confirm(`Are you sure you want to delete the worksheet "${title}"?\n\nThis action cannot be undone.`)) {
                return;
            }

            try {
                const response = await fetch(`/api/worksheets/${encodeURIComponent(title)}`, {
                    method: 'DELETE'
                });

                const data = await response.json();

                if (data.success) {
                    showAlert(`Worksheet "${title}" deleted successfully!`);
                    loadWorksheets();
                } else {
                    showAlert(data.message || 'Failed to delete worksheet', 'error');
                }
            } catch (error) {
                showAlert('Failed to delete worksheet: ' + error.message, 'error');
            }
        }

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

        // Load worksheets on page load
        loadWorksheets();
    </script>
</body>
</html>
