<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Service Finder - Flotta Kezelő</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 Képernyő */
        .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; }
        
        /* Alkalmazás stílusok */
        .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; }
        .history-item { border-left: 3px solid #e9ecef; padding-left: 20px; padding-bottom: 20px; position: relative; }
        .history-icon { position: absolute; left: -11px; top: 0; width: 20px; height: 20px; border-radius: 50%; border: 2px solid white; }
    </style>
</head>
<body>

<div id="app">
    <div v-if="!isLoggedIn" class="auth-wrapper">
        <div class="auth-card">
            <h2 class="fw-bold mb-4 text-center text-primary"><i class="bi bi-speedometer2"></i> Service Finder</h2>
            <div v-if="authView === 'login'">
                <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 py-2" @click="login">Bejelentkezés</button>
                <p class="text-center mt-3 small">Nincs fiókod? <a href="#" @click="authView='register'">Regisztrálj!</a></p>
            </div>
            <div v-if="authView === 'register'">
                <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-success w-100 py-2" @click="register">Regisztráció</button>
                <p class="text-center mt-3 small"><a href="#" @click="authView='login'">Vissza a belépéshez</a></p>
            </div>
        </div>
    </div>

    <div v-else>
        <nav class="navbar navbar-dark bg-primary shadow-sm px-4 py-2">
            <div class="container">
                <span class="navbar-brand fw-bold"><i class="bi bi-speedometer2 me-2"></i>Service Finder</span>
                <div class="d-flex align-items-center">
                    <span class="text-white me-3 small">{{ userEmail }}</span>
                    <button class="btn btn-outline-light btn-sm" @click="logout"><i class="bi bi-box-arrow-right"></i></button>
                </div>
            </div>
        </nav>

        <div class="container main-container">
            <div v-if="view === 'dashboard'">
                <div class="d-flex justify-content-between mb-4">
                    <h4 class="fw-bold">Saját Járművek</h4>
                    <button class="btn btn-primary btn-sm"><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>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="plate-badge">{{ car.plate }}</span>
                                <i v-if="car.status !== 'OK'" class="bi bi-exclamation-triangle text-danger"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="view === 'detail' && selectedCar">
                <button class="btn btn-link text-decoration-none ps-0 mb-3" @click="view='dashboard'"><i class="bi bi-arrow-left"></i> Vissza a listához</button>
                <div class="detail-header shadow-sm border">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h2 class="fw-bold mb-1">{{ selectedCar.brand }} {{ selectedCar.model }}</h2>
                            <span class="plate-badge fs-6">{{ selectedCar.plate }}</span>
                        </div>
                        <div class="text-end">
                            <button class="btn btn-success" @click="openCostModal"><i class="bi bi-plus-lg"></i> Költség</button>
                        </div>
                    </div>
                </div>

                <div class="tab-content-area shadow-sm">
                    <div class="row text-center">
                        <div class="col-4 border-end"><h6>Km állás</h6><div class="fw-bold fs-4">{{ selectedCar.mileage }}</div></div>
                        <div class="col-4 border-end"><h6>Idei költség</h6><div class="fw-bold fs-4">{{ formatMoney(selectedCar.year_cost, selectedCar.currency) }}</div></div>
                        <div class="col-4"><h6>Állapot</h6><div :class="selectedCar.status === 'OK' ? 'text-success' : 'text-danger'" class="fw-bold fs-4">{{ selectedCar.status }}</div></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div v-if="showCostModal" class="modal-backdrop-custom auth-wrapper" style="position:fixed; top:0; left:0; width:100%; background:rgba(0,0,0,0.5); z-index:9999;">
        <div class="auth-card" style="max-width: 500px;">
            <h4 class="fw-bold mb-4">Új Költség Rögzítése</h4>
            <div class="row g-3">
                <div class="col-6">
                    <label class="small fw-bold">Kategória</label>
                    <select class="form-select" v-model="costForm.mainCategory" @change="updateSubCategory">
                        <option v-for="(val, key) in costDefinitions" :value="key">{{ val.label }}</option>
                    </select>
                </div>
                <div class="col-6">
                    <label class="small fw-bold">Típus</label>
                    <select class="form-select" v-model="costForm.subCategory">
                        <option v-for="(label, key) in currentSubOptions" :value="key">{{ label }}</option>
                    </select>
                </div>
                <div class="col-6"><input type="number" class="form-control" v-model="costForm.amount" placeholder="Összeg"></div>
                <div class="col-6"><select class="form-select" v-model="costForm.currency"><option value="HUF">HUF</option><option value="EUR">EUR</option></select></div>
            </div>
            <div class="d-flex justify-content-end mt-4">
                <button class="btn btn-light me-2" @click="showCostModal=false">Mégse</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'),
                userEmail: '',
                authView: 'login',
                view: 'dashboard',
                authForm: { email: '', password: '' },
                myCars: [],
                selectedCar: null,
                showCostModal: false,
                costForm: { mainCategory: '', subCategory: '', amount: '', currency: 'HUF' },
                costDefinitions: {}
            }
        },
        computed: {
            currentSubOptions() { return this.costDefinitions[this.costForm.mainCategory]?.subs || null; }
        },
        methods: {
            // --- AUTH ---
            async login() {
    const params = new URLSearchParams();
    params.append('username', this.authForm.email); // Az email megy a username mezőbe
    params.append('password', this.authForm.password);

    try {
        const res = await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: params
        });

        if (res.ok) {
            const data = await res.json();
            localStorage.setItem('token', data.access_token);
            this.isLoggedIn = true;
            this.initApp();
        } else {
            const errorData = await res.json();
            alert("Belépés elutasítva: " + (errorData.detail || "Ismeretlen hiba"));
        }
    } catch (e) {
        alert("Szerver hiba a bejelentkezéskor!");
    }
}
            },
            async register() {
                const fd = new FormData();
                fd.append('email', this.authForm.email);
                fd.append('password', this.authForm.password);
                await fetch('/api/auth/register', { method: 'POST', body: fd });
                alert("Sikeres regisztráció! Jelentkezz be.");
                this.authView = 'login';
            },
            logout() { localStorage.removeItem('token'); this.isLoggedIn = false; },

            // --- API HELPERS (JWT Token-nel!) ---
            async apiFetch(url, options = {}) {
                const token = localStorage.getItem('token');
                options.headers = { ...options.headers, 'Authorization': `Bearer ${token}` };
                const res = await fetch(url, options);
                if(res.status === 401) this.logout();
                return res;
            },

            // --- ALKALMAZÁS LOGIKA ---
            async initApp() {
                if(!this.isLoggedIn) return;
                const resCars = await this.apiFetch('/api/my_vehicles');
                this.myCars = await resCars.json();
                const resTypes = await fetch('/api/ref/cost_types'); // Ez publikus is lehet
                this.costDefinitions = await resTypes.json();
            },
            async openVehicleDetail(id) {
                const res = await this.apiFetch(`/api/vehicle/${id}`);
                this.selectedCar = await res.json();
                this.view = 'detail';
            },
            openCostModal() {
                this.costForm.mainCategory = Object.keys(this.costDefinitions)[0];
                this.updateSubCategory();
                this.showCostModal = true;
            },
            updateSubCategory() {
                const subs = this.costDefinitions[this.costForm.mainCategory]?.subs;
                this.costForm.subCategory = subs ? Object.keys(subs)[0] : '';
            },
            async submitCost() {
                const fd = new FormData();
                fd.append('vehicle_id', this.selectedCar.id);
                fd.append('cost_type', this.costForm.subCategory || this.costForm.mainCategory);
                fd.append('amount', this.costForm.amount);
                fd.append('currency', this.costForm.currency);
                fd.append('date_str', new Date().toISOString().split('T')[0]);
                fd.append('mileage', this.selectedCar.mileage);

                const res = await this.apiFetch('/api/add_cost', { method: 'POST', body: fd });
                if(res.ok) {
                    this.showCostModal = false;
                    this.openVehicleDetail(this.selectedCar.id);
                }
            },
            formatMoney(amount, curr) { return new Intl.NumberFormat('hu-HU', { style: 'currency', currency: curr }).format(amount); }
        },
        mounted() { this.initApp(); }
    }).mount('#app')
</script>
</body>
</html>