write the full code I want the math to be correct of the hour's listen fix it up to be accurate also write the full complete code, just edit the changes: <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spotify Listening Stats</title>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
            background-color: #ffffff;
            color: #37352f;
            line-height: 1.5;
        }
        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 40px 20px;
        }
        .header {
            margin-bottom: 40px;
        }
        .title {
            font-size: 40px;
            font-weight: 700;
            margin-bottom: 10px;
        }
        .subtitle {
            font-size: 16px;
            color: #6b7280;
        }
        .connect-btn, .fetch-btn {
            background-color: #2eaadc;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            margin-top: 20px;
        }
        .stats-container, .now-playing-container {
            background-color: #f7f6f3;
            border-radius: 3px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .stat-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #e5e5e5;
        }
        .stat-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        .stat-label {
            font-weight: 600;
        }
        .loading {
            text-align: center;
            font-style: italic;
            color: #6b7280;
        }
        .date-range {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .date-range input {
            padding: 5px;
            border: 1px solid #e5e5e5;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="title">Spotify Listening Stats</h1>
            <p class="subtitle">Connect your Spotify account to view your listening statistics.</p>
            <button id="connectBtn" class="connect-btn">Connect Spotify</button>
        </div>
        <div id="nowPlayingContainer" class="now-playing-container" style="display: none;">
            <h2>Now Playing</h2>
            <p id="nowPlaying">Not currently playing</p>
        </div>
        <div id="dateRangeContainer" class="date-range" style="display: none;">
            <input type="date" id="startDate">
            <input type="date" id="endDate">
            <button id="fetchBtn" class="fetch-btn">Fetch Stats</button>
        </div>
        <div id="statsContainer" class="stats-container">
            <p class="loading">Connect your Spotify account to view your stats</p>
        </div>
    </div>

    <script>
        // Replace these with your actual Spotify API credentials
        const CLIENT_ID = 'YOUR_CLIENT_ID_HERE';
        const REDIRECT_URI = 'YOUR_REDIRECT_URI_HERE';

        const connectBtn = document.getElementById('connectBtn');
        const statsContainer = document.getElementById('statsContainer');
        const dateRangeContainer = document.getElementById('dateRangeContainer');
        const nowPlayingContainer = document.getElementById('nowPlayingContainer');
        const nowPlayingText = document.getElementById('nowPlaying');
        const startDateInput = document.getElementById('startDate');
        const endDateInput = document.getElementById('endDate');
        const fetchBtn = document.getElementById('fetchBtn');

        let accessToken = null;

        connectBtn.addEventListener('click', () => {
            const authUrl = `https://accounts.spotify.com/authorize?client_id=${CLIENT_ID}&response_type=token&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=user-read-recently-played%20user-read-currently-playing`;
            window.location.href = authUrl;
        });

        fetchBtn.addEventListener('click', () => {
            const startDate = new Date(startDateInput.value);
            const endDate = new Date(endDateInput.value);
            fetchSpotifyData(startDate, endDate);
        });

        window.onload = () => {
            const hash = window.location.hash.substring(1);
            const params = new URLSearchParams(hash);
            accessToken = params.get('access_token');

            if (accessToken) {
                connectBtn.style.display = 'none';
                dateRangeContainer.style.display = 'flex';
                nowPlayingContainer.style.display = 'block';
                
                // Set default date range to last month
                const today = new Date();
                const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                const endOfLastMonth = new Date(today.getFullYear(), today.getMonth(), 0);
                
                startDateInput.value = formatDate(lastMonth);
                endDateInput.value = formatDate(endOfLastMonth);
                
                fetchSpotifyData(lastMonth, endOfLastMonth);
                updateNowPlaying();
                setInterval(updateNowPlaying, 30000); // Update now playing every 30 seconds
            }
        };

        function formatDate(date) {
            return date.toISOString().split('T')[0];
        }

        async function fetchSpotifyData(startDate, endDate) {
            try {
                statsContainer.innerHTML = '<p class="loading">Fetching your data...</p>';

                const response = await fetch(`https://api.spotify.com/v1/me/player/recently-played?limit=50&after=${startDate.getTime()}`, {
                    headers: { 'Authorization': 'Bearer ' + accessToken }
                });
                const data = await response.json();

                const stats = calculateStats(data.items, startDate, endDate);
                displayStats(stats);
            } catch (error) {
                console.error('Error fetching Spotify data:', error);
                statsContainer.innerHTML = '<p class="loading">Error fetching data. Please try again.</p>';
            }
        }

        function calculateStats(items, startDate, endDate) {
            let totalMilliseconds = 0;
            const artistCounts = {};
            const trackCounts = {};

            items.forEach(item => {
                const playedAt = new Date(item.played_at);
                if (playedAt >= startDate && playedAt <= endDate) {
                    totalMilliseconds += item.track.duration_ms;
                    
                    const artistName = item.track.artists[0].name;
                    artistCounts[artistName] = (artistCounts[artistName] || 0) + 1;

                    const trackName = item.track.name;
                    trackCounts[trackName] = (trackCounts[trackName] || 0) + 1;
                }
            });

            const totalHours = totalMilliseconds / (1000 * 60 * 60);
            const topArtist = Object.entries(artistCounts).sort((a, b) => b[1] - a[1])[0];
            const topTrack = Object.entries(trackCounts).sort((a, b) => b[1] - a[1])[0];

            const daysDifference = (endDate - startDate) / (1000 * 60 * 60 * 24) + 1;
            const estimatedTotal = (totalHours / Math.min(daysDifference, items.length)) * daysDifference;

            return {
                estimatedTotal: estimatedTotal.toFixed(1),
                topArtist: topArtist ? topArtist[0] : 'N/A',
                topTrack: topTrack ? topTrack[0] : 'N/A',
                dataSpan: Math.min(daysDifference, items.length)
            };
        }

        function displayStats(stats) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <span class="stat-label">Estimated Listening Hours:</span>
                    <span>${stats.estimatedTotal} hours</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">Top Artist:</span>
                    <span>${stats.topArtist}</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">Top Track:</span>
                    <span>${stats.topTrack}</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">Data based on:</span>
                    <span>Last ${stats.dataSpan} days</span>
                </div>
            `;
        }

        async function updateNowPlaying() {
            try {
                const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', {
                    headers: { 'Authorization': 'Bearer ' + accessToken }
                });
                
                if (response.status === 204) {
                    nowPlayingText.textContent = 'Not currently playing';
                    return;
                }
                
                const data = await response.json();
                if (data.item) {
                    const trackName = data.item.name;
                    const artistName = data.item.artists.map(artist => artist.name).join(', ');
                    nowPlayingText.textContent = `${trackName} by ${artistName}`;
                } else {
                    nowPlayingText.textContent = 'Not currently playing';
                }
            } catch (error) {
                console.error('Error fetching now playing:', error);
                nowPlayingText.textContent = 'Unable to fetch current track';
            }
        }
    </script>
</body>
</html>