/**
 * Bristol Bus Service - LIVE DATA
 * Fetches real-time bus info from BODS via bristol_bus_api.php
 * 
 * Version: 4.0 - Live API Integration
 */

const BUS_API_URL = 'bristol_bus_api.php';

// Stop name mappings
const STOP_MAPPINGS = {
    'bus station': 'bus_station',
    'temple meads': 'temple_meads',
    'the centre': 'the_centre',
    'center': 'the_centre',
    'centre': 'the_centre',
    'broadmead': 'broadmead',
    'cabot circus': 'cabot_circus',
    'cabot': 'cabot_circus',
    'clifton': 'clifton',
    'clifton triangle': 'clifton',
    'uwe': 'uwe',
    'university': 'uwe',
    'frenchay': 'uwe',
    'southmead': 'southmead_hospital',
    'southmead hospital': 'southmead_hospital',
    'hospital': 'southmead_hospital',
    'cribbs': 'cribbs_causeway',
    'cribbs causeway': 'cribbs_causeway',
    'the mall': 'cribbs_causeway',
    'mall': 'cribbs_causeway',
    'gloucester road': 'gloucester_road',
    'glos road': 'gloucester_road',
    'bedminster': 'bedminster',
    'fishponds': 'fishponds',
    'hengrove': 'hengrove',
    'kingswood': 'kingswood',
    'yate': 'yate',
    'airport': 'airport',
    'bristol airport': 'airport'
};

// ============================================
// MAIN PROCESSING FUNCTION
// ============================================
async function processBusRequest(message) {
    const lowerMessage = (message || '').toLowerCase().trim();
    
    // Check for bus keywords
    const busKeywords = ['bus', 'buses', 'next bus', 'bus time', 'bus to', 'bus from', 'what bus', 'which bus', 'catch bus', 'get bus', 'take bus', 'route'];
    const hasBusKeyword = busKeywords.some(kw => lowerMessage.includes(kw));
    
    if (!hasBusKeyword) return null;
    
    // Extract route number (e.g., "72", "X39", "M1", "A1")
    const routeMatch = lowerMessage.match(/\b(?:bus\s+|route\s+)?(\d{1,3}[a-z]?|x\d{1,2}|m\d|a1)\b/i);
    const routeNumber = routeMatch ? routeMatch[1] : null;
    
    // Extract stop name
    let stopKey = null;
    for (const [phrase, key] of Object.entries(STOP_MAPPINGS)) {
        if (lowerMessage.includes(phrase)) {
            stopKey = key;
            break;
        }
    }
    
    // CASE 1: User asks about specific route ("when's the next 72?")
    if (routeNumber) {
        return await fetchRouteInfo(routeNumber);
    }
    
    // CASE 2: User asks about a stop ("bus times at temple meads")
    if (stopKey) {
        return await fetchStopArrivals(stopKey);
    }
    
    // CASE 3: Generic question - don't handle, let AI respond
    return null;
}

// ============================================
// FETCH LIVE ROUTE INFO
// ============================================
async function fetchRouteInfo(routeNumber) {
    try {
        const response = await fetch(`${BUS_API_URL}?action=route&number=${encodeURIComponent(routeNumber)}`);
        const data = await response.json();
        
        if (!data.success) {
            return null; // Let AI handle unknown routes
        }
        
        return formatRouteCard(data);
        
    } catch (error) {
        console.error('[BUS] Route fetch error:', error);
        return null;
    }
}

// ============================================
// FETCH LIVE STOP ARRIVALS
// ============================================
async function fetchStopArrivals(stopKey) {
    try {
        const response = await fetch(`${BUS_API_URL}?action=arrivals&stop=${encodeURIComponent(stopKey)}`);
        const data = await response.json();
        
        if (!data.success) {
            return null;
        }
        
        return formatArrivalsCard(data);
        
    } catch (error) {
        console.error('[BUS] Arrivals fetch error:', error);
        return null;
    }
}

// ============================================
// FORMAT: Route Info Card
// ============================================
function formatRouteCard(data) {
    const route = data.route;
    const arrivals = data.next_arrivals || [];
    const isLive = data.live;
    
    // Determine route type colors
    let bgColor = '#3B82F6'; // Blue default
    let typeLabel = '🚌 Regular';
    
    if (route.type === 'metrobus') { bgColor = '#DC2626'; typeLabel = '🚍 Metrobus'; }
    else if (route.type === 'express') { bgColor = '#8B5CF6'; typeLabel = '⚡ Express'; }
    else if (route.type === 'airport') { bgColor = '#F59E0B'; typeLabel = '✈️ Airport'; }
    else if (route.type === 'frequent') { typeLabel = '🚌 Frequent'; }
    
    return `
<div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border: 2px solid ${bgColor}; border-radius: 16px; overflow: hidden; margin: 10px 0;">
    
    <!-- Header -->
    <div style="background: ${bgColor}; padding: 16px 20px; display: flex; align-items: center; gap: 15px;">
        <div style="background: white; color: ${bgColor}; padding: 12px 18px; border-radius: 12px; font-weight: 800; font-size: 28px;">
            ${route.number}
        </div>
        <div style="flex: 1;">
            <div style="color: white; font-weight: 700; font-size: 17px;">${route.name}</div>
            <div style="color: rgba(255,255,255,0.85); font-size: 13px; margin-top: 3px;">${typeLabel} • Every ${route.frequency}</div>
        </div>
        ${isLive ? '<div style="background: #10B981; color: white; padding: 5px 10px; border-radius: 20px; font-size: 10px; font-weight: 700;">● LIVE</div>' : ''}
    </div>
    
    <!-- Next Buses -->
    <div style="padding: 16px 20px;">
        <div style="color: #9CA3AF; font-size: 11px; font-weight: 600; text-transform: uppercase; margin-bottom: 10px;">Next Departures</div>
        <div style="display: flex; gap: 10px; flex-wrap: wrap;">
            ${arrivals.map(mins => `
                <div style="background: ${mins <= 2 ? '#10B981' : 'rgba(255,255,255,0.1)'}; color: ${mins <= 2 ? 'white' : '#FFD700'}; padding: 10px 18px; border-radius: 10px; font-weight: 700; font-size: 15px;">
                    ${mins <= 1 ? 'Due' : mins + ' min'}
                </div>
            `).join('')}
        </div>
        ${data.live_vehicles > 0 ? `<div style="color: #6EE7B7; font-size: 12px; margin-top: 10px;">🚌 ${data.live_vehicles} buses currently running</div>` : ''}
    </div>
    
    <!-- Service Info -->
    <div style="padding: 0 20px 16px;">
        <div style="background: rgba(255,255,255,0.05); border-radius: 12px; padding: 14px; display: flex; justify-content: space-around;">
            <div style="text-align: center;">
                <div style="color: #9CA3AF; font-size: 11px;">Frequency</div>
                <div style="color: #E5E7EB; font-weight: 600; font-size: 15px;">Every ${route.frequency}</div>
            </div>
            <div style="text-align: center;">
                <div style="color: #9CA3AF; font-size: 11px;">First Bus</div>
                <div style="color: #E5E7EB; font-weight: 600; font-size: 15px;">${route.first_bus}</div>
            </div>
            <div style="text-align: center;">
                <div style="color: #9CA3AF; font-size: 11px;">Last Bus</div>
                <div style="color: #E5E7EB; font-weight: 600; font-size: 15px;">${route.last_bus}</div>
            </div>
        </div>
    </div>
    
    <!-- Links -->
    <div style="padding: 0 20px 16px; display: flex; gap: 10px;">
        <a href="${data.timetable_url}" target="_blank" style="flex: 1; background: rgba(59,130,246,0.15); border: 1px solid #3B82F6; color: #93C5FD; padding: 12px; border-radius: 10px; text-decoration: none; font-size: 14px; font-weight: 600; text-align: center;">
            📋 Timetable
        </a>
        <a href="${data.track_url}" target="_blank" style="flex: 1; background: rgba(16,185,129,0.15); border: 1px solid #10B981; color: #6EE7B7; padding: 12px; border-radius: 10px; text-decoration: none; font-size: 14px; font-weight: 600; text-align: center;">
            🗺️ Track Live
        </a>
    </div>
    
    <!-- Footer -->
    <div style="background: rgba(0,0,0,0.2); padding: 10px 20px; font-size: 11px; color: #6B7280;">
        Updated ${data.updated} • ${isLive ? 'Live from BODS' : 'Demo data'}
    </div>
</div>`;
}

// ============================================
// FORMAT: Stop Arrivals Card
// ============================================
function formatArrivalsCard(data) {
    const stop = data.stop;
    const arrivals = data.arrivals || [];
    const isLive = data.live;
    const isDemo = data.demo;
    
    if (arrivals.length === 0) {
        return `
<div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border: 2px solid #3B82F6; border-radius: 16px; padding: 20px; margin: 10px 0;">
    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 15px;">
        <span style="font-size: 28px;">🚏</span>
        <div style="color: white; font-weight: 700; font-size: 18px;">${stop.name}</div>
    </div>
    <div style="color: #9CA3AF; font-size: 14px;">No buses due at this stop right now.</div>
</div>`;
    }
    
    return `
<div style="background: linear-gradient(135deg, #1a1a2e, #16213e); border: 2px solid #3B82F6; border-radius: 16px; overflow: hidden; margin: 10px 0;">
    
    <!-- Header -->
    <div style="background: linear-gradient(135deg, #3B82F6, #1D4ED8); padding: 16px 20px; display: flex; align-items: center; gap: 12px;">
        <span style="font-size: 28px;">🚏</span>
        <div style="flex: 1;">
            <div style="color: white; font-weight: 700; font-size: 18px;">${stop.name}</div>
            <div style="color: rgba(255,255,255,0.8); font-size: 12px;">Live departures</div>
        </div>
        <div style="background: ${isLive ? '#10B981' : '#F59E0B'}; color: white; padding: 5px 12px; border-radius: 20px; font-size: 11px; font-weight: 700;">
            ${isLive ? '● LIVE' : '● DEMO'}
        </div>
    </div>
    
    <!-- Arrivals List -->
    <div style="padding: 8px 0;">
        ${arrivals.slice(0, 6).map(arr => `
        <div style="display: flex; align-items: center; padding: 14px 20px; border-bottom: 1px solid rgba(255,255,255,0.08);">
            <div style="background: #3B82F6; color: white; padding: 6px 14px; border-radius: 8px; font-weight: 700; font-size: 15px; min-width: 55px; text-align: center;">
                ${arr.route}
            </div>
            <div style="flex: 1; padding: 0 16px;">
                <div style="color: #E5E7EB; font-size: 14px;">${arr.destination}</div>
                ${arr.scheduled ? `<div style="color: #6B7280; font-size: 11px;">Scheduled: ${arr.scheduled}</div>` : ''}
            </div>
            <div style="background: ${arr.minutes <= 2 ? '#10B981' : 'rgba(255,255,255,0.1)'}; color: ${arr.minutes <= 2 ? 'white' : '#FFD700'}; padding: 8px 14px; border-radius: 8px; font-weight: 700; font-size: 14px;">
                ${arr.minutes <= 1 ? 'Due' : arr.minutes + ' min'}
            </div>
        </div>
        `).join('')}
    </div>
    
    <!-- Footer -->
    <div style="background: rgba(0,0,0,0.2); padding: 12px 20px; display: flex; justify-content: space-between; align-items: center;">
        <span style="color: #9CA3AF; font-size: 12px;">Updated ${data.updated}</span>
        <a href="https://www.firstbus.co.uk/bristol-bath-and-west" target="_blank" style="color: #3B82F6; text-decoration: none; font-size: 13px; font-weight: 600;">First Bus App →</a>
    </div>
    
    ${isDemo ? `
    <div style="background: rgba(245, 158, 11, 0.1); padding: 10px 20px; font-size: 12px; color: #FCD34D;">
        ⚠️ Demo data shown. For live times, API key needed - <a href="https://data.bus-data.dft.gov.uk/account/signup/" target="_blank" style="color: #FCD34D; text-decoration: underline;">Get free key</a>
    </div>
    ` : ''}
</div>`;
}

// ============================================
// EXPORT
// ============================================
if (typeof window !== 'undefined') {
    window.processBusRequest = processBusRequest;
}

console.log('🚌 Bristol Bus Service v4.0 - Live API Integration loaded');