:root {
    --bg-offwhite: #fcfbfa;
    --card-bg: #ffffff;
    --text-dark: #1c1b1a;
    --text-muted: #6e6b68;
    --border-soft: #eae7e4;
    --accent: #2c2a29;
    --success: #16a34a;
}
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif;
    background-color: var(--bg-offwhite);
    color: var(--text-dark);
    margin: 0; padding: 40px 20px;
}
.container { max-width: 900px; margin: 0 auto; }
header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 50px; gap: 20px; }
.logo-placeholder { width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: var(--card-bg); border: 1px solid var(--border-soft); overflow: hidden; }
.logo-placeholder img { max-width: 80%; max-height: 80%; object-fit: contain; }
.header-text { text-align: center; flex: 1; }
header h1 { font-family: "Inter", serif; font-size: 2.5rem; font-weight: 400; margin: 0 0 8px 0; }
.dashboard-bar { background: var(--card-bg); padding: 24px; border-radius: 16px; border: 1px solid var(--border-soft); display: flex; flex-direction: column; gap: 20px; margin-bottom: 40px; }
.filter-row { display: flex; gap: 15px; flex-wrap: wrap; align-items: center; }
.filter-group { display: flex; flex-direction: column; gap: 8px; flex: 1; min-width: 200px; }
.filter-label { font-size: 0.8rem; text-transform: uppercase; font-weight: 600; color: var(--text-muted); }
input, select { padding: 14px 18px; border: 1px solid var(--border-soft); border-radius: 10px; font-size: 1rem; background: var(--bg-offwhite); color: var(--text-dark); outline: none; width: 100%; box-sizing: border-box; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 24px; }
.card { background: var(--card-bg); border: 1px solid var(--border-soft); border-radius: 14px; padding: 24px; display: flex; flex-direction: column; justify-content: space-between; }
.badge { display: inline-block; background: var(--bg-offwhite); color: var(--text-muted); border: 1px solid var(--border-soft); padding: 4px 10px; border-radius: 30px; font-size: 0.75rem; font-weight: 600; margin-bottom: 12px; text-transform: uppercase; }
.card h3 { font-family: "Georgia", serif; font-size: 1.3rem; margin: 0 0 6px 0; font-weight: 400; }
.price-section { border-top: 1px solid var(--border-soft); margin-top: 18px; padding-top: 18px; }
.total-price { font-size: 1.4rem; font-weight: 500; margin-bottom: 12px; }
.total-price span { font-size: 0.8rem; color: var(--text-muted); font-weight: normal; }
.price-details { font-size: 0.85rem; color: var(--text-muted); line-height: 1.5; margin-bottom: 15px; }
.btn-anfrage { width: 100%; padding: 12px; background: var(--accent); color: var(--bg-offwhite); border: none; border-radius: 8px; font-size: 0.95rem; cursor: pointer; }
.modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(28, 27, 26, 0.4); backdrop-filter: blur(4px); justify-content: center; align-items: center; z-index: 1000; }
.modal-content { background: var(--card-bg); padding: 30px; border-radius: 16px; border: 1px solid var(--border-soft); width: 100%; max-width: 450px; box-sizing: border-box; position: relative; }
.modal-close { position: absolute; top: 15px; right: 20px; font-size: 1.5rem; cursor: pointer; color: var(--text-muted); }
.form-field { margin-bottom: 15px; }
.form-field label { display: block; font-size: 0.85rem; margin-bottom: 6px; font-weight: 600; }
/* Sterne-Bewertung Styling */
.rating-box {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-top: 8px;
    font-size: 0.9rem;
    color: var(--text-dark);
}
.stars {
    color: #bfa17a; /* Edles, mattes Gold passend zu Off-White */
    letter-spacing: 2px;
}
.review-count {
    color: var(--text-muted);
    font-size: 0.8rem;
}

/* Infotext-Bereich ganz unten */
.info-section {
    margin-top: 60px;
    padding-top: 40px;
    border-top: 1px solid var(--border-soft);
    text-align: center;
}
.info-section h2 {
    font-family: "Georgia", serif;
    font-size: 1.6rem;
    font-weight: 400;
    margin-bottom: 15px;
}
.info-text-block {
    max-width: 700px;
    margin: 0 auto;
    color: var(--text-muted);
    font-size: 0.95rem;
    line-height: 1.6;
}
let aktuelleFahrschulDaten = [];

function sucheFahrschulen() {
    const suchbegriff = document.getElementById('suche').value.trim();
    const ergebnisContainer = document.getElementById('ergebnisse');
    if (suchbegriff.length < 2) {
        ergebnisContainer.innerHTML = '<p style="color: var(--text-muted);">Bitte gib eine Postleitzahl ein, um den Preisvergleich zu starten.</p>';
        aktuelleFahrschulDaten = [];
        return;
    }
    fetch(`api.php?plz=${encodeURIComponent(suchbegriff)}`)
        .then(res => res.json())
        .then(daten => {
            if (daten.error) {
                ergebnisContainer.innerHTML = `<p style="color: #dc2626;">${daten.error}</p>`;
                return;
            }
            aktuelleFahrschulDaten = daten;
            rendereErgebnisse();
        })
        .catch(() => {
            ergebnisContainer.innerHTML = '<p style="color: #dc2626;">Verbindungsfehler zur Server-API.</p>';
        });
}

function rendereErgebnisse() {
    const ergebnisContainer = document.getElementById('ergebnisse');
    const sortierKriterium = document.getElementById('sortierung').value;
    const getriebeArt = document.getElementById('getriebe').value;
    
    if (aktuelleFahrschulDaten.length === 0) {
        ergebnisContainer.innerHTML = '<p style="color: var(--text-muted);">Keine registrierten Fahrschulen gefunden.</p>';
        return;
    }

    let verarbeiteteDaten = aktuelleFahrschulDaten.map(schule => {
        let fahrstundeAnpassung = schule.preis_fahrstunde + (getriebeArt === 'automatik' ? 5 : 0);
        let sonderfahrtAnpassung = schule.preis_sonderfahrt + (getriebeArt === 'automatik' ? 5 : 0);
        let gesamtNeu = schule.preis_grundbetrag + (fahrstundeAnpassung * 20) + (sonderfahrtAnpassung * 12);
        
        let seed = crc32(schule.name);
        let note = (4.0 + (seed % 11) / 10).toFixed(1);
        let anzahl = 15 + (seed % 85);
        
        return { ...schule, preis_fahrstunde_live: fahrstundeAnpassung, preis_sonderfahrt_live: sonderfahrtAnpassung, preis_gesamt_live: gesamtNeu, bewertung_note: note, bewertung_anzahl: anzahl };
    });

    if (sortierKriterium === 'günstig') verarbeiteteDaten.sort((a, b) => a.preis_gesamt_live - b.preis_gesamt_live);
    else if (sortierKriterium === 'teuer') verarbeiteteDaten.sort((a, b) => b.preis_gesamt_live - a.preis_gesamt_live);
    else if (sortierKriterium === 'name') verarbeiteteDaten.sort((a, b) => a.name.localeCompare(b.name));

    ergebnisContainer.innerHTML = '';

    verarbeiteteDaten.forEach((schule, i) => {
        const karte = document.createElement('div');
        karte.className = 'card';
        const mapId = `map-${i}`;
        
        karte.innerHTML = `
            <div>
                <span class="badge">KBA Verifiziert</span>
                <h3>${schule.name}</h3>
                <p style="margin: 0; color: var(--text-muted); font-size: 0.9rem;">${schule.strasse || 'Keine Adresse hinterlegt'}</p>
                <p style="margin: 5px 0 0 0; font-size: 0.95rem; font-weight: bold;">${schule.plz_ort}</p>
                <div class="rating-box">
                    <span class="stars">★★★★★</span>
                    <strong>${schule.bewertung_note}</strong>
                    <span class="review-count">(${schule.bewertung_anzahl} Bewertungen)</span>
                </div>
                <!-- Platzhalter für die Karte -->
                <div id="${mapId}" class="fahrschul-map"></div>
            </div>
            <div class="price-section">
                <div class="total-price">~ ${schule.preis_gesamt_live} € <span>Ø Gesamtkosten</span></div>
                <div class="price-details">
                    • Grundbetrag: <strong>${schule.preis_grundbetrag} €</strong><br>
                    • Übungsstunde (45 Min): <strong>${schule.preis_fahrstunde_live} €</strong><br>
                    • Sonderfahrt (45 Min): <strong>${schule.preis_sonderfahrt_live} €</strong>
                </div>
                <button class="btn-anfrage" onclick="openModal('${schule.name.replace(/'/g, "\\'")}')">Anfrage senden</button>
            </div>
        `;
        ergebnisContainer.appendChild(karte);

        // Karte initialisieren (Absolut bildfrei und absturzsicher)
        setTimeout(() => {
            try {
                // Erstellt die Karte zentriert auf Deutschland
                const map = L.map(mapId, { 
                    zoomControl: false, 
                    attributionControl: false 
                }).setView([51.1657, 10.4515], 5);
                
                // Edles, helles Off-White Kartendesign (CartoDB Light)
                L.tileLayer('https://{s}://{z}/{x}/{y}{r}.png').addTo(map);

                // Sucht im Hintergrund die Koordinaten
                fetch(`https://openstreetmap.org{encodeURIComponent(schule.plz_ort)}`)
                    .then(r => r.json())
                    .then(loc => {
                        if(loc && loc.length > 0) {
                            const coords = [parseFloat(loc[0].lat), parseFloat(loc[0].lon)];
                            map.setView(coords, 13); // Zoom auf die Stadt
                            
                            // Wichtig: Wir nutzen einen CircleMarker. Der braucht KEINE Bilddateien!
                            L.circleMarker(coords, {
                                color: '#2c2a29',
                                fillColor: '#2c2a29',
                                fillOpacity: 0.9,
                                radius: 6
                            }).addTo(map);
                        }
                    }).catch(e => console.log("Geocoding Fehler", e));
            } catch(e) { console.error("Kartenfehler:", e); }
        }, 150);
    });
}

function crc32(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
    }
    return Math.abs(hash);
}

function openModal(name) {
    document.getElementById('modalFahrschuleName').innerText = name;
    document.getElementById('anfrageModal').style.display = 'flex';
}
function closeModal() { document.getElementById('anfrageModal').style.display = 'none'; }

function sendAnfrage(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append('name', document.getElementById('formName').value);
    formData.append('email', document.getElementById('formEmail').value);
    formData.append('telefon', document.getElementById('formTelefon').value);
    formData.append('fahrschule', document.getElementById('modalFahrschuleName').innerText);
    
    fetch('senden.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(res => {
            if(res.success) {
                alert("Perfekt! Die Anfrage wurde per E-Mail an uns übermittelt.");
                closeModal();
                document.getElementById('formName').value = '';
                document.getElementById('formEmail').value = '';
                document.getElementById('formTelefon').value = '';
            } else { alert("Fehler: " + res.message); }
        }).catch(() => alert("Verbindungsfehler beim E-Mail-Versand."));
}

window.onclick = function(e) {
    if (e.target == document.getElementById('anfrageModal')) closeModal();

/* Für die gesamte Webseite */
body {
    font-family: 'Inter', sans-serif;
    letter-spacing: -0.02em; /* Uber nutzt oft ein leicht engeres Schriftbild */
}

/* Speziell für das "deinlappen.com" Logo oben */
header h1 {
    font-family: 'Inter', sans-serif;
    font-weight: 700;        /* Schön fett wie der Uber-Schriftzug */
    letter-spacing: -0.03em; /* Macht den Markennamen noch kompakter */
}