// ==========================================
// File: style.css
// ==========================================
:root {
    --primary: #2563eb;
    --primary-dark: #1d4ed8;
    --secondary: #475569;
    --bg-color: #f8fafc;
    --surface: #ffffff;
    --text-main: #0f172a;
    --text-muted: #64748b;
    --success: #10b981;
    --warning: #f59e0b;
    --danger: #ef4444;
    --gold: #fbbf24;
    --border: #e2e8f0;
    --radius-md: 12px;
    --radius-lg: 20px;
    --shadow-sm: 0 1px 3px rgba(0,0,0,0.1);
    --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

body {
    background-color: var(--bg-color);
    color: var(--text-main);
    line-height: 1.5;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    -webkit-user-select: none;
}

/* Utilities */
.hidden { display: none !important; }
.full-width { width: 100%; }
.mb-2 { margin-bottom: 0.5rem; }
.text { color: var(--text-main); }
.text.primary { color: var(--primary); }

/* Buttons */
.btn {
    user-select: none;
    -webkit-user-select: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.75rem 1.5rem;
    border-radius: var(--radius-md);
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    gap: 0.5rem;
    font-size: 1rem;
}

.btn.primary {
    background-color: var(--primary);
    color: white;
}
.btn.primary:active { background-color: var(--primary-dark); }

.btn.secondary {
    background-color: var(--surface);
    color: var(--text-main);
    border: 1px solid var(--border);
}
.btn.secondary:active { background-color: var(--bg-color); }

.btn.danger {
    background-color: var(--danger);
    color: white;
}

.btn.outline.gold {
    background-color: transparent;
    color: var(--gold);
    border: 1px solid var(--gold);
}

.btn.outline.primary {
    background-color: transparent;
    color: var(--primary);
    border: 1.5px solid var(--primary);
}
.btn.outline.primary:active {
    background-color: rgba(37, 99, 235, 0.1);
}

.btn.icon-only {
    padding: 0.5rem;
    border-radius: 50%;
}

.btn.small {
    padding: 0.4rem 0.8rem;
    font-size: 0.875rem;
}

/* Inputs */
input, select, textarea {
    width: 100%;
    padding: 0.75rem 1rem;
    border: 1px solid var(--border);
    border-radius: var(--radius-md);
    font-size: 1rem;
    background-color: var(--surface);
    color: var(--text-main);
    transition: border-color 0.2s;
}
input:focus, select:focus, textarea:focus {
    outline: none;
    border-color: var(--primary);
}
.form-group {
    margin-bottom: 1rem;
}
.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: var(--text-muted);
}

/* Layout & Views */
#app {
    max-width: 600px;
    margin: 0 auto;
    min-height: 100vh;
    position: relative;
    padding-bottom: 80px; /* Space for bottom nav */
    background-color: var(--bg-color);
    box-shadow: var(--shadow-sm);
}

.view {
    display: none !important;
    padding: 1.5rem;
    animation: fadeIn 0.3s ease;
}
.view.active {
    display: block !important;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

/* Auth View */
.auth-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 80vh;
    text-align: center;
}
.logo {
    margin-bottom: 3rem;
}
.logo i {
    font-size: 4rem;
    color: var(--primary);
    margin-bottom: 1rem;
}
.auth-step {
    display: none;
    width: 100%;
    max-width: 320px;
}
.auth-step.active {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

/* Header */
.app-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 1.5rem;
    background-color: var(--surface);
    border-bottom: 1px solid var(--border);
    position: sticky;
    top: 0;
    z-index: 10;
}
.user-info {
    display: flex;
    align-items: center;
    gap: 0.75rem;
}
.header-actions {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: var(--primary);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* Sections */
.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
}
.current-km {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    background-color: var(--surface);
    padding: 0.5rem 1rem;
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-sm);
}

/* Dashboard */
.health-overview {
    background-color: var(--surface);
    border-radius: var(--radius-lg);
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    box-shadow: var(--shadow-md);
    text-align: center;
}
.chart-container {
    position: relative;
    height: 200px;
    width: 200px;
    margin: 0 auto 1rem;
}
.status-good { color: var(--success); }

.parts-grid {
    display: grid;
    gap: 1rem;
}
.part-card {
    background-color: var(--surface);
    border-radius: var(--radius-md);
    padding: 1rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    box-shadow: var(--shadow-sm);
    border-left: 4px solid var(--success);
}
.part-card.warning { border-left-color: var(--warning); }
.part-card.danger { border-left-color: var(--danger); }
.part-icon {
    font-size: 1.5rem;
    color: var(--text-muted);
}
.part-details {
    flex: 1;
}
.progress-bar {
    height: 8px;
    background-color: var(--border);
    border-radius: 4px;
    margin: 0.5rem 0;
    overflow: hidden;
}
.progress {
    height: 100%;
    background-color: var(--success);
    transition: width 1s ease-out;
}
.warning .progress { background-color: var(--warning); }
.danger .progress { background-color: var(--danger); }
.remaining {
    font-size: 0.8rem;
    color: var(--text-muted);
}

/* Tabs */
.tabs {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
    border-bottom: 1px solid var(--border);
}
.tab {
    background: none;
    border: none;
    padding: 0.5rem 0;
    font-size: 1rem;
    color: var(--text-muted);
    cursor: pointer;
    border-bottom: 2px solid transparent;
}
.tab.active {
    color: var(--primary);
    border-bottom-color: var(--primary);
    font-weight: 600;
}
.tab-content {
    display: none;
}
.tab-content.active {
    display: block;
    animation: fadeIn 0.3s ease;
}

/* History Items */
.history-item {
    background-color: var(--surface);
    padding: 1rem;
    border-radius: var(--radius-md);
    margin-bottom: 1rem;
    box-shadow: var(--shadow-sm);
}
.history-item-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 0.5rem;
    font-weight: 600;
}
.history-item-meta {
    font-size: 0.85rem;
    color: var(--text-muted);
    display: flex;
    gap: 1rem;
}

/* DIY Section */
.diy-cards {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    margin-bottom: 1.5rem;
}
.card {
    background-color: var(--surface);
    padding: 1rem;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-sm);
    text-align: center;
}
.card i {
    font-size: 2rem;
    color: var(--primary);
    margin-bottom: 0.5rem;
}
.card h3 { font-size: 1rem; margin-bottom: 0.5rem; }
.card p { font-size: 0.85rem; color: var(--text-muted); margin-bottom: 1rem; }

.video-grid {
    display: grid;
    gap: 1rem;
    margin-top: 1rem;
}
.video-card {
    background-color: var(--surface);
    border-radius: var(--radius-md);
    overflow: hidden;
    box-shadow: var(--shadow-sm);
}
.video-thumb {
    height: 150px;
    background-color: var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    color: white;
}
.video-info { padding: 1rem; }

/* AI & OBD2 */
.obd-section {
    background-color: var(--surface);
    padding: 1.5rem;
    border-radius: var(--radius-lg);
    text-align: center;
    margin-bottom: 1.5rem;
    box-shadow: var(--shadow-md);
}
.obd-status {
    font-size: 1.2rem;
    font-weight: bold;
    margin-bottom: 1rem;
    color: var(--text-muted);
}
.ai-chat-section {
    background-color: var(--surface);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-md);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    height: 400px;
}
.chat-messages {
    flex: 1;
    padding: 1rem;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 1rem;
}
.message {
    max-width: 80%;
    padding: 0.75rem 1rem;
    border-radius: var(--radius-md);
    line-height: 1.4;
}
.message.ai {
    background-color: var(--bg-color);
    align-self: flex-start;
    border-bottom-right-radius: 0;
}
.message.user {
    background-color: var(--primary);
    color: white;
    align-self: flex-end;
    border-bottom-left-radius: 0;
}
.chat-input {
    display: flex;
    padding: 1rem;
    border-top: 1px solid var(--border);
    gap: 0.5rem;
}
.chat-input input { margin-bottom: 0; }

/* Settings */
.settings-group {
    background-color: var(--surface);
    padding: 1.5rem;
    border-radius: var(--radius-lg);
    margin-bottom: 1.5rem;
    box-shadow: var(--shadow-sm);
}
.settings-group h3 {
    margin-bottom: 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid var(--border);
}
.setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}
.setting-item select { width: auto; min-width: 120px; }

/* Bottom Nav */
.bottom-nav {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    max-width: 600px;
    margin: 0 auto;
    background-color: var(--surface);
    display: flex;
    justify-content: space-around;
    padding: 0.75rem 0;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
    z-index: 100;
}
.nav-item {
    user-select: none;
    -webkit-user-select: none;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-decoration: none;
    color: var(--text-muted);
    font-size: 0.8rem;
    gap: 0.25rem;
    transition: color 0.2s;
}
.nav-item i { font-size: 1.25rem; }
.nav-item.active { color: var(--primary); }

/* Modals */
.modal {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 1000;
    align-items: flex-end; /* Mobile style, slide from bottom */
    justify-content: center;
}
.modal.active { display: flex; }
.modal-content {
    background-color: var(--surface);
    width: 100%;
    max-width: 600px;
    padding: 2rem;
    border-radius: 20px 20px 0 0;
    animation: slideUp 0.3s ease;
    position: relative;
    max-height: 90vh;
    overflow-y: auto;
}
.close-modal {
    position: absolute;
    top: 1rem;
    left: 1.5rem;
    font-size: 1.5rem;
    cursor: pointer;
    color: var(--text-muted);
}
@keyframes slideUp {
    from { transform: translateY(100%); }
    to { transform: translateY(0); }
}

/* Toast */
.toast {
    position: fixed;
    bottom: 90px;
    left: 50%;
    transform: translateX(-50%);
    background-color: #333;
    color: white;
    padding: 0.75rem 1.5rem;
    border-radius: var(--radius-md);
    z-index: 2000;
    opacity: 0;
    transition: opacity 0.3s;
    pointer-events: none;
}
.toast.show { opacity: 1; }

/* PWA Install Banner */
.pwa-install-banner {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 1rem;
    background: linear-gradient(135deg, #1d4ed8 0%, #2563eb 100%);
    color: #ffffff;
    padding: 0.85rem 1.25rem;
    border-radius: var(--radius-md);
    margin: 0.75rem 1rem;
    box-shadow: 0 4px 14px rgba(37, 99, 235, 0.25);
    z-index: 100;
    position: relative;
    border: 1px solid rgba(255, 255, 255, 0.15);
}
.banner-content {
    display: flex;
    align-items: center;
    gap: 0.85rem;
}
.banner-icon {
    width: 44px;
    height: 44px;
    border-radius: 10px;
    object-fit: cover;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
    border: 1.5px solid rgba(255, 255, 255, 0.4);
}
.banner-text {
    display: flex;
    flex-direction: column;
}
.banner-text strong {
    font-size: 0.95rem;
    font-weight: 700;
    letter-spacing: -0.2px;
}
.banner-text span {
    font-size: 0.8rem;
    opacity: 0.92;
    margin-top: 2px;
}
.banner-actions {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.banner-actions .btn {
    user-select: none;
    -webkit-user-select: none;
    white-space: nowrap;
    background-color: #ffffff;
    color: var(--primary-dark);
    font-weight: 700;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.banner-actions .btn:hover {
    background-color: #f8fafc;
}
.banner-close-btn {
    background: transparent;
    border: none;
    color: rgba(255, 255, 255, 0.75);
    font-size: 1.6rem;
    line-height: 1;
    cursor: pointer;
    padding: 0.25rem 0.5rem;
    border-radius: 6px;
    transition: all 0.2s;
}
.banner-close-btn:hover {
    color: #ffffff;
    background-color: rgba(255, 255, 255, 0.15);
}

/* Auth Install Section */
.auth-install-section {
    margin-top: 2rem;
    width: 100%;
    max-width: 320px;
    padding-top: 1rem;
    border-top: 1px dashed var(--border);
}

/* Install Guide Modal */
.install-guide-content {
    text-align: right;
    max-width: 540px;
    padding: 1.75rem;
}
.install-guide-header {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1.25rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border);
}
.install-guide-logo {
    width: 52px;
    height: 52px;
    border-radius: 12px;
    box-shadow: 0 4px 10px rgba(37, 99, 235, 0.2);
}
.install-guide-header h2 {
    font-size: 1.15rem;
    color: var(--text-main);
    margin-bottom: 0.25rem;
}
.install-guide-header p {
    font-size: 0.82rem;
    color: var(--text-muted);
}
.guide-platform-section {
    background: var(--bg-color);
    border-radius: var(--radius-md);
    padding: 1rem 1.25rem;
    margin-bottom: 1rem;
    border: 1px solid var(--border);
}
.guide-platform-section h4 {
    color: var(--primary);
    font-size: 0.95rem;
    margin-bottom: 0.75rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.guide-steps {
    padding-right: 1.25rem;
    font-size: 0.88rem;
    line-height: 1.9;
    color: var(--text-main);
}
.guide-steps strong {
    color: var(--primary-dark);
}

@media (max-width: 576px) {
    .pwa-install-banner {
        flex-direction: column;
        align-items: stretch;
        gap: 0.75rem;
    }
    .banner-actions {
        justify-content: space-between;
    }
    .banner-actions .btn {
    user-select: none;
    -webkit-user-select: none;
        flex: 1;
    }
});

const app = {
    config: {
        supabaseUrl: 'https://miotuyaypolahjzhkfpq.supabase.co',
        supabaseKey: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im1pb3R1eWF5cG9sYWhqemhrZnBxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3OTE2MTYyOTgsImV4cCI6MjEwNzE5MjI5OH0.YUnMHxiM0dbYuqeOSbsM66HqQrmXVW2PvFScGDZZ7mw',
        zarinpalMerchant: 'YOUR_ZARINPAL_MERCHANT_ID',
        openAiKey: 'YOUR_OPENAI_API_KEY'
    },
    state: { user: null, phone: '', currentKm: 0, records: [], obdDevice: null, deferredPrompt: null, isStandalone: false },
    els: {},

    init() {
        this.cacheDOM();
        this.bindEvents();
        this.initPwa();
        this.initSupabase();
        this.checkAuth();
        this.registerServiceWorker();
    },

    cacheDOM() {
        this.els = {
            authView: document.getElementById('auth-view'),
            mainLayout: document.getElementById('main-layout'),
            views: document.querySelectorAll('.view:not(#auth-view)'),
            navItems: document.querySelectorAll('.nav-item'),
            phoneInput: document.getElementById('phone-input'),
            sendOtpBtn: document.getElementById('send-otp-btn'),
            otpInput: document.getElementById('otp-input'),
            verifyOtpBtn: document.getElementById('verify-otp-btn'),
            loginStep1: document.getElementById('login-step-1'),
            loginStep2: document.getElementById('login-step-2'),
            displayPhone: document.getElementById('display-phone'),
            userPhoneDisplay: document.getElementById('user-phone-display'),
            logoutBtn: document.getElementById('logout-btn'),
            dashboardKm: document.getElementById('dashboard-km'),
            updateKmBtn: document.getElementById('update-km-btn'),
            newRecordBtn: document.getElementById('new-record-btn'),
            addRecordModal: document.getElementById('add-record-modal'),
            closeModals: document.querySelectorAll('.close-modal'),
            recordForm: document.getElementById('record-form'),
            recordType: document.getElementById('record-type'),
            serviceFields: document.querySelectorAll('.service-fields'),
            tabs: document.querySelectorAll('.tab'),
            tabContents: document.querySelectorAll('.tab-content'),
            premiumBtn: document.getElementById('premium-btn'),
            paymentModal: document.getElementById('payment-modal'),
            connectObdBtn: document.getElementById('connect-obd-btn'),
            obdStatus: document.getElementById('obd-connection-status'),
            aiInput: document.getElementById('ai-input'),
            aiSendBtn: document.getElementById('ai-send-btn'),
            aiMessages: document.getElementById('ai-messages'),
            toast: document.getElementById('toast'),
            pwaInstallBanner: document.getElementById('pwa-install-banner'),
            bannerInstallBtn: document.getElementById('banner-install-btn'),
            bannerCloseBtn: document.getElementById('banner-close-btn'),
            authInstallBtn: document.getElementById('auth-install-btn'),
            headerInstallBtn: document.getElementById('header-install-btn'),
            installBtn: document.getElementById('install-btn'),
            installGroup: document.getElementById('install-group'),
            installGuideModal: document.getElementById('install-guide-modal'),
            guideTriggerInstallBtn: document.getElementById('guide-trigger-install-btn'),
            guideIos: document.getElementById('guide-ios'),
            guideAndroid: document.getElementById('guide-android'),
            guideDesktop: document.getElementById('guide-desktop')
        };
    },

    bindEvents() {
        this.els.navItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const viewId = e.currentTarget.dataset.view;
                this.switchView(viewId);
                this.els.navItems.forEach(nav => nav.classList.remove('active'));
                e.currentTarget.classList.add('active');
            });
        });

        if (this.els.sendOtpBtn) this.els.sendOtpBtn.addEventListener('click', () => this.sendOtp());
        if (this.els.verifyOtpBtn) this.els.verifyOtpBtn.addEventListener('click', () => this.verifyOtp());
        const backBtn = document.getElementById('back-to-phone-btn');
        if (backBtn) backBtn.addEventListener('click', () => {
            this.els.loginStep2.classList.remove('active');
            this.els.loginStep1.classList.add('active');
        });
        if (this.els.logoutBtn) this.els.logoutBtn.addEventListener('click', () => this.logout());
        if (this.els.newRecordBtn) this.els.newRecordBtn.addEventListener('click', () => this.openModal(this.els.addRecordModal));
        if (this.els.premiumBtn) this.els.premiumBtn.addEventListener('click', () => this.openModal(this.els.paymentModal));
        this.els.closeModals.forEach(btn => btn.addEventListener('click', (e) => this.closeModal(e.target.closest('.modal'))));
        
        if (this.els.recordType) {
            this.els.recordType.addEventListener('change', (e) => {
                const isService = e.target.value === 'service';
                this.els.serviceFields.forEach(field => {
                    field.style.display = isService ? 'block' : 'none';
                    const input = field.querySelector('input');
                    if(input) input.required = isService;
                });
            });
        }
        if (this.els.recordForm) this.els.recordForm.addEventListener('submit', (e) => this.saveRecord(e));

        this.els.tabs.forEach(tab => {
            tab.addEventListener('click', (e) => {
                const targetId = e.target.dataset.target;
                this.els.tabs.forEach(t => t.classList.remove('active'));
                this.els.tabContents.forEach(c => c.classList.remove('active'));
                e.target.classList.add('active');
                document.getElementById(targetId).classList.add('active');
            });
        });

        if (this.els.connectObdBtn) this.els.connectObdBtn.addEventListener('click', () => this.connectOBD());
        if (this.els.aiSendBtn) this.els.aiSendBtn.addEventListener('click', () => this.sendAiMessage());
        if (this.els.aiInput) {
            this.els.aiInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') this.sendAiMessage(); });
        }

        const installTriggerElements = [this.els.bannerInstallBtn, this.els.authInstallBtn, this.els.headerInstallBtn, this.els.installBtn, this.els.guideTriggerInstallBtn];
        installTriggerElements.forEach(btn => {
            if (btn) btn.addEventListener('click', (e) => { e.preventDefault(); this.triggerInstall(); });
        });

        if (this.els.bannerCloseBtn) this.els.bannerCloseBtn.addEventListener('click', () => this.dismissBanner());
        window.addEventListener('online', () => { this.showToast('اینترنت متصل شد. در حال همگام‌سازی...', 'success'); this.syncOfflineData(); });
        window.addEventListener('offline', () => { this.showToast('ارتباط با اینترنت قطع شد.', 'warning'); });

        if (this.els.updateKmBtn) {
            this.els.updateKmBtn.addEventListener('click', () => {
                const newKm = prompt('کیلومتر فعلی خودرو را وارد کنید:', this.state.currentKm);
                if (newKm && !isNaN(newKm)) this.updateKm(parseInt(newKm));
            });
        }
    },

    initSupabase() {
        if (!this.config.supabaseUrl || this.config.supabaseUrl === 'YOUR_SUPABASE_URL') {
            this.supabase = null; return;
        }
        try {
            this.supabase = window.supabase.createClient(this.config.supabaseUrl, this.config.supabaseKey);
        } catch(e) {
            this.supabase = null;
        }
    },

    checkAuth() {
        const savedUser = localStorage.getItem('autoyar_user');
        if (savedUser) {
            this.state.user = JSON.parse(savedUser);
            this.showMainApp();
        } else {
            this.els.authView.style.display = 'block';
            this.els.mainLayout.style.display = 'none';
        }
    },

    async sendOtp() {
        const rawPhone = this.els.phoneInput.value;
        if (!rawPhone || rawPhone.length < 10) {
            this.showToast('شماره موبایل نامعتبر است', 'error'); return;
        }
        
        let formattedPhone = rawPhone;
        if (rawPhone.startsWith('09')) formattedPhone = '+98' + rawPhone.substring(1);
        else if (rawPhone.startsWith('9')) formattedPhone = '+98' + rawPhone;

        this.state.phone = formattedPhone;
        this.els.displayPhone.textContent = rawPhone;

        let apiSuccess = false;
        if (this.supabase) {
            try {
                const { error } = await this.supabase.auth.signInWithOtp({ phone: formattedPhone });
                if (error) throw error;
                apiSuccess = true;
            } catch(e) {
                console.warn('Supabase Error, using local fallback.', e);
            }
        }

        if (apiSuccess) {
            this.showToast('کد تایید ارسال شد', 'success');
        } else {
            this.showToast('حالت آفلاین/تستی (کد: 123456)', 'warning');
        }
        this.els.loginStep1.classList.remove('active');
        this.els.loginStep2.classList.add('active');
    },

    async verifyOtp() {
        const otp = this.els.otpInput.value;
        let apiSuccess = false;

        if (this.supabase) {
            try {
                const { data, error } = await this.supabase.auth.verifyOtp({ phone: this.state.phone, token: otp, type: 'sms' });
                if (error) throw error;
                this.state.user = { phone: this.state.phone, id: data.user.id, isPremium: false };
                apiSuccess = true;
            } catch(e) {
                apiSuccess = false;
            }
        }

        if (!apiSuccess) {
            if (otp === '123456') {
                this.state.user = { phone: this.state.phone, id: 'user_test', isPremium: false };
            } else {
                this.showToast('کد تایید اشتباه است', 'error'); return;
            }
        }

        localStorage.setItem('autoyar_user', JSON.stringify(this.state.user));
        this.showMainApp();
        this.showToast('ورود موفقیت آمیز بود', 'success');
    },

    async logout() {
        localStorage.removeItem('autoyar_user');
        if(this.supabase) await this.supabase.auth.signOut();
        window.location.reload();
    },

    showMainApp() {
        this.els.authView.style.display = 'none';
        this.els.authView.classList.remove('active');
        this.els.mainLayout.style.display = 'block';
        if(this.els.userPhoneDisplay) this.els.userPhoneDisplay.textContent = this.state.user.phone;
        this.switchView('dashboard-view');
        this.loadDashboardData();
        this.loadHistory();
    },

    switchView(viewId) {
        this.els.views.forEach(view => {
            view.classList.remove('active');
            view.style.display = 'none'; 
        });
        const targetView = document.getElementById(viewId);
        if(targetView) {
            targetView.style.display = 'block';
            setTimeout(() => targetView.classList.add('active'), 10);
        }
        if(viewId === 'dashboard-view' && !this.chartInit) {
            try { this.initChart(); this.chartInit = true; } catch (e) {}
        }
    },

    openModal(modal) { if(modal) modal.classList.add('active'); },
    closeModal(modal) { if(modal) modal.classList.remove('active'); },
    
    showToast(message, type = 'info') {
        if(!this.els.toast) return;
        this.els.toast.textContent = message;
        this.els.toast.className = `toast show ${type}`;
        setTimeout(() => { this.els.toast.classList.remove('show'); }, 3000);
    },

    updateKm(km) {
        this.state.currentKm = km;
        if(this.els.dashboardKm) this.els.dashboardKm.textContent = km.toLocaleString();
        this.showToast('کیلومتر بروزرسانی شد', 'success');
    },

    async loadDashboardData() { this.updateKm(this.state.currentKm || 0); },
    initChart() { /* Chart Logic Unchanged */ },
    
    async saveRecord(e) {
        e.preventDefault();
        const type = this.els.recordType.value;
        const record = {
            id: Date.now(), type: type,
            title: document.getElementById('record-title').value,
            date: new Date().toLocaleDateString('fa-IR'),
            desc: document.getElementById('record-desc').value, synced: false 
        };
        if (type === 'service') {
            record.km = document.getElementById('record-km').value;
            record.nextKm = document.getElementById('record-next-km').value;
            record.cost = document.getElementById('record-cost').value;
        }
        this.state.records.unshift(record); 
        localStorage.setItem('autoyar_records', JSON.stringify(this.state.records));
        this.renderRecords();
        this.closeModal(this.els.addRecordModal);
        this.els.recordForm.reset();
        await this.syncRecordToCloud(record);
    },

    async syncRecordToCloud(record) {},
    async syncOfflineData() {},
    async loadHistory() { this.renderRecords(); },

    renderRecords() {
        const repairsList = document.getElementById('repairs-list');
        const symptomsList = document.getElementById('symptoms-list');
        if(!repairsList || !symptomsList) return;
        repairsList.innerHTML = ''; symptomsList.innerHTML = '';
        this.state.records.forEach(r => {
            const div = document.createElement('div');
            div.className = 'history-item';
            div.innerHTML = `<div class="history-item-header"><span>${r.title}</span></div>`;
            if (r.type === 'service') repairsList.appendChild(div);
            else symptomsList.appendChild(div);
        });
    },

    async connectOBD() {},
    async sendAiMessage() {},
    initPwa() {},
    triggerInstall() {},
    registerServiceWorker() {}
};

window.app = app;
const startApp = () => { if (!window.appInitialized) { app.init(); window.appInitialized = true; } };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', startApp); } else { startApp(); }

/* Vehicle Selector */
.vehicle-selector-container {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.vehicle-selector {
    padding: 0.5rem;
    border-radius: var(--radius-md);
    border: 1px solid var(--border);
    background: var(--surface);
    color: var(--text-main);
    font-size: 0.9rem;
    min-width: 120px;
    max-width: 180px;
}
