const LOCAL_STORAGE_KEY = 'codm_wc_collected_series_v3'; const DRAFT_STORAGE_KEY = 'codm_wc_active_draft_v3'; const BACKEND_API_URL = 'api.php'; const API_KEY = ''; // Runtime-injected automatically when empty function generateId(prefix = 'id') { return { ...series, id: series.id || generateId('series'), stageLabel: series.stageLabel || 'CODM World Championship', seriesCode: series.seriesCode || '', matchDate: series.matchDate || '', teamA: series.teamA || 'Team A', teamB: series.teamB || 'Team B', teamABans, teamBBans, proofScreenshots, maps }; } // ========================================================================= // CENTRAL BACKEND API HELPERS (api.php) // ========================================================================= async function fetchSeriesFromBackend() { const res = await fetch(BACKEND_API_URL, { method: 'GET', cache: 'no-store' }); if (!res.ok) { throw new Error(`Backend GET failed (${res.status})`); } const data = await res.json(); if (!data || data.ok === false || !Array.isArray(data.series)) { throw new Error(data?.error || 'Invalid response from backend.'); } return data.series.map(normalizeSeriesRecord); } async function saveSeriesToBackend(seriesObj) { const res = await fetch(BACKEND_API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(seriesObj) }); if (!res.ok) { const errText = await res.text().catch(() => ''); throw new Error(errText || `Backend POST failed (${res.status})`); } const data = await res.json(); if (!data || data.ok === false) { throw new Error(data?.error || 'Backend failed to save series.'); } return data.series ? normalizeSeriesRecord(data.series) : seriesObj; } async function deleteSeriesFromBackend(seriesId) { const res = await fetch(`${BACKEND_API_URL}?id=${encodeURIComponent(seriesId)}`, { method: 'DELETE' }); if (!res.ok) { throw new Error(`Backend DELETE failed (${res.status})`); } const data = await res.json(); if (!data || data.ok === false) { throw new Error(data?.error || 'Backend failed to delete series.'); } } // ========================================================================= // GEMINI VISION SCREENSHOT STAT EXTRACTION // ========================================================================= function CollectedSeriesVault({ seriesList, backendConnected, isSyncingBackend, onRefreshFromBackend, onDeleteSeries, onLoadToEditor, onImportJsonSeries, onShowToast }) { const [searchTerm, setSearchTerm] = useState(''); const [expandedId, setExpandedId] = useState(null); const importInputRef = useRef(null); const filteredSeries = useMemo(() => { const handleExportJson = () => { if (seriesList.length === 0) { onShowToast('No collected match series to export yet.', 'error'); return; } if (backendConnected) { window.open(`${BACKEND_API_URL}?action=export_json`, '_blank', 'noopener,noreferrer'); onShowToast('Downloading full central JSON archive from server...', 'success'); return; } const stamp = new Date().toISOString().slice(0, 10); downloadFile( JSON.stringify(seriesList, null, 2), `codm_wc_match_series_${stamp}.json`, 'application/json' ); onShowToast(`Exported ${seriesList.length} match series as JSON.`, 'success'); }; const handleExportCsv = () => { if (seriesList.length === 0) { onShowToast('No collected match series to export yet.', 'error'); return; } if (backendConnected) { window.open(`${BACKEND_API_URL}?action=export_csv`, '_blank', 'noopener,noreferrer'); onShowToast('Downloading full central CSV dataset from server...', 'success'); return; } const stamp = new Date().toISOString().slice(0, 10); const csv = buildSeriesCsv(seriesList); downloadFile(csv, `codm_wc_match_stats_${stamp}.csv`, 'text/csv;charset=utf-8;'); onShowToast(`Exported ${seriesList.length} match series as CSV.`, 'success'); }; const handleImportFile = (e) => { return (
{/* Vault Header & Export/Import Actions */}

Collected Match Series Archive

{backendConnected ? 'Central Backend Connected' : 'Local Browser Fallback'}

All submitted CODM WC series, map bans, proof screenshots, map screenshots, and player stats stored centrally and ready to inspect or export.

{/* Search Filter */} // ========================================================================= // MAIN APPLICATION COMPONENT // ========================================================================= function App() { const [activeTab, setActiveTab] = useState('entry'); // 'entry' | 'vault' const [toast, setToast] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const [backendConnected, setBackendConnected] = useState(false); const [isSyncingBackend, setIsSyncingBackend] = useState(false); const [draft, setDraft] = useState(() => { const [firebaseReady, setFirebaseReady] = useState(false); const [firestoreContext, setFirestoreContext] = useState(null); const [userId, setUserId] = useState(null); const syncAllFromBackend = async (silent = false) => { setIsSyncingBackend(true); try { const serverSeries = await fetchSeriesFromBackend(); setBackendConnected(true); setCollectedSeries((prevLocal) => { const byId = new Map(); serverSeries.forEach((s) => byId.set(s.id, s)); prevLocal.forEach((localItem) => { if (!byId.has(localItem.id)) { byId.set(localItem.id, localItem); } }); return Array.from(byId.values()).sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '') ); }); if (!silent) { showToast(`Synced ${serverSeries.length} series from central backend.`, 'success'); } } catch (err) { setBackendConnected(false); if (!silent) { showToast('Backend not reachable yet; using local browser storage.', 'info'); } } finally { setIsSyncingBackend(false); } }; useEffect(() => { syncAllFromBackend(true); }, []); const showToast = (message, type = 'info') => { setCollectedSeries((prev) => { const withoutDup = prev.filter((item) => item.id !== submittedSeries.id); return [submittedSeries, ...withoutDup]; }); let savedCentral = submittedSeries; try { savedCentral = await saveSeriesToBackend(submittedSeries); setBackendConnected(true); setCollectedSeries((prev) => { const withoutDup = prev.filter((item) => item.id !== savedCentral.id); return [savedCentral, ...withoutDup]; }); } catch (apiErr) { console.warn('Central backend save skipped/failed:', apiErr); } if (firebaseReady && firestoreContext && userId) { const { db, appId, fb } = firestoreContext; const docRef = fb.doc( db, 'artifacts', appId, 'users', userId, 'codm_wc_series', savedCentral.id ); try { await fb.setDoc(docRef, { id: savedCentral.id, teamA: savedCentral.teamA, teamB: savedCentral.teamB, createdAt: savedCentral.createdAt, payloadJson: JSON.stringify(savedCentral) }); } catch (fsErr) { await fb.setDoc(docRef, { id: savedCentral.id, teamA: savedCentral.teamA, teamB: savedCentral.teamB, createdAt: savedCentral.createdAt, payloadJson: JSON.stringify(stripScreenshotsForQuotaFallback(savedCentral)) }); } } setDraft(createEmptyDraft()); showToast( `Match series (${cleanTeamA} vs ${cleanTeamB}) saved to backend with screenshots & stats!`, 'success' ); window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (err) { console.error('Submit series failed:', err); showToast('Error saving match series. Please try again.', 'error'); } finally { setIsSubmitting(false); } }; const handleResetDraft = () => { setDraft(createEmptyDraft()); showToast('Started a fresh match series form.', 'info'); }; const handleDeleteSeries = async (seriesId) => { setCollectedSeries((prev) => prev.filter((s) => s.id !== seriesId)); try { await deleteSeriesFromBackend(seriesId); } catch (apiErr) { console.warn('Could not delete from backend:', apiErr); } if (firebaseReady && firestoreContext && userId) { try { const { db, appId, fb } = firestoreContext; await fb.deleteDoc( fb.doc(db, 'artifacts', appId, 'users', userId, 'codm_wc_series', seriesId) ); } catch (err) { console.warn('Could not delete from Firestore:', err); } } showToast('Removed match series from archive.', 'info'); }; ) : ( syncAllFromBackend(false)} onDeleteSeries={handleDeleteSeries} onLoadToEditor={handleLoadSeriesToEditor} onImportJsonSeries={handleImportJsonSeries} onShowToast={showToast} /> )} setToast(null)} />
); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render();