async function loadMatch(container, team1, team2) { const storageKey = `match_${team1}_${team2}`; try { const res = await fetch("https://love-weld-nine.vercel.app/api/espn"); const data = await res.json(); if (!data.events?.length) { loadFromStorage("No matches available"); return; } const match = data.events.find( e => e.competitions?.[0]?.competitors?.some(c => c.team?.name === team1) && e.competitions?.[0]?.competitors?.some(c => c.team?.name === team2) ); if (!match) { loadFromStorage("No upcoming or live match found for selected teams"); return; } localStorage.setItem(storageKey, JSON.stringify(match)); displayMatch(match); if (match.status?.type?.state === "in") { setTimeout(() => loadMatch(container, team1, team2), 30000); } } catch (err) { console.error(err); loadFromStorage("❌ Failed to load match data"); } function loadFromStorage(fallbackMsg) { const stored = localStorage.getItem(storageKey); if (stored) { const match = JSON.parse(stored); displayMatch(match, true); } else { container.innerHTML = fallbackMsg; } } function displayMatch(match, fromStorage = false) { const comp = match.competitions[0]; const home = comp.competitors?.find(c => c.homeAway === "home"); const away = comp.competitors?.find(c => c.homeAway === "away"); const homeName = home?.team?.name || "Home"; const awayName = away?.team?.name || "Away"; const kickoff = new Date(match.date).toLocaleString("en-GB", { timeZone: "Europe/Paris", dateStyle: "short", timeStyle: "short" }); const isLive = match.status?.type?.state === "in"; const isComplete = match.status?.type?.state === "post"; const clock = match.status?.displayClock || match.status?.clock || ""; const liveButton = isLive ? '🔴 LIVE' : isComplete ? '✅ FULL TIME' : '⏰ SCHEDULED'; const homeForm = home?.form ?.split("") .map( f => `${f}` ) .join("") || ""; const awayForm = away?.form ?.split("") .map( f => `${f}` ) .join("") || ""; const homeStats = home?.statistics || []; const awayStats = away?.statistics || []; const statsMap = {}; homeStats.forEach(h => { const key = h.name; const homeVal = h.displayValue || h.value || "-"; const awayObj = awayStats.find(a => a.name === key); const awayVal = awayObj?.displayValue || awayObj?.value || "-"; statsMap[key] = { home: homeVal, away: awayVal }; }); awayStats.forEach(a => { if (!statsMap[a.name]) { const homeObj = homeStats.find(h => h.name === a.name); const homeVal = homeObj?.displayValue || homeObj?.value || "-"; const awayVal = a.displayValue || a.value || "-"; statsMap[a.name] = { home: homeVal, away: awayVal }; } }); let statsHtml = ""; Object.entries(statsMap).forEach(([key, val]) => { statsHtml += `
${key}${val.home} - ${val.away}
`; }); const moneyline = comp.odds?.find(o => o.moneyline)?.moneyline || {}; const overUnder = comp.odds?.find(o => o.overUnder)?.overUnder || {}; const attendance = comp.attendance || "TBD"; const venue = comp.venue?.fullName || "TBD"; const venueCapacity = comp.venue?.capacity || "Unknown"; const weather = comp.weather || {}; const broadcast = comp.broadcasts?.map(b => b.names?.join(", "))?.join(" | ") || "TBD"; const tickets = comp.tickets ?.map( t => `${t.summary}` ) .join(" | ") || "Check official website"; const season = match.season?.year + " " + (match.season?.slug?.replace(/-/g, " ") || "Season") || ""; const events = comp.details?.events || []; const eventsHtml = events.length ? events .map( ev => `
${ev.clock || "FT"}${ev.text || ev.description || "Event"}
` ) .join("") : "

No match events available

"; container.innerHTML = `

⚽ ${homeName} vs ${awayName}

${season}
${fromStorage ? '

(cached data)

' : ""}

${isLive || isComplete ? "FINAL" : "VS"} ${ isLive || isComplete ? `
${home?.score || "0"} - ${away?.score || "0"}
` : "" }
${homeName}
${awayName}
${!isLive && !isComplete ? `

📅 ${kickoff}

` : ""}

${liveButton} ${clock ? `- ${clock}` : ""}

🏟️ ${venue}${venueCapacity !== "Unknown" ? ` (${venueCapacity})` : ""}

👥 Attendance: ${attendance.toLocaleString ? attendance.toLocaleString() : attendance}

📺 ${broadcast}

📊 Live Statistics

${statsHtml || "

No live stats available

"}
Home Form${homeForm}
Away Form${awayForm}
Home Record${home?.records?.[0]?.summary || "N/A"}
Away Record${away?.records?.[0]?.summary || "N/A"}

💰 Betting Odds

Home Win

${moneyline.home?.close?.odds || "-"}

Draw

${moneyline.draw?.close?.odds || "-"}

Away Win

${moneyline.away?.close?.odds || "-"}

Over 2.5

${overUnder.over?.close?.odds || "-"}

Under 2.5

${overUnder.under?.close?.odds || "-"}

⚽ Match Events

${eventsHtml}

🎫 Match Information

Tickets${tickets}
Weather${weather.temperature || "N/A"}${weather.condition ? ` - ${weather.condition}` : ""}
Referee${comp.officials?.[0]?.displayName || "TBD"}
Competition${match.season?.slug?.replace(/-/g, " ") || "League"}

`; } } // Auto-init for all containers document.querySelectorAll(".match-widget-container").forEach(container => { const team1 = container.getAttribute("data-team1"); const team2 = container.getAttribute("data-team2"); loadMatch(container, team1, team2); setInterval(() => loadMatch(container, team1, team2), 30000); });