<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Service Finder - Profi Flotta</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background-color: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        .auth-wrapper { height: 100vh; display: flex; align-items: center; justify-content: center; }
        .auth-card { background: white; padding: 40px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); width: 100%; max-width: 400px; }
        .main-container { max-width: 1000px; margin: 30px auto; }
        .garage-card { border: none; border-radius: 12px; background: white; box-shadow: 0 2px 8px rgba(0,0,0,0.04); cursor: pointer; transition: 0.2s; position: relative; overflow: hidden; }
        .garage-card:hover { transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
        .card-top-strip { height: 6px; background: #0d6efd; width: 100%; position: absolute; top: 0; left: 0; }
        .card-top-strip.danger { background: #dc3545; }
        .plate-badge { background: #ffcc00; color: black; border: 1px solid #e0b000; font-family: 'Courier New', monospace; font-weight: bold; padding: 2px 6px; border-radius: 4px; }
        .tab-content-area { background: white; border-radius: 15px; padding: 25px; box-shadow: 0 5px 15px rgba(0,0,0,0.03); }
        .modal-backdrop-custom { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1040; display: flex; align-items: center; justify-content: center; }
    </style>
</head>
<body>

<div id="app">
    <div v-if="!isLoggedIn" class="auth-wrapper">
        <div class="auth-card">
            <h2 class="text-center text-primary mb-4 fw-bold">Service Finder</h2>
            <input type="email" class="form-control mb-3" v-model="authForm.email" placeholder="Email">
            <input type="password" class="form-control mb-3" v-model="authForm.password" placeholder="Jelszó">
            <button class="btn btn-primary w-100" @click="login">Belépés</button>
            <p class="text-center mt-3 small"><a href="#" @click="register">Regisztráció</a></p>
        </div>
    </div>

    <div v-else>
        <nav class="navbar navbar-dark bg-primary px-4 py-2 shadow-sm">
            <div class="container">
                <span class="navbar-brand fw-bold" @click="view='dashboard'; initApp()" style="cursor:pointer">Service Finder</span>
                <button class="btn btn-outline-light btn-sm" @click="logout">Kijelentkezés</button>
            </div>
        </nav>

        <div class="container main-container">
            <div v-if="view === 'dashboard'">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h4 class="fw-bold">Garázsom</h4>
                    <button class="btn btn-success" @click="showRegisterModal=true"><i class="bi bi-plus-lg"></i> Új Jármű</button>
                </div>
                <div class="row g-3">
                    <div class="col-md-4" v-for="car in myCars" :key="car.vehicle_id">
                        <div class="card garage-card p-3" @click="openVehicleDetail(car.vehicle_id)">
                            <div class="card-top-strip" :class="{danger: car.status !== 'OK'}"></div>
                            <h5 class="fw-bold mb-0">{{ car.brand }}</h5>
                            <div class="text-muted small mb-2">{{ car.model }}</div>
                            <span class="plate-badge">{{ car.plate }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="view === 'detail' && selectedCar">
                <button class="btn btn-link ps-0 mb-3 text-decoration-none" @click="view='dashboard'"><i class="bi bi-arrow-left"></i> Vissza</button>
                <div class="tab-content-area mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h2 class="fw-bold mb-0">{{ selectedCar.brand }} {{ selectedCar.model }}</h2>
                            <span class="plate-badge fs-6">{{ selectedCar.plate }}</span>
                        </div>
                        <div class="d-flex gap-2">
                            <button class="btn btn-danger btn-sm" @click="showErrorModal=true">Hiba Jelentése</button>
                            <button class="btn btn-success btn-sm" @click="openCostModal">Költség +</button>
                        </div>
                    </div>
                    <div class="row g-2 text-center">
                        <div class="col-4 border-end"><h6>Km állás</h6><div class="fw-bold">{{ selectedCar.mileage }}</div></div>
                        <div class="col-4 border-end"><h6>Státusz</h6><div class="fw-bold" :class="selectedCar.status==='OK'?'text-success':'text-danger'">{{ selectedCar.status }}</div></div>
                        <div class="col-4"><h6>Idei költség</h6><div class="fw-bold">{{ formatMoney(selectedCar.year_cost, selectedCar.currency) }}</div></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div v-if="showRegisterModal" class="modal-backdrop-custom">
        <div class="auth-card" style="max-width: 500px;">
            <h4 class="fw-bold mb-4">Jármű Regisztráció</h4>
            <div class="mb-3">
                <label class="small fw-bold">Modell kiválasztása</label>
                <select class="form-select" v-model="regForm.model_id">
                    <option v-for="m in allModels" :value="m.id">{{ m.brand }} {{ m.model }}</option>
                </select>
            </div>
            <div class="row g-2 mb-3">
                <div class="col-6"><input type="text" class="form-control" placeholder="Rendszám" v-model="regForm.plate"></div>
                <div class="col-6"><input type="text" class="form-control" placeholder="Alvázszám (utolsó 6)" v-model="regForm.vin"></div>
            </div>
            <div class="row g-2 mb-3">
                <div class="col-6"><input type="number" class="form-control" placeholder="Km óra" v-model="regForm.mileage"></div>
                <div class="col-6"><input type="date" class="form-control" v-model="regForm.purchase_date"></div>
            </div>
            <div class="d-flex justify-content-end gap-2">
                <button class="btn btn-light" @click="showRegisterModal=false">Mégse</button>
                <button class="btn btn-primary" @click="submitRegister">Mentés</button>
            </div>
        </div>
    </div>

    <div v-if="showCostModal" class="modal-backdrop-custom">
        <div class="auth-card" style="max-width: 500px;">
            <h4 class="fw-bold mb-4">Költség rögzítése</h4>
            <select class="form-select mb-3" v-model="costForm.type">
                <option value="FUEL">Üzemanyag</option>
                <option value="SERVICE_REPAIR">Szerviz/Javítás</option>
                <option value="TAX_WEIGHT">Súlyadó</option>
                <option value="INSURANCE_KGFB">Biztosítás (KGFB)</option>
            </select>
            <input type="number" class="form-control mb-3" placeholder="Összeg" v-model="costForm.amount">
            <div class="d-flex justify-content-end gap-2">
                <button class="btn btn-light" @click="showCostModal=false">Bezár</button>
                <button class="btn btn-success" @click="submitCost">Mentés</button>
            </div>
        </div>
    </div>
</div>

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
    const { createApp } = Vue
    createApp({
        data() {
            return {
                isLoggedIn: !!localStorage.getItem('token'),
                view: 'dashboard',
                authForm: { email: '', password: '' },
                regForm: { model_id: '', plate: '', vin: '', mileage: '', purchase_date: '' },
                costForm: { type: 'FUEL', amount: '' },
                myCars: [],
                allModels: [],
                selectedCar: null,
                showRegisterModal: false,
                showCostModal: false,
                showErrorModal: false
            }
        },
        methods: {
            async login() {
                const p = new URLSearchParams(); p.append('username', this.authForm.email); p.append('password', this.authForm.password);
                const res = await fetch('/api/auth/login', { method: 'POST', body: p });
                if (res.ok) { const d = await res.json(); localStorage.setItem('token', d.access_token); this.isLoggedIn = true; this.initApp(); }
            },
            async register() {
                const f = new FormData(); f.append('email', this.authForm.email); f.append('password', this.authForm.password);
                await fetch('/api/auth/register', { method: 'POST', body: f }); alert("Sikeres regisztráció!");
            },
            logout() { localStorage.clear(); this.isLoggedIn = false; },
            
            async apiFetch(url, options = {}) {
                const token = localStorage.getItem('token');
                options.headers = { ...options.headers, 'Authorization': 'Bearer ' + token };
                return await fetch(url, options);
            },

            async initApp() {
                if(!this.isLoggedIn) return;
                const r1 = await this.apiFetch('/api/my_vehicles'); if(r1.ok) this.myCars = await r1.json();
                const r2 = await fetch('/api/vehicles'); if(r2.ok) this.allModels = await r2.json();
            },

            async openVehicleDetail(id) {
                const r = await this.apiFetch('/api/vehicle/' + id);
                if(r.ok) { this.selectedCar = await r.json(); this.view = 'detail'; }
            },

            async submitRegister() {
                const r = await this.apiFetch('/api/register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(this.regForm)
                });
                if(r.ok) { this.showRegisterModal = false; this.initApp(); }
            },

            async submitCost() {
                const fd = new FormData();
                fd.append('vehicle_id', this.selectedCar.id);
                fd.append('cost_type', this.costForm.type);
                fd.append('amount', this.costForm.amount);
                fd.append('currency', this.selectedCar.currency || 'HUF');
                fd.append('date_str', new Date().toISOString().split('T')[0]);
                fd.append('mileage', this.selectedCar.mileage);
                
                const r = await this.apiFetch('/api/add_cost', { method: 'POST', body: fd });
                if(r.ok) { this.showCostModal = false; this.openVehicleDetail(this.selectedCar.id); }
            },

            formatMoney(a, c) { return new Intl.NumberFormat('hu-HU', { style: 'currency', currency: c || 'HUF' }).format(a || 0); }
        },
        mounted() { this.initApp(); }
    }).mount('#app')
</script>
</body>
</html>