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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Enhanced Twilio Phone Lookup Dashboard</title>

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com" defer></script>

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">

    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <!-- Axios CDN -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <!-- Chart.js CDN -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        body {
            font-family: 'Roboto', sans-serif;
        }

        .sidebar {
            width: 240px;
            transition: width 0.3s ease;
            background-color: #1E293B;
            height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            padding: 20px;
            color: white;
            overflow: hidden;
        }

        .sidebar.collapsed {
            width: 80px;
        }

        .sidebar h2 {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 2rem;
            transition: opacity 0.3s ease;
        }

        .sidebar.collapsed h2 {
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .sidebar ul {
            list-style-type: none;
            padding: 0;
        }

        .sidebar li {
            margin-bottom: 1.5rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .sidebar a {
            display: flex;
            align-items: center;
            color: white;
            text-decoration: none;
            font-size: 1.1rem;
            font-weight: 500;
        }

        .sidebar i {
            margin-right: 1rem;
            font-size: 1.2rem;
        }

        .nav-item {
            transition: background-color 0.3s ease;
            padding: 0.8rem;
            border-radius: 8px;
        }

        .nav-item:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .sidebar.collapsed a {
            justify-content: center;
        }

        .sidebar.collapsed i {
            margin-right: 0;
        }

        .sidebar.collapsed li span {
            display: none;
        }

        .collapse-btn {
            position: absolute;
            bottom: 20px;
            left: 20px;
            color: white;
            cursor: pointer;
        }

        .content-area {
            margin-left: 240px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }

        .sidebar.collapsed~.content-area {
            margin-left: 80px;
        }

        .loading-spinner {
            display: none;
            text-align: center;
            margin: 20px auto;
        }

        .page {
            display: none;
        }

        .page.active {
            display: block;
        }

        .error-message {
            color: red;
            font-size: 0.9rem;
        }

        button:disabled {
            background-color: gray;
            cursor: not-allowed;
        }

        .loading-message {
            text-align: center;
            margin-top: 50px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }

        th,
        td {
            padding: 8px;
            text-align: left;
        }

        /* Progress Bar */
        .progress-bar {
            margin-top: 20px;
            width: 100%;
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }

        .progress {
            height: 100%;
            background-color: #4caf50;
            text-align: center;
            color: white;
            line-height: 20px;
            border-radius: 10px;
            width: 0%;
        }

        /* Dark mode styles */
        .dark-mode {
            background-color: #1a202c;
            color: #e2e8f0;
        }

        .dark-mode .bg-white {
            background-color: #2d3748;
        }

        .dark-mode .text-gray-700 {
            color: #e2e8f0;
        }

        .dark-mode .border-gray-300 {
            border-color: #4a5568;
        }

        .dark-mode .shadow-lg {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2);
        }
    </style>
</head>

<body class="bg-gray-100 text-gray-700">

    <!-- Loading message -->
    <div id="loadingMessage" class="loading-message hidden">
        <p>Loading... Please wait.</p>
    </div>

    <!-- Sidebar and Main Content Area (Dashboard) -->
    <div class="content-area" id="dashboardContainer">
        <!-- Sidebar -->
        <div class="sidebar" role="navigation">
            <h2>Dashboard Menu</h2>
            <ul>
                <li>
                    <a href="#" class="nav-item" onclick="showPage('phone-lookup')" aria-label="Phone Lookup">
                        <i class="fas fa-search"></i>
                        <span class="menu-text">Phone Lookup</span>
                    </a>
                </li>
                <li>
                    <a href="#" class="nav-item" onclick="showPage('reports')" aria-label="Reports">
                        <i class="fas fa-chart-line"></i>
                        <span class="menu-text">Reports</span>
                    </a>
                </li>
                <li>
                    <a href="#" class="nav-item" onclick="showPage('settings')" aria-label="Settings">
                        <i class="fas fa-cog"></i>
                        <span class="menu-text">Settings</span>
                    </a>
                </li>
            </ul>
            <div class="collapse-btn" aria-label="Collapse Sidebar">
                <i class="fas fa-chevron-left" onclick="toggleSidebar()" aria-hidden="true"></i>
            </div>
        </div>

        <!-- Phone Lookup Page -->
        <div id="phone-lookup" class="page active" role="main">
            <div class="bg-white shadow-lg rounded-lg p-8">
                <h3 class="text-2xl font-bold text-blue-600 mb-6">Phone Lookup</h3>

                <!-- Phone Lookup Form -->
                <form id="lookupForm" class="flex items-center gap-4" onsubmit="lookupPhoneNumber(event)">
                    <input type="text" id="phoneNumber" class="flex-grow p-3 border border-gray-300 rounded-lg" placeholder="Enter phone number" aria-required="true">
                    <button type="submit" class="bg-blue-600 text-white py-3 px-6 rounded-lg hover:bg-blue-700">Lookup</button>
                </form>
                <div id="phoneError" class="error-message hidden"></div>

                <!-- Bulk Lookup CSV -->
                <div class="mt-8">
                    <label for="csvFile" class="block text-gray-700 mb-2">Upload CSV for Bulk Lookup</label>
                    <input type="file" id="csvFile" accept=".csv" class="border border-gray-300 p-2 rounded-lg">
                    <button onclick="handleBulkUpload()" class="bg-blue-600 text-white py-3 px-6 rounded-lg hover:bg-blue-700 mt-4">Upload and Process CSV</button>
                </div>

                <!-- Progress Bar -->
                <div class="progress-bar hidden" id="progressBarContainer">
                    <div class="progress" id="progressBar"></div>
                </div>

                <!-- Loading Spinner -->
                <div class="loading-spinner mt-4" id="loadingSpinner" aria-hidden="true">
                    <i class="fas fa-spinner fa-spin text-2xl text-blue-600"></i>
                </div>

                <!-- Result Section -->
                <div id="lookupResult" class="result-card bg-gray-50 rounded-lg shadow p-6 mt-6 hidden">
                    <h4 class="text-lg font-bold text-gray-800 mb-4">Lookup Result</h4>
                    <div id="resultContent"></div>
                </div>

                <!-- Lookup History Search -->
                <div class="mt-8">
                    <input type="text" id="historySearch" class="w-1/3 p-3 border border-gray-300 rounded-lg" placeholder="Search Lookup History..." oninput="updateHistoryTable()" aria-label="Search Lookup History">
                </div>

                <!-- Lookup History Table -->
                <table id="lookupHistoryTable" class="min-w-full mt-6 bg-white rounded-lg shadow">
                    <thead class="bg-blue-600 text-white">
                        <tr>
                            <th class="py-2 px-4 text-left">Phone Number</th>
                            <th class="py-2 px-4 text-left">Carrier Name</th>
                            <th class="py-2 px-4 text-left">Line Type</th>
                            <th class="py-2 px-4 text-left">Caller Name</th>
                            <th class="py-2 px-4 text-left">Caller Type</th>
                            <th class="py-2 px-4 text-left">Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Rows will be dynamically added here -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Reports Page -->
        <div id="reports" class="page" role="main">
            <div class="bg-white shadow-lg rounded-lg p-8">
                <h3 class="text-2xl font-bold text-blue-600 mb-6">Reports</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div>
                        <h4 class="text-lg font-semibold mb-4">Line Type Distribution</h4>
                        <canvas id="lineTypeChart"></canvas>
                    </div>
                    <div>
                        <h4 class="text-lg font-semibold mb-4">Caller Type Distribution</h4>
                        <canvas id="callerTypeChart"></canvas>
                    </div>
                </div>
                <div class="mt-8">
                    <h4 class="text-lg font-semibold mb-4">Lookup History Over Time</h4>
                    <canvas id="lookupHistoryChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Settings Page -->
        <div id="settings" class="page" role="main">
            <div class="bg-white shadow-lg rounded-lg p-8">
                <h3 class="text-2xl font-bold text-blue-600 mb-6">Settings</h3>
                <p>Configure your Twilio API keys and settings here:</p>
                <div class="mt-4">
                    <label class="block text-gray-700">Account SID</label>
                    <input type="text" id="accountSID" value="ACxxxx" class="w-full p-3 border border-gray-300 rounded-lg mt-2 shadow-md">
                </div>
                <div class="mt-4">
                    <label class="block text-gray-700">Auth Token</label>
                    <input type="password" id="authToken" value="••••••••" class="w-full p-3 border border-gray-300 rounded-lg mt-2 shadow-md">
                </div>
                <button class="btn bg-blue-600 text-white py-3 px-6 rounded-lg mt-6 hover:bg-blue-700 shadow-lg" onclick="saveSettings()">Save Settings</button>
                
                <div class="mt-8">
                    <h4 class="text-lg font-semibold mb-4">Appearance</h4>
                    <label class="flex items-center">
                        <input type="checkbox" id="darkModeToggle" onchange="toggleDarkMode()" class="mr-2">
                        Dark Mode
                    </label>
                </div>
                
                <div class="mt-8">
                    <h4 class="text-lg font-semibold mb-4">Data Management</h4>
                    <button class="btn bg-red-600 text-white py-2 px-4 rounded-lg hover:bg-red-700 shadow-lg" onclick="clearLookupHistory()">Clear Lookup History</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let lookupHistory = JSON.parse(localStorage.getItem('lookupHistory')) || [];

        async function lookupPhoneNumber(event) {
            event.preventDefault();
            const phoneNumberInput = document.getElementById('phoneNumber');
            const phoneError = document.getElementById('phoneError');
            const phoneNumber = phoneNumberInput.value.trim().replace(/[^\d+]/g, '');
            const fullPhoneNumber = phoneNumber.startsWith('+') ? phoneNumber : '+1' + phoneNumber;

            const accountSID = localStorage.getItem('accountSID');
            const authToken = localStorage.getItem('authToken');

            if (!accountSID || !authToken) {
                alert('Please set your Twilio credentials in the Settings page.');
                return;
            }

            // Check if the phone number is already in the history
            const existingRecord = lookupHistory.find(item => item.phoneNumber === fullPhoneNumber);
            if (existingRecord) {
                displayResult(existingRecord);
                return;
            }

            const phoneNumberPattern = /^\+\d{10,15}$/;
            if (!phoneNumberPattern.test(fullPhoneNumber)) {
                phoneError.textContent = 'Invalid phone number format. Please use a valid number.';
                phoneError.classList.remove('hidden');
                return;
            }
            phoneError.classList.add('hidden');

            const loadingSpinner = document.getElementById('loadingSpinner');
            loadingSpinner.style.display = 'block';

            const twilioUrl = `https://lookups.twilio.com/v2/PhoneNumbers/${fullPhoneNumber}?Fields=caller_name,line_type_intelligence`;

            try {
                const response = await axios.get(twilioUrl, {
                    headers: {
                        'Authorization': 'Basic ' + btoa(`${accountSID}:${authToken}`),
                    }
                });
                loadingSpinner.style.display = 'none';

                const data = response.data;

                const lookupData = {
                    phoneNumber: data.phone_number,
                    carrierName: data.line_type_intelligence?.carrier_name || "Unknown Carrier",
                    lineType: data.line_type_intelligence?.type || "Unknown Line Type",
                    callerName: data.caller_name?.caller_name || "Unknown Caller",
                    callerType: data.caller_name?.caller_type || "Unknown Caller Type",
                    date: new Date().toLocaleString()
                };

                // Add to lookup history
                lookupHistory.push(lookupData);
                localStorage.setItem('lookupHistory', JSON.stringify(lookupHistory));
                updateHistoryTable();
                updateCharts();

                displayResult(lookupData);
            } catch (error) {
                loadingSpinner.style.display = 'none';
                alert(`Failed to fetch: ${error.message}`);
            }
        }

        // Update Lookup History Table
        function updateHistoryTable() {
            const historySearch = document.getElementById('historySearch').value.toLowerCase();
            const filteredHistory = lookupHistory.filter(item =>
                item.phoneNumber.includes(historySearch) ||
                item.carrierName.toLowerCase().includes(historySearch) ||
                item.lineType.toLowerCase().includes(historySearch) ||
                item.callerName.toLowerCase().includes(historySearch) ||
                item.callerType.toLowerCase().includes(historySearch)
            );

            const lookupHistoryTable = document.getElementById('lookupHistoryTable').getElementsByTagName('tbody')[0];
            lookupHistoryTable.innerHTML = '';

            filteredHistory.forEach(item => {
                const row = `
                    <tr class="border-b">
                        <td class="py-2 px-4">${item.phoneNumber}</td>
                        <td class="py-2 px-4">${item.carrierName}</td>
                        <td class="py-2 px-4">${item.lineType}</td>
                        <td class="py-2 px-4">${item.callerName}</td>
                        <td class="py-2 px-4">${item.callerType}</td>
                        <td class="py-2 px-4">${item.date}</td>
                    </tr>
                `;
                lookupHistoryTable.innerHTML += row;
            });
        }

        // Display result in the result section
        function displayResult(data) {
            let resultContent = `
                <p class="text-green-500 font-bold">Lookup Success!</p>
                <p><strong>Phone Number:</strong> ${data.phoneNumber}</p>
                <p><strong>Carrier Name:</strong> ${data.carrierName}</p>
                <p><strong>Line Type:</strong> ${data.lineType}</p>
                <p><strong>Caller Name:</strong> ${data.callerName}</p>
                <p><strong>Caller Type:</strong> ${data.callerType}</p>
            `;
            document.getElementById('resultContent').innerHTML = resultContent;
            document.getElementById('lookupResult').style.display = 'block';
        }

        // Handle Bulk Upload
        async function handleBulkUpload() {
            const fileInput = document.getElementById('csvFile');
            const file = fileInput.files[0];
            if (!file) {
                alert('Please select a CSV file.');
                return;
            }

            if (file.type !== 'text/csv') {
                alert('Invalid file format. Please upload a CSV file.');
                return;
            }

            const reader = new FileReader();
            reader.onload = async function (e) {
                const csvContent = e.target.result;
                const phoneNumbers = parseCSV(csvContent);
                processBulkLookup(phoneNumbers);
            };
            reader.readAsText(file);
        }

        // Parse CSV into an array of phone numbers
        function parseCSV(csvContent) {
            const rows = csvContent.split('\n');
            const phoneNumbers = rows.map(row => row.trim()).filter(row => row.length > 0);
            return phoneNumbers;
        }

        // Process bulk lookup for an array of phone numbers
        async function processBulkLookup(phoneNumbers) {
            const progressBar = document.getElementById('progressBar');
            const progressBarContainer = document.getElementById('progressBarContainer');
            progressBarContainer.classList.remove('hidden');

            const total = phoneNumbers.length;
            let completed = 0;

            const accountSID = localStorage.getItem('accountSID');
            const authToken = localStorage.getItem('authToken');

            if (!accountSID || !authToken) {
                alert('Please set your Twilio credentials in the Settings page.');
                return;
            }

            for (let phoneNumber of phoneNumbers) {
                // Check if the phone number is already in the history
                const existingRecord = lookupHistory.find(item => item.phoneNumber === phoneNumber);
                if (existingRecord) {
                    completed++;
                    updateProgress(completed, total);
                    continue;
                }

                const twilioUrl = `https://lookups.twilio.com/v2/PhoneNumbers/${phoneNumber}?Fields=caller_name,line_type_intelligence`;

                try {
                    const response = await axios.get(twilioUrl, {
                        headers: {
                            'Authorization': 'Basic ' + btoa(`${accountSID}:${authToken}`),
                        }
                    });

                    const data = response.data;

                    const lookupData = {
                        phoneNumber: data.phone_number,
                        carrierName: data.line_type_intelligence?.carrier_name || "Unknown Carrier",
                        lineType: data.line_type_intelligence?.type || "Unknown Line Type",
                        callerName: data.caller_name?.caller_name || "Unknown Caller",
                        callerType: data.caller_name?.caller_type || "Unknown Caller Type",
                        date: new Date().toLocaleString()
                    };

                    // Add to lookup history
                    lookupHistory.push(lookupData);
                    localStorage.setItem('lookupHistory', JSON.stringify(lookupHistory));
                    updateHistoryTable();
                } catch (error) {
                    console.error(`Failed to fetch: ${error.message}`);
                }

                completed++;
                updateProgress(completed, total);
            }

            alert('Bulk lookup completed!');
            updateCharts();
        }

        // Update progress bar
        function updateProgress(completed, total) {
            const progressBar = document.getElementById('progressBar');
            const percentage = (completed / total) * 100;
            progressBar.style.width = `${percentage}%`;
            progressBar.textContent = `${Math.round(percentage)}%`;
        }

        // Toggle Sidebar
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const contentArea = document.querySelector('.content-area');
            sidebar.classList.toggle('collapsed');
            contentArea.classList.toggle('collapsed');
        }

        // Show specific page in the dashboard
        function showPage(pageId) {
            const pages = document.querySelectorAll('.page');
            pages.forEach(page => page.classList.remove('active'));
            const activePage = document.getElementById(pageId);
            if (activePage) {
                activePage.classList.add('active');
            } else {
                console.error(`Page with ID "${pageId}" not found.`);
            }

            if (pageId === 'reports') {
                updateCharts();
            }
        }

        // Save settings
        function saveSettings() {
            const accountSID = document.getElementById('accountSID').value;
            const authToken = document.getElementById('authToken').value;

            localStorage.setItem('accountSID', accountSID);
            localStorage.setItem('authToken', authToken);

            alert('Settings saved successfully!');
        }

        // Toggle Dark Mode
        function toggleDarkMode() {
            document.body.classList.toggle('dark-mode');
            localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
        }

        // Clear Lookup History
        function clearLookupHistory() {
            if (confirm('Are you sure you want to clear all lookup history? This action cannot be undone.')) {
                lookupHistory = [];
                localStorage.removeItem('lookupHistory');
                updateHistoryTable();
                updateCharts();
                alert('Lookup history has been cleared.');
            }
        }

        // Update Charts
        function updateCharts() {
            updateLineTypeChart();
            updateCallerTypeChart();
            updateLookupHistoryChart();
        }

        function updateLineTypeChart() {
            const lineTypes = lookupHistory.map(item => item.lineType);
            const lineTypeCounts = lineTypes.reduce((acc, type) => {
                acc[type] = (acc[type] || 0) + 1;
                return acc;
            }, {});

            const ctx = document.getElementById('lineTypeChart').getContext('2d');
            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: Object.keys(lineTypeCounts),
                    datasets: [{
                        data: Object.values(lineTypeCounts),
                        backgroundColor: [
                            '#FF6384',
                            '#36A2EB',
                            '#FFCE56',
                            '#4BC0C0',
                            '#9966FF'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    title: {
                        display: true,
                        text: 'Line Type Distribution'
                    }
                }
            });
        }

        function updateCallerTypeChart() {
            const callerTypes = lookupHistory.map(item => item.callerType);
            const callerTypeCounts = callerTypes.reduce((acc, type) => {
                acc[type] = (acc[type] || 0) + 1;
                return acc;
            }, {});

            const ctx = document.getElementById('callerTypeChart').getContext('2d');
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: Object.keys(callerTypeCounts),
                    datasets: [{
                        data: Object.values(callerTypeCounts),
                        backgroundColor: [
                            '#FF6384',
                            '#36A2EB',
                            '#FFCE56',
                            '#4BC0C0',
                            '#9966FF'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    title: {
                        display: true,
                        text: 'Caller Type Distribution'
                    }
                }
            });
        }

        function updateLookupHistoryChart() {
            const dates = lookupHistory.map(item => new Date(item.date).toLocaleDateString());
            const dateCounts = dates.reduce((acc, date) => {
                acc[date] = (acc[date] || 0) + 1;
                return acc;
            }, {});

            const ctx = document.getElementById('lookupHistoryChart').getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: Object.keys(dateCounts),
                    datasets: [{
                        label: 'Number of Lookups',
                        data: Object.values(dateCounts),
                        borderColor: '#4BC0C0',
                        fill: false
                    }]
                },
                options: {
                    responsive: true,
                    title: {
                        display: true,
                        text: 'Lookup History Over Time'
                    },
                    scales: {
                        xAxes: [{
                            type: 'time',
                            time: {
                                unit: 'day'
                            }
                        }],
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }

        // Initialize the dashboard on page load
        window.onload = () => {
            console.log("Window loaded, initializing dashboard...");
            document.getElementById('loadingMessage').classList.add('hidden');
            document.getElementById('dashboardContainer').classList.remove('hidden');

            // Load saved settings
            const accountSID = localStorage.getItem('accountSID') || 'ACxxxx';
            const authToken = localStorage.getItem('authToken') || '••••••••';
            document.getElementById('accountSID').value = accountSID;
            document.getElementById('authToken').value = authToken;

            // Load dark mode preference
            const darkMode = localStorage.getItem('darkMode') === 'true';
            document.getElementById('darkModeToggle').checked = darkMode;
            if (darkMode) {
                document.body.classList.add('dark-mode');
            }

            // Update history table and charts
            updateHistoryTable();
            updateCharts();
        };
    </script>

</body>

</html>