<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Walk Score Calculator</title>
    <style>
        /* Basic styling for the Walk Score Calculator */

        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
            margin: 0;
            padding: 0;
        }

        .container {
            max-width: 600px;
            margin: 50px auto;
            padding: 30px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        
        h1 {
            text-align: center;
            color: #333;
        }

        input[type="text"] {
            width: 100%;
            padding: 12px 20px;
            margin: 10px 0;
            box-sizing: border-box;
            border: 2px solid #ccc;
            border-radius: 4px;
        }

        button {
            width: 100%;
            background-color: #28a745;
            color: white;
            padding: 14px 20px;
            margin: 10px 0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background-color: #218838;
        }

        #result {
            margin-top: 20px;
            text-align: center;
            font-size: 18px;
        }

        .error {
            color: #dc3545;
        }

        .loading {
            color: #17a2b8;
        }

        .score {
            font-weight: bold;
            color: #28a745;
        }

        .amenities {
            margin-top: 10px;
            text-align: left;
        }

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

        .amenities li {
            background: #f1f1f1;
            margin: 5px 0;
            padding: 8px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Walk Score Calculator</h1>
        <input type="text" id="address" placeholder="Enter address" size="50" />
        <button id="calculate">Calculate Walk Score</button>
        <div id="result"></div>
    </div>

    <script>
        document.getElementById('calculate').addEventListener('click', () => {
            const address = document.getElementById('address').value.trim();
            const resultDiv = document.getElementById('result');
        
            if (!address) {
                resultDiv.innerHTML = '<p class="error">Please enter a valid address.</p>';
                return;
            }
        
            resultDiv.innerHTML = '<p class="loading">Calculating Walk Score...</p>';
        
            geocodeAddress(address)
                .then(coords => {
                    if (coords) {
                        fetchAmenities(coords.lat, coords.lon)
                            .then(amenities => {
                                const score = calculateWalkScore(amenities);
                                displayResult(score, amenities, coords);
                            })
                            .catch(err => {
                                console.error(err);
                                resultDiv.innerHTML = '<p class="error">Error fetching amenities.</p>';
                            });
                    } else {
                        resultDiv.innerHTML = '<p class="error">Address not found.</p>';
                    }
                })
                .catch(err => {
                    console.error(err);
                    resultDiv.innerHTML = '<p class="error">Error during geocoding.</p>';
                });
        });

        /
         * Geocode the address to get latitude and longitude using Nominatim.
         * @param {string} address - The address to geocode.
         * @returns {Promise<Object|null>} - An object with lat and lon or null if not found.
         */
        async function geocodeAddress(address) {
            const url = https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(address)};
        
            try {
                const response = await fetch(url, {
                    headers: {
                        'Accept-Language': 'en',
                        'User-Agent': 'WalkScoreCalculator/1.0 (your.email@example.com)' // Replace with your contact info
                    }
                });
                const data = await response.json();
        
                if (data && data.length > 0) {
                    return { lat: data[0].lat, lon: data[0].lon };
                } else {
                    return null;
                }
            } catch (error) {
                console.error('Geocoding Error:', error);
                return null;
            }
        }

        /**
         * Fetch nearby amenities using Overpass API.
         * @param {string} lat - Latitude of the location.
         * @param {string} lon - Longitude of the location.
         * @param {number} radius - Search radius in meters.
         * @returns {Promise<Array>} - An array of amenities.
         */
        async function fetchAmenities(lat, lon, radius = 1000) {
            // Define the amenities to search for
            const amenities = [
                'school',
                'park',
                'hospital',
                'supermarket',
                'bank',
                'cafe',
                'restaurant',
                'library',
                'pharmacy',
                'post_office'
            ];
        
            // Construct Overpass QL query using template literals
            const query = <br/> [out:json];<br/> (<br/> node["amenity"~"${amenities.join('|')}"](around:${radius},${lat},${lon});<br/> way["amenity"~"${amenities.join('|')}"](around:${radius},${lat},${lon});<br/> relation["amenity"~"${amenities.join('|')}"](around:${radius},${lat},${lon});<br/> );<br/> out center;<br/> ;
        
            const url = https://overpass-api.de/api/interpreter?data=${encodeURIComponent(query)};
        
            try {
                const response = await fetch(url, {
                    headers: {
                        'User-Agent': 'WalkScoreCalculator/1.0 (your.email@example.com)' // Replace with your contact info
                    }
                });
                const data = await response.json();
                return data.elements;
            } catch (error) {
                console.error('Overpass API Error:', error);
                throw error;
            }
        }

        /
         * Calculate Walk Score based on the number and types of amenities.
         * This is a simplified version and does not reflect the actual Walk Score algorithm.
         * @param {Array} amenities - Array of amenities fetched from Overpass API.
         * @returns {number} - Calculated walk score (0-100).
         */
        function calculateWalkScore(amenities) {
            // Assign weights to different types of amenities
            const weights = {
                'supermarket': 10,
                'cafe': 8,
                'restaurant': 8,
                'bank': 5,
                'pharmacy': 5,
                'post_office': 5,
                'library': 5,
                'school': 10,
                'park': 10,
                'hospital': 15
            };

            let score = 0;

            amenities.forEach(item => {
                const amenityType = item.tags.amenity;
                if (weights[amenityType]) {
                    score += weights[amenityType];
                }
            });

            // Normalize score to be out of 100
            // Assuming maximum possible score in this configuration is 100
            if (score > 100) score = 100;
            if (score < 0) score = 0;

            return score;
        }

        /**
         * Display the Walk Score result along with nearby amenities.
         * @param {number} score - The calculated walk score.
         * @param {Array} amenities - Array of amenities.
         * @param {Object} coords - Coordinates of the address.
         */
        function displayResult(score, amenities, coords) {
            const resultDiv = document.getElementById('result');
            let html = &lt;p&gt;Your Walk Score is: &lt;span class="score"&gt;${score}&lt;/span&gt;/100&lt;/p&gt;;

            // Optionally, add the location
            html += &lt;p&gt;Location: (${coords.lat}, ${coords.lon})&lt;/p&gt;;

            // List nearby amenities
            if (amenities.length > 0) {
                html += &lt;div class="amenities"&gt;&lt;h3&gt;Nearby Amenities:&lt;/h3&gt;&lt;ul&gt;;
                amenities.forEach(item => {
                    const name = item.tags.name || 'Unnamed';
                    const amenity = item.tags.amenity;
                    html += &lt;li&gt;${capitalizeFirstLetter(amenity)}: ${name}&lt;/li&gt;;
                });
                html += &lt;/ul&gt;&lt;/div&gt;;
            } else {
                html += &lt;p&gt;No nearby amenities found within the specified radius.&lt;/p&gt;;
            }

            resultDiv.innerHTML = html;
        }

        /**
         * Capitalize the first letter of a string.
         * @param {string} str - The string to capitalize.
         * @returns {string} - Capitalized string.
         */
        function capitalizeFirstLetter(str) {
            return str.charAt(0).toUpperCase() + str.slice(1);
        }
    </script>
</body>
</html>