@extends('layouts.app')

@section('title', 'Langkah 2: Data Keuangan - FIN-ANALYSIS PRO')

@section('content')
<div class="max-w-4xl mx-auto">
    <!-- Header -->
    <div class="mb-8 text-center">
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">
            Data Keuangan
        </h1>
        <p class="text-gray-600 dark:text-gray-400">
            Masukkan data keuangan perusahaan untuk periode {{ $companyData['period'] ?? '' }}
        </p>
    </div>

    <!-- Step Indicator -->
    <div class="mb-8">
        <div class="flex items-center justify-between">
            <div class="flex items-center text-green-600 dark:text-green-400">
                <div class="step-circle step-circle-completed">
                    <i class="fas fa-check text-sm"></i>
                </div>
                <span class="ml-2 font-medium hidden sm:inline">Data Perusahaan</span>
            </div>
            <div class="flex-1 mx-4 h-0.5 bg-green-300 dark:bg-green-700"></div>
            <div class="flex items-center text-primary-600 dark:text-primary-400">
                <div class="step-circle step-circle-active">2</div>
                <span class="ml-2 font-medium hidden sm:inline">Data Keuangan</span>
            </div>
            <div class="flex-1 mx-4 h-0.5 bg-gray-300 dark:bg-gray-700"></div>
            <div class="flex items-center text-gray-400 dark:text-gray-600">
                <div class="step-circle step-circle-inactive">3</div>
                <span class="ml-2 font-medium hidden sm:inline">Hasil Analisis</span>
            </div>
        </div>
    </div>

    <!-- Company Info Summary -->
    <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4 mb-6">
        <div class="flex items-center justify-between flex-wrap gap-4">
            <div>
                <span class="text-sm text-gray-500 dark:text-gray-400">Perusahaan</span>
                <h3 class="font-semibold text-gray-900 dark:text-white">{{ $companyData['company_name'] ?? '-' }}</h3>
            </div>
            <div>
                <span class="text-sm text-gray-500 dark:text-gray-400">Bidang Usaha</span>
                <p class="font-semibold text-gray-900 dark:text-white">
                    @if(($companyData['business_field'] ?? '') === 'Lainnya')
                        {{ $companyData['other_field'] ?? 'Lainnya' }}
                    @else
                        {{ $companyData['business_field'] ?? '-' }}
                    @endif
                </p>
            </div>
            <div>
                <span class="text-sm text-gray-500 dark:text-gray-400">Periode</span>
                <p class="font-semibold text-gray-900 dark:text-white">{{ $companyData['period'] ?? '-' }}</p>
            </div>
            <div>
                <span class="text-sm text-gray-500 dark:text-gray-400">Mata Uang</span>
                <p class="font-semibold text-gray-900 dark:text-white">{{ $companyData['currency'] ?? '-' }}</p>
            </div>
            <a href="{{ route('analysis.step1') }}" class="text-primary-600 hover:text-primary-700 text-sm">
                <i class="fas fa-edit mr-1"></i> Ubah
            </a>
        </div>
    </div>

    <!-- Form Card -->
    <div class="card">
        <form action="{{ route('analysis.step2.save') }}" method="POST" id="financialForm" x-data="financialForm()">
            @csrf

            <!-- Aset -->
            <div class="mb-8">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                    <i class="fas fa-chart-pie text-primary-600 mr-2"></i>
                    Aset
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Aset Lancar -->
                    <div class="form-group">
                        <label for="aset_lancar" class="label-field required">
                            Aset Lancar
                            <span class="text-xs text-gray-500 block">(Kas, Piutang, Persediaan)</span>
                        </label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 sm:text-sm">Rp</span>
                            </div>
                            {{-- Input tampilan (format ribuan) --}}
                            <input type="text"
                                   id="aset_lancar_display"
                                   class="input-field pl-12 @error('aset_lancar') input-error @enderror currency-input"
                                   placeholder="0"
                                   autocomplete="off"
                                   data-field="aset_lancar">
                            {{-- Hidden input nilai murni ke server --}}
                            <input type="hidden" name="aset_lancar" id="aset_lancar"
                                   value="{{ old('aset_lancar', $financialData['aset_lancar'] ?? '') }}">
                        </div>
                        @error('aset_lancar')
                            <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Aset Tetap -->
                    <div class="form-group">
                        <label for="aset_tetap" class="label-field required">
                            Aset Tetap
                            <span class="text-xs text-gray-500 block">(Peralatan, Tanah, Bangunan)</span>
                        </label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 sm:text-sm">Rp</span>
                            </div>
                            <input type="text"
                                   id="aset_tetap_display"
                                   class="input-field pl-12 @error('aset_tetap') input-error @enderror currency-input"
                                   placeholder="0"
                                   autocomplete="off"
                                   data-field="aset_tetap">
                            <input type="hidden" name="aset_tetap" id="aset_tetap"
                                   value="{{ old('aset_tetap', $financialData['aset_tetap'] ?? '') }}">
                        </div>
                        @error('aset_tetap')
                            <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <!-- Total Aset -->
                <div class="mt-4 p-4 bg-primary-50 dark:bg-primary-900/20 rounded-lg">
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700 dark:text-gray-300">Total Aset:</span>
                        <span class="text-xl font-bold text-primary-600 dark:text-primary-400" id="total_aset_display">Rp 0</span>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Total Aset = Aset Lancar + Aset Tetap (dihitung otomatis)</p>
                </div>
            </div>

            <!-- Utang -->
            <div class="mb-8">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                    <i class="fas fa-credit-card text-warning-600 mr-2"></i>
                    Utang / Liabilitas
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Utang Lancar -->
                    <div class="form-group">
                        <label for="utang_lancar" class="label-field required">
                            Utang Lancar
                            <span class="text-xs text-gray-500 block">(Utang Dagang, Utang Gaji)</span>
                        </label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 sm:text-sm">Rp</span>
                            </div>
                            <input type="text"
                                   id="utang_lancar_display"
                                   class="input-field pl-12 @error('utang_lancar') input-error @enderror currency-input"
                                   placeholder="0"
                                   autocomplete="off"
                                   data-field="utang_lancar">
                            <input type="hidden" name="utang_lancar" id="utang_lancar"
                                   value="{{ old('utang_lancar', $financialData['utang_lancar'] ?? '') }}">
                        </div>
                        @error('utang_lancar')
                            <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Utang Jangka Panjang -->
                    <div class="form-group">
                        <label for="utang_jangka_panjang" class="label-field required">
                            Utang Jangka Panjang
                            <span class="text-xs text-gray-500 block">(Utang Bank, Obligasi)</span>
                        </label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 sm:text-sm">Rp</span>
                            </div>
                            <input type="text"
                                   id="utang_jangka_panjang_display"
                                   class="input-field pl-12 @error('utang_jangka_panjang') input-error @enderror currency-input"
                                   placeholder="0"
                                   autocomplete="off"
                                   data-field="utang_jangka_panjang">
                            <input type="hidden" name="utang_jangka_panjang" id="utang_jangka_panjang"
                                   value="{{ old('utang_jangka_panjang', $financialData['utang_jangka_panjang'] ?? '') }}">
                        </div>
                        @error('utang_jangka_panjang')
                            <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <!-- Total Utang -->
                <div class="mt-4 p-4 bg-warning-50 dark:bg-warning-900/20 rounded-lg">
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700 dark:text-gray-300">Total Utang:</span>
                        <span class="text-xl font-bold text-warning-600 dark:text-warning-400" id="total_utang_display">Rp 0</span>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Total Utang = Utang Lancar + Utang Jangka Panjang (dihitung otomatis)</p>
                </div>
            </div>

            <!-- Ekuitas -->
            <div class="mb-8">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                    <i class="fas fa-chart-line text-success-600 mr-2"></i>
                    Ekuitas
                </h3>
                <div class="p-4 bg-success-50 dark:bg-success-900/20 rounded-lg">
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700 dark:text-gray-300">Nilai Buku Ekuitas:</span>
                        <span class="text-xl font-bold text-success-600 dark:text-success-400" id="ekuitas_display">Rp 0</span>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Nilai Buku Ekuitas = Total Aset - Total Utang (dihitung otomatis)</p>
                </div>
            </div>

            <!-- Laba Rugi -->
            <div class="mb-8">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                    <i class="fas fa-chart-bar text-info-600 mr-2"></i>
                    Laba Rugi
                </h3>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Pendapatan -->
                    <div class="form-group">
                        <label for="pendapatan" class="label-field required">
                            Pendapatan
                            <span class="text-xs text-gray-500 block">(Penjualan/Pendapatan)</span>
                        </label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 sm:text-sm">Rp</span>
                            </div>
                            <input type="text"
                                   id="pendapatan_display"
                                   class="input-field pl-12 @error('pendapatan') input-error @enderror currency-input"
                                   placeholder="0"
                                   autocomplete="off"
                                   data-field="pendapatan">
                            <input type="hidden" name="pendapatan" id="pendapatan"
                                   value="{{ old('pendapatan', $financialData['pendapatan'] ?? '') }}">
                        </div>
                        @error('pendapatan')
                            <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- Biaya Operasional -->
                    <div class="form-group">
                        <label for="biaya_operasional" class="label-field required">
                            Biaya Operasional
                            <span class="text-xs text-gray-500 block">(Biaya Gaji, Produksi)</span>
                        </label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <span class="text-gray-500 sm:text-sm">Rp</span>
                            </div>
                            <input type="text"
                                   id="biaya_operasional_display"
                                   class="input-field pl-12 @error('biaya_operasional') input-error @enderror currency-input"
                                   placeholder="0"
                                   autocomplete="off"
                                   data-field="biaya_operasional">
                            <input type="hidden" name="biaya_operasional" id="biaya_operasional"
                                   value="{{ old('biaya_operasional', $financialData['biaya_operasional'] ?? '') }}">
                        </div>
                        @error('biaya_operasional')
                            <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                        @enderror
                    </div>
                </div>

                <!-- Laba Sebelum Pajak -->
                <div class="mt-4 p-4 bg-info-50 dark:bg-info-900/20 rounded-lg">
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700 dark:text-gray-300">Laba Sebelum Pajak:</span>
                        <span class="text-xl font-bold text-info-600 dark:text-info-400" id="laba_sebelum_pajak_display">Rp 0</span>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Laba Sebelum Pajak = Pendapatan - Biaya Operasional (dihitung otomatis)</p>
                </div>

                <!-- Prive -->
                <div class="form-group mt-6">
                    <label for="prive" class="label-field required">
                        Pengambilan Pribadi (Prive)
                        <span class="text-xs text-gray-500 block">(Pengambilan dana oleh pemilik)</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <span class="text-gray-500 sm:text-sm">Rp</span>
                        </div>
                        <input type="text"
                               id="prive_display"
                               class="input-field pl-12 @error('prive') input-error @enderror currency-input"
                               placeholder="0"
                               autocomplete="off"
                               data-field="prive">
                        <input type="hidden" name="prive" id="prive"
                               value="{{ old('prive', $financialData['prive'] ?? '') }}">
                    </div>
                    @error('prive')
                        <p class="mt-1 text-sm text-danger-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Laba Ditahan -->
                <div class="mt-4 p-4 bg-purple-50 dark:bg-purple-900/20 rounded-lg">
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700 dark:text-gray-300">Laba Ditahan:</span>
                        <span class="text-xl font-bold text-purple-600 dark:text-purple-400" id="laba_ditahan_display">Rp 0</span>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">Laba Ditahan = Laba Sebelum Pajak - Prive (dihitung otomatis)</p>
                </div>
            </div>

            <!-- Live Preview Z-Score -->
            <div class="mb-8 p-4 border border-gray-200 dark:border-gray-700 rounded-lg" id="previewSection" style="display:none">
                <h4 class="font-semibold text-gray-900 dark:text-white mb-3">
                    <i class="fas fa-calculator mr-2"></i>
                    Pratinjau Z-Score
                </h4>
                <div class="grid grid-cols-2 md:grid-cols-5 gap-4 text-center">
                    <div><div class="text-xs text-gray-500">X1</div><div class="font-mono font-bold" id="prev_x1">0</div></div>
                    <div><div class="text-xs text-gray-500">X2</div><div class="font-mono font-bold" id="prev_x2">0</div></div>
                    <div><div class="text-xs text-gray-500">X3</div><div class="font-mono font-bold" id="prev_x3">0</div></div>
                    <div><div class="text-xs text-gray-500">X4</div><div class="font-mono font-bold" id="prev_x4">0</div></div>
                    <div><div class="text-xs text-gray-500">X5</div><div class="font-mono font-bold" id="prev_x5">0</div></div>
                </div>
                <div class="mt-2 text-center">
                    <span class="text-sm font-medium">Z-Score: </span>
                    <span class="text-lg font-bold" id="prev_zscore">0</span>
                    <span class="ml-2 text-sm" id="prev_label"></span>
                </div>
            </div>

            <!-- Toggle Preview -->
            <div class="flex items-center justify-end mb-4">
                <label class="flex items-center cursor-pointer">
                    <span class="mr-2 text-sm text-gray-600 dark:text-gray-400">Pratinjau Z-Score</span>
                    <div class="relative">
                        <input type="checkbox" class="sr-only" id="togglePreview">
                        <div class="w-10 h-5 bg-gray-300 rounded-full shadow-inner" id="toggleTrack"></div>
                        <div class="absolute left-0 top-0 w-5 h-5 bg-white rounded-full shadow transition-transform duration-200 transform" id="toggleThumb"></div>
                    </div>
                </label>
            </div>

            <!-- Tombol Aksi -->
            <div class="flex items-center justify-between pt-4 border-t border-gray-200 dark:border-gray-700">
                <a href="{{ route('analysis.step1') }}" class="btn-secondary">
                    <i class="fas fa-arrow-left mr-2"></i>
                    Kembali
                </a>
                <div class="flex space-x-3">
                    <button type="button" id="btnReset" class="btn-outline">
                        <i class="fas fa-undo mr-2"></i>
                        Reset
                    </button>
                    <button type="submit" class="btn-primary">
                        Hitung Analisis
                        <i class="fas fa-calculator ml-2"></i>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Tips -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3">
            <div class="flex items-center">
                <i class="fas fa-lightbulb text-blue-600 mr-2"></i>
                <span class="text-sm font-medium text-blue-800">Tips</span>
            </div>
            <p class="text-xs text-blue-700 mt-1">Ketik angka saja — titik pemisah ribuan otomatis muncul saat mengetik.</p>
        </div>
        <div class="bg-green-50 dark:bg-green-900/20 rounded-lg p-3">
            <div class="flex items-center">
                <i class="fas fa-check-circle text-green-600 mr-2"></i>
                <span class="text-sm font-medium text-green-800">Akurasi</span>
            </div>
            <p class="text-xs text-green-700 mt-1">Pastikan data sesuai laporan keuangan untuk hasil yang akurat.</p>
        </div>
        <div class="bg-purple-50 dark:bg-purple-900/20 rounded-lg p-3">
            <div class="flex items-center">
                <i class="fas fa-history text-purple-600 mr-2"></i>
                <span class="text-sm font-medium text-purple-800">Riwayat</span>
            </div>
            <p class="text-xs text-purple-700 mt-1">Hasil analisis tersimpan dan bisa dilihat di halaman Riwayat.</p>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
(function () {
    'use strict';

    // ── CORE: Format angka ke "2.000.000" sambil menjaga posisi kursor ──
    function formatRibuan(str) {
        // Ambil digit saja
        const digits = str.replace(/\D/g, '');
        if (!digits) return '';
        // Tambah titik setiap 3 digit dari kanan
        return parseInt(digits, 10).toLocaleString('id-ID');
    }

    function getRawValue(displayVal) {
        return parseInt(displayVal.replace(/\D/g, '') || '0', 10);
    }

    function formatRp(num) {
        if (num < 0) return 'Rp -' + Math.abs(num).toLocaleString('id-ID');
        return 'Rp ' + num.toLocaleString('id-ID');
    }

    // ── STATE: nilai numerik murni ────────────────────────────────────
    const vals = {
        aset_lancar:          0,
        aset_tetap:           0,
        utang_lancar:         0,
        utang_jangka_panjang: 0,
        pendapatan:           0,
        biaya_operasional:    0,
        prive:                0,
    };

    // ── COMPUTED ──────────────────────────────────────────────────────
    function compute() {
        const totalAset   = vals.aset_lancar + vals.aset_tetap;
        const totalUtang  = vals.utang_lancar + vals.utang_jangka_panjang;
        const ekuitas     = totalAset - totalUtang;
        const lsbp        = vals.pendapatan - vals.biaya_operasional;
        const labaDitahan = lsbp - vals.prive;

        // Update tampilan total
        setText('total_aset_display',         formatRp(totalAset),   totalAset   >= 0);
        setText('total_utang_display',        formatRp(totalUtang),  true, 'text-warning-600 dark:text-warning-400');
        setText('ekuitas_display',            formatRp(ekuitas),     ekuitas     >= 0, ekuitas < 0 ? 'text-red-600' : 'text-success-600 dark:text-success-400');
        setText('laba_sebelum_pajak_display', formatRp(lsbp),        lsbp        >= 0, lsbp < 0 ? 'text-red-600' : 'text-info-600 dark:text-info-400');
        setText('laba_ditahan_display',       formatRp(labaDitahan), labaDitahan >= 0, labaDitahan < 0 ? 'text-red-600' : 'text-purple-600 dark:text-purple-400');

        return { totalAset, totalUtang, ekuitas, lsbp, labaDitahan };
    }

    function setText(id, value, positive, cls) {
        const el = document.getElementById(id);
        if (!el) return;
        el.textContent = value;
        if (cls) el.className = el.className.replace(/text-\S+/g, '') + ' ' + cls;
    }

    // ── SETUP INPUT: format real-time saat mengetik ───────────────────
    function setupCurrencyInput(displayId, hiddenId) {
        const display = document.getElementById(displayId);
        const hidden  = document.getElementById(hiddenId);
        if (!display || !hidden) return;

        // Set nilai awal dari hidden input (old value / session)
        const initVal = parseInt(hidden.value || '0', 10);
        if (initVal > 0) {
            display.value    = initVal.toLocaleString('id-ID');
            vals[hiddenId]   = initVal;
        }

        display.addEventListener('input', function () {
            // Simpan posisi kursor SEBELUM format
            const selStart  = this.selectionStart;
            const selEnd    = this.selectionEnd;
            const oldVal    = this.value;
            const oldLen    = oldVal.length;

            // Hitung jumlah digit sebelum kursor (untuk restore posisi)
            const digitsBeforeCursor = oldVal.slice(0, selStart).replace(/\D/g, '').length;

            // Format ulang
            const formatted = formatRibuan(this.value);
            this.value = formatted;

            // Update hidden input dengan nilai murni
            const raw = getRawValue(formatted);
            hidden.value    = raw;
            vals[hiddenId]  = raw;

            // Restore posisi kursor berdasarkan jumlah digit
            // Hitung berapa karakter formatted sampai digit ke-N
            let digitCount = 0;
            let newPos = 0;
            for (let i = 0; i < formatted.length; i++) {
                if (/\d/.test(formatted[i])) digitCount++;
                if (digitCount === digitsBeforeCursor) {
                    newPos = i + 1;
                    break;
                }
            }
            // Kalau tidak ketemu (misal hapus semua), taruh di akhir
            if (digitCount < digitsBeforeCursor) newPos = formatted.length;

            this.setSelectionRange(newPos, newPos);

            // Recalculate semua total
            compute();

            // Update preview jika aktif
            if (previewActive) fetchPreview();
        });

        // Saat paste: bersihkan dan format
        display.addEventListener('paste', function (e) {
            e.preventDefault();
            const pasted = (e.clipboardData || window.clipboardData).getData('text');
            const digits  = pasted.replace(/\D/g, '');
            if (!digits) return;
            this.value     = parseInt(digits, 10).toLocaleString('id-ID');
            hidden.value   = digits;
            vals[hiddenId] = parseInt(digits, 10);
            compute();
            if (previewActive) fetchPreview();
        });
    }

    // ── INIT semua input ──────────────────────────────────────────────
    document.addEventListener('DOMContentLoaded', function () {
        [
            'aset_lancar',
            'aset_tetap',
            'utang_lancar',
            'utang_jangka_panjang',
            'pendapatan',
            'biaya_operasional',
            'prive',
        ].forEach(field => setupCurrencyInput(field + '_display', field));

        // Hitung awal
        compute();

        // ── RESET ────────────────────────────────────────────────────
        document.getElementById('btnReset')?.addEventListener('click', function () {
            if (!confirm('Reset semua data keuangan?')) return;
            Object.keys(vals).forEach(k => { vals[k] = 0; });
            document.querySelectorAll('.currency-input').forEach(el => { el.value = ''; });
            document.querySelectorAll('input[type=hidden]').forEach(el => {
                if (Object.keys(vals).includes(el.name)) el.value = 0;
            });
            compute();
        });

        // ── TOGGLE PREVIEW ───────────────────────────────────────────
        const toggle = document.getElementById('togglePreview');
        const track  = document.getElementById('toggleTrack');
        const thumb  = document.getElementById('toggleThumb');
        const section = document.getElementById('previewSection');

        toggle?.addEventListener('change', function () {
            previewActive = this.checked;
            section.style.display = previewActive ? 'block' : 'none';
            track.classList.toggle('bg-primary-500', previewActive);
            track.classList.toggle('bg-gray-300', !previewActive);
            thumb.style.transform = previewActive ? 'translateX(20px)' : 'translateX(0)';
            if (previewActive) fetchPreview();
        });
    });

    // ── LIVE PREVIEW ──────────────────────────────────────────────────
    let previewActive = false;
    let previewTimer  = null;

    function fetchPreview() {
        clearTimeout(previewTimer);
        previewTimer = setTimeout(function () {
            const { totalAset, totalUtang, ekuitas, lsbp, labaDitahan } = compute();

            fetch('{{ route("api.calculate") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({
                    aset_lancar:          vals.aset_lancar,
                    aset_tetap:           vals.aset_tetap,
                    utang_lancar:         vals.utang_lancar,
                    utang_jangka_panjang: vals.utang_jangka_panjang,
                    pendapatan:           vals.pendapatan,
                    biaya_operasional:    vals.biaya_operasional,
                    prive:                vals.prive,
                })
            })
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                const c = data.components;
                ['x1','x2','x3','x4','x5'].forEach(k => {
                    const el = document.getElementById('prev_' + k);
                    if (el) el.textContent = parseFloat(c[k]).toFixed(4);
                });
                const zEl    = document.getElementById('prev_zscore');
                const lblEl  = document.getElementById('prev_label');
                const labels = { safe:'Aman', grey:'Waspada', distress:'Berbahaya' };
                const colors = { safe:'text-green-600', grey:'text-yellow-600', distress:'text-red-600' };
                if (zEl) {
                    zEl.textContent = data.z_score;
                    zEl.className   = 'text-lg font-bold ' + (colors[data.category] || '');
                }
                if (lblEl) lblEl.textContent = labels[data.category] || data.category;
            })
            .catch(() => {});
        }, 400); // debounce 400ms
    }

})();
</script>
@endpush