@extends('layouts.app')
@section('title', 'Preview Laporan - ' . $analysis->company_name)

@push('styles')
<style>
/* Dark mode for report preview */
.dark {
    color: #f1f5f9 !important;
}

.dark #reportCard {
    background: #1e293b !important;
    border-color: #334155 !important;
}

/* Heading "Komponen Z'-Score" */
.dark div[style*="color:#64748B"] {
    color: #cbd5e1 !important;
}

/* Table headers "Neraca" dan "Laba Rugi" */
.dark div[style*="color:#1E293B;border-bottom"] {
    color: #f1f5f9 !important;
    border-color: #475569 !important;
}

/* Table text */
.dark table td {
    border-color: #475569 !important;
}

.dark table td[style*="color:#475569"] {
    color: #cbd5e1 !important;
}

.dark table td[style*="color:#1E293B"] {
    color: #f1f5f9 !important;
}

.dark table tr[style*="background:#F8FAFF"] {
    background: #334155 !important;
}

/* Card backgrounds */
.dark div[style*="background:#F8FAFF"] {
    background: #334155 !important;
    border-color: #475569 !important;
}

.dark div[style*="background:#F1F5F9"] {
    background: #0f172a !important;
    border-color: #475569 !important;
}

.dark div[style*="background:#F1F5F9;border-radius"] {
    background: #1e293b !important;
    border-color: #475569 !important;
    color: #cbd5e1 !important;
}

/* Strong tags in formula section */
.dark div[style*="background:#F1F5F9"] strong {
    color: #60a5fa !important;
}

/* Rekomendasi section */
.dark div[style*="background:#F8FAFF;border-radius"] {
    background: #334155 !important;
}

.dark ul li[style*="color:#1E293B"] {
    color: #f1f5f9 !important;
}

/* Footer border */
.dark div[style*="border-top:1px solid #E2E8F0"] {
    border-top-color: #475569 !important;
    color: #94a3b8 !important;
}

.dark span[style*="color:#94A3B8"] {
    color: #94a3b8 !important;
}

/* Light mode - ensure text stays visible */
.light div[style*="color:#64748B"] {
    color: #475569 !important;
}

.light div[style*="color:#1E293B;border-bottom"] {
    color: #0f172a !important;
    border-color: #e2e8f0 !important;
}

/* Dark mode for Email Modal */
.dark #emailModal {
    background: rgba(0, 0, 0, 0.7) !important;
}

.dark #emailModal > div {
    background: #1e293b !important;
    border: 1px solid #334155 !important;
}

.dark #emailModal > div > div[style*="font-size:1.125rem"] {
    color: #f1f5f9 !important;
}

.dark #emailModal .form-group label {
    color: #cbd5e1 !important;
}

.dark #emailModal .form-group label span.required {
    color: #ef4444 !important;
}

.dark #emailModal input.form-control,
.dark #emailModal textarea.form-control {
    background: #334155 !important;
    color: #f1f5f9 !important;
    border-color: #475569 !important;
}

.dark #emailModal input.form-control:focus,
.dark #emailModal textarea.form-control:focus {
    border-color: #60a5fa !important;
    outline: none !important;
}

.dark #emailModal input.form-control::placeholder,
.dark #emailModal textarea.form-control::placeholder {
    color: #94a3b8 !important;
}

.dark #emailModal .btn {
    font-weight: 600 !important;
}

/* Light mode - ensure contrast */
.light #emailModal > div {
    background: #ffffff !important;
}

.light #emailModal > div > div[style*="font-size:1.125rem"] {
    color: #0f172a !important;
}

.light #emailModal .form-group label {
    color: #1e293b !important;
}

.light #emailModal input.form-control,
.light #emailModal textarea.form-control {
    background: #ffffff !important;
    color: #0f172a !important;
    border-color: #e2e8f0 !important;
}

@media print {
    .navbar,.stepper-bar,.site-footer,.no-print { display:none !important; }
    .main-content { padding:0 !important; max-width:100% !important; }
    #reportCard { border:none !important; border-radius:0 !important; box-shadow:none !important; }
}
</style>
@endpush

@section('content')
<div class="max-w-4xl mx-auto">

    {{-- Action Bar --}}
    <div class="no-print" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.5rem;flex-wrap:wrap;gap:.75rem">
        <div style="display:flex;align-items:center;gap:8px">
            <a href="{{ url()->previous() }}" class="btn btn-secondary btn-sm">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg>
                Kembali
            </a>
            <span style="color:#64748B;font-size:.875rem">/ Preview Laporan</span>
        </div>
        <div style="display:flex;gap:.625rem;flex-wrap:wrap">
            <button onclick="window.print()" class="btn btn-secondary btn-sm">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="5"/></svg>
                Cetak
            </button>
            <a href="{{ route('report.download', $analysis->id) }}" class="btn btn-primary btn-sm">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                Unduh PDF
            </a>
        </div>
    </div>

    {{-- Laporan --}}
    <div id="reportCard" style="background:white;border:1px solid #E2E8F0;border-radius:16px;overflow:hidden;box-shadow:0 4px 20px rgba(0,0,0,.06)">

        {{-- Header --}}
        <div style="background:linear-gradient(135deg,#0B1437 0%,#1A56DB 100%);padding:2.5rem;color:white">
            <div style="display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:1rem">
                <div>
                    <div style="font-size:.7rem;font-weight:600;letter-spacing:.12em;opacity:.6;margin-bottom:.5rem;text-transform:uppercase">Laporan Analisis Keuangan</div>
                    <div style="font-size:1.75rem;font-weight:800;margin-bottom:.375rem">{{ $analysis->company_name }}</div>
                    <div style="opacity:.75">{{ $analysis->business_field }}</div>
                </div>
                <div style="text-align:right;font-size:.875rem">
                    <div style="font-weight:700;font-size:.75rem;letter-spacing:.06em;text-transform:uppercase;opacity:.5;margin-bottom:4px">FIN-ANALYSIS PRO</div>
                    <div style="font-weight:600">{{ $analysis->period }}</div>
                    <div style="opacity:.65;margin-top:3px;font-size:.8rem">{{ $analysis->created_at->format('d F Y') }}</div>
                </div>
            </div>
        </div>

        <div style="padding:2rem">
            @php
                $cat = $analysis->z_category;
                $zc  = [
                    'safe'     => ['bg'=>'#D1FAE5','border'=>'#6EE7B7','text'=>'#065F46','badge'=>'#059669','label'=>'ZONA AMAN'],
                    'grey'     => ['bg'=>'#FEF3C7','border'=>'#FCD34D','text'=>'#92400E','badge'=>'#D97706','label'=>'ZONA WASPADA'],
                    'distress' => ['bg'=>'#FEE2E2','border'=>'#FCA5A5','text'=>'#991B1B','badge'=>'#DC2626','label'=>'ZONA BERBAHAYA'],
                ][$cat] ?? ['bg'=>'#FEF3C7','border'=>'#FCD34D','text'=>'#92400E','badge'=>'#D97706','label'=>'ZONA WASPADA'];
                $cur = $analysis->currency;
                $fd  = $financial;
                $fmt = fn($v) => $cur . ' ' . number_format((float)($v ?? 0), 0, ',', '.');
            @endphp

            {{-- Z-Score Card --}}
            <div style="display:flex;align-items:center;justify-content:center;gap:2rem;padding:1.5rem;background:{{ $zc['bg'] }};border:1.5px solid {{ $zc['border'] }};border-radius:12px;margin-bottom:2rem;flex-wrap:wrap;text-align:center">
                <div>
                    <div style="font-size:.75rem;font-weight:700;color:{{ $zc['text'] }};letter-spacing:.08em;text-transform:uppercase;margin-bottom:.5rem">Altman Z'-Score</div>
                    <div style="font-size:3rem;font-weight:900;color:{{ $zc['text'] }};line-height:1">{{ number_format($analysis->z_score, 4) }}</div>
                </div>
                <div>
                    <div style="display:inline-block;padding:8px 22px;background:{{ $zc['badge'] }};color:white;border-radius:30px;font-size:.875rem;font-weight:700;letter-spacing:.04em;margin-bottom:.5rem">
                        {{ $zc['label'] }}
                    </div>
                    <div style="font-size:.8125rem;color:{{ $zc['text'] }};opacity:.8">
                        @if($cat==='safe') Kondisi keuangan sehat
                        @elseif($cat==='grey') Perlu perhatian khusus
                        @else Potensi kesulitan keuangan @endif
                    </div>
                </div>
            </div>

            {{-- Info Perusahaan --}}
            <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:.875rem;margin-bottom:2rem">
                @foreach([['Perusahaan',$analysis->company_name],['Bidang Usaha',$analysis->business_field],['Periode',$analysis->period],['Mata Uang',$analysis->currency]] as [$l,$v])
                <div style="background:#F8FAFF;border-radius:8px;padding:.875rem">
                    <div style="font-size:.7rem;color:#64748B;font-weight:600;margin-bottom:3px;text-transform:uppercase;letter-spacing:.04em">{{ $l }}</div>
                    <div style="font-size:.875rem;font-weight:700;color:#1E293B">{{ $v }}</div>
                </div>
                @endforeach
            </div>

            {{-- Komponen X1-X5 --}}
            <div style="margin-bottom:2rem">
                <div style="font-size:.8rem;font-weight:700;color:#64748B;text-transform:uppercase;letter-spacing:.04em;border-bottom:1px solid #E2E8F0;padding-bottom:.5rem;margin-bottom:1rem">Komponen Z'-Score</div>
                <div style="display:grid;grid-template-columns:repeat(5,1fr);gap:.75rem;margin-bottom:.875rem">
                    @foreach([
                        ['X1',$zScoreComponents['x1'],'× 0.717','Modal Kerja / Total Aset'],
                        ['X2',$zScoreComponents['x2'],'× 0.847','Laba Ditahan / Total Aset'],
                        ['X3',$zScoreComponents['x3'],'× 3.107','EBIT / Total Aset'],
                        ['X4',$zScoreComponents['x4'],'× 0.420','Ekuitas / Total Utang'],
                        ['X5',$zScoreComponents['x5'],'× 0.998','Pendapatan / Total Aset'],
                    ] as [$n,$v,$w,$d])
                    <div style="background:#F8FAFF;border-radius:8px;padding:.875rem;text-align:center">
                        <div style="font-size:.8rem;font-weight:700;color:#1A56DB;margin-bottom:3px">{{ $n }}</div>
                        <div style="font-size:1.1rem;font-weight:800;color:#1E293B;font-family:monospace">{{ number_format($v,4) }}</div>
                        <div style="font-size:.65rem;color:#94A3B8;margin-top:2px">{{ $w }}</div>
                        <div style="font-size:.65rem;color:#64748B;margin-top:3px;line-height:1.3">{{ $d }}</div>
                    </div>
                    @endforeach
                </div>
                <div style="background:#F1F5F9;border-radius:8px;padding:.875rem;font-size:.8125rem;color:#475569;text-align:center">
                    Z' = 0.717({{ number_format($zScoreComponents['x1'],4) }}) + 0.847({{ number_format($zScoreComponents['x2'],4) }}) + 3.107({{ number_format($zScoreComponents['x3'],4) }}) + 0.420({{ number_format($zScoreComponents['x4'],4) }}) + 0.998({{ number_format($zScoreComponents['x5'],4) }})
                    = <strong style="color:#1A56DB">{{ number_format($analysis->z_score,4) }}</strong>
                </div>
            </div>

            {{-- Detail Keuangan --}}
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;margin-bottom:2rem">
                <div>
                    <div style="font-size:.8rem;font-weight:700;color:#1E293B;border-bottom:1px solid #E2E8F0;padding-bottom:.5rem;margin-bottom:.75rem">Neraca</div>
                    <table style="width:100%;font-size:.875rem;border-collapse:collapse">
                        @foreach([
                            ['Aset Lancar',$fd['aset_lancar']??0,false,''],
                            ['Aset Tetap',$fd['aset_tetap']??0,false,''],
                            ['Total Aset',$fd['total_aset']??0,true,'#1A56DB'],
                            ['Utang Lancar',$fd['utang_lancar']??0,false,''],
                            ['Utang Jangka Panjang',$fd['utang_jangka_panjang']??0,false,''],
                            ['Total Utang',$fd['total_utang']??0,true,'#1A56DB'],
                            ['Nilai Buku Ekuitas',$fd['nilai_buku_ekuitas']??0,true,($fd['nilai_buku_ekuitas']??0)<0?'#DC2626':'#1A56DB'],
                        ] as [$l,$v,$b,$c])
                        <tr style="{{ $b?'background:#F8FAFF;':'' }}">
                            <td style="padding:6px 8px;color:{{ $b?'#1E293B':'#475569' }};font-weight:{{ $b?'700':'400' }}">{{ $l }}</td>
                            <td style="padding:6px 8px;text-align:right;font-weight:{{ $b?'700':'400' }};color:{{ $v<0?'#DC2626':($b?$c:'#1E293B') }}">{{ $fmt($v) }}</td>
                        </tr>
                        @endforeach
                    </table>
                </div>
                <div>
                    <div style="font-size:.8rem;font-weight:700;color:#1E293B;border-bottom:1px solid #E2E8F0;padding-bottom:.5rem;margin-bottom:.75rem">Laba Rugi</div>
                    <table style="width:100%;font-size:.875rem;border-collapse:collapse">
                        @foreach([
                            ['Pendapatan',$fd['pendapatan']??0,false,''],
                            ['Biaya Operasional',$fd['biaya_operasional']??0,false,''],
                            ['Laba Sebelum Pajak',$fd['laba_sebelum_pajak']??0,true,($fd['laba_sebelum_pajak']??0)<0?'#DC2626':'#7C3AED'],
                            ['Pengambilan Pribadi (Prive)',$fd['prive']??0,false,''],
                            ['Laba Ditahan',$fd['laba_ditahan']??0,true,($fd['laba_ditahan']??0)<0?'#DC2626':'#7C3AED'],
                        ] as [$l,$v,$b,$c])
                        <tr style="{{ $b?'background:#F8FAFF;':'' }}">
                            <td style="padding:6px 8px;color:{{ $b?'#1E293B':'#475569' }};font-weight:{{ $b?'700':'400' }}">{{ $l }}</td>
                            <td style="padding:6px 8px;text-align:right;font-weight:{{ $b?'700':'400' }};color:{{ $v<0?'#DC2626':($b?$c:'#1E293B') }}">{{ $fmt($v) }}</td>
                        </tr>
                        @endforeach
                    </table>
                </div>
            </div>

            {{-- Rekomendasi --}}
            <div style="border-left:4px solid {{ $cat==='safe'?'#10B981':($cat==='grey'?'#F59E0B':'#EF4444') }};padding:1rem 1.25rem;background:#F8FAFF;border-radius:0 8px 8px 0;margin-bottom:2rem">
                <div style="font-size:.8rem;font-weight:700;color:#64748B;text-transform:uppercase;letter-spacing:.04em;margin-bottom:.75rem">Rekomendasi</div>
                <ul style="list-style:disc;padding-left:1.25rem;display:flex;flex-direction:column;gap:4px">
                    @if($cat==='safe')
                        @foreach(['Pertahankan rasio likuiditas yang baik','Terus optimalkan efisiensi operasional','Pertimbangkan ekspansi bisnis yang terencana','Jaga struktur modal yang sehat'] as $r)
                        <li style="font-size:.875rem;color:#1E293B">{{ $r }}</li>
                        @endforeach
                    @elseif($cat==='grey')
                        @foreach(['Evaluasi dan efisiensi biaya operasional','Tingkatkan pendapatan melalui strategi pemasaran','Kelola utang dengan hati-hati','Perkuat modal kerja perusahaan'] as $r)
                        <li style="font-size:.875rem;color:#1E293B">{{ $r }}</li>
                        @endforeach
                    @else
                        @foreach(['Segera lakukan restrukturisasi keuangan','Konsultasikan dengan konsultan keuangan profesional','Kurangi utang dan negosiasikan ulang syarat pembayaran','Cari sumber pendanaan baru atau investor'] as $r)
                        <li style="font-size:.875rem;color:#1E293B">{{ $r }}</li>
                        @endforeach
                    @endif
                </ul>
            </div>

            {{-- Footer Laporan --}}
            <div style="padding-top:1rem;border-top:1px solid #E2E8F0;display:flex;justify-content:space-between;align-items:center;font-size:.75rem;color:#94A3B8;flex-wrap:wrap;gap:.5rem">
                <span>FIN-ANALYSIS PRO &mdash; {{ $analysis->created_at->format('d F Y, H:i') }}</span>
                <span>Metode: Altman Z'-Score (Modified)</span>
            </div>
        </div>
    </div>

    {{-- Export Options --}}
    <div class="no-print" style="display:grid;grid-template-columns:repeat(3,1fr);gap:1rem;margin-top:1.5rem">
        <div class="card" style="padding:1.25rem">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:.625rem">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#DC2626" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
                <span style="font-weight:700;color:#1E293B">Unduh PDF</span>
            </div>
            <p style="font-size:.8125rem;color:#64748B;margin-bottom:1rem">Unduh laporan format PDF siap cetak.</p>
            <a href="{{ route('report.download', $analysis->id) }}" class="btn btn-primary btn-sm" style="width:100%;justify-content:center">Unduh PDF</a>
        </div>
        <div class="card" style="padding:1.25rem">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:.625rem">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#059669" stroke-width="2"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
                <span style="font-weight:700;color:#1E293B">Cetak</span>
            </div>
            <p style="font-size:.8125rem;color:#64748B;margin-bottom:1rem">Cetak langsung dari browser.</p>
            <button onclick="window.print()" class="btn btn-secondary btn-sm" style="width:100%;justify-content:center">Cetak Laporan</button>
        </div>
        <div class="card" style="padding:1.25rem">
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:.625rem">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#7C3AED" stroke-width="2"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                <span style="font-weight:700;color:#1E293B">Kirim Email</span>
            </div>
            <p style="font-size:.8125rem;color:#64748B;margin-bottom:1rem">Kirim laporan ke email tertentu.</p>
            <button onclick="document.getElementById('emailModal').style.display='flex'" class="btn btn-secondary btn-sm" style="width:100%;justify-content:center">Kirim Email</button>
        </div>
    </div>
</div>

{{-- Email Modal --}}
<div id="emailModal" style="display:none;position:fixed;inset:0;z-index:200;align-items:center;justify-content:center;background:rgba(0,0,0,.5)">
    <div style="background:white;border-radius:16px;padding:2rem;width:100%;max-width:440px;margin:1rem">
        <div style="font-size:1.125rem;font-weight:700;color:#1E293B;margin-bottom:1.25rem">Kirim Laporan via Email</div>
        <div class="form-group">
            <label class="form-label">Alamat Email <span class="required" style="color:#DC2626">*</span></label>
            <input type="email" id="emailTo" class="form-control" placeholder="contoh@email.com" style="border:1px solid #e2e8f0">
        </div>
        <div class="form-group">
            <label class="form-label">Pesan (Opsional)</label>
            <textarea id="emailMsg" class="form-control" rows="3" placeholder="Pesan tambahan..." style="border:1px solid #e2e8f0"></textarea>
        </div>
        <div style="display:flex;gap:.75rem;margin-top:1.25rem">
            <button onclick="closeEmailModal()" class="btn btn-secondary" style="flex:1">Batal</button>
            <button onclick="sendEmailReport({{ $analysis->id }})" class="btn btn-primary" style="flex:1">Kirim</button>
        </div>
        <div id="emailStatus" style="margin-top:1rem;font-size:.875rem;display:none"></div>
    </div>
</div>

@push('scripts')
<script>
function closeEmailModal() {
    document.getElementById('emailModal').style.display = 'none';
    document.getElementById('emailTo').value = '';
    document.getElementById('emailMsg').value = '';
    document.getElementById('emailStatus').style.display = 'none';
}

function sendEmailReport(id) {
    const email = document.getElementById('emailTo').value.trim();
    const message = document.getElementById('emailMsg').value.trim();
    const statusEl = document.getElementById('emailStatus');
    
    // Validasi email
    if (!email) {
        statusEl.innerHTML = '<span style="color:#ef4444">❌ Email harus diisi</span>';
        statusEl.style.display = 'block';
        return;
    }
    
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        statusEl.innerHTML = '<span style="color:#ef4444">❌ Format email tidak valid</span>';
        statusEl.style.display = 'block';
        return;
    }
    
    // Show loading state
    statusEl.innerHTML = '<span style="color:#64748b">⏳ Mengirim laporan...</span>';
    statusEl.style.display = 'block';
    
    // Send email
    fetch(`/report/${id}/email`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: JSON.stringify({
            email: email,
            message: message
        })
    })
    .then(response => {
        // Check if response is ok
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        return response.json();
    })
    .then(data => {
        if (data.success) {
            statusEl.innerHTML = '<span style="color:#059669">✅ Laporan berhasil dikirim ke ' + email + '</span>';
            setTimeout(() => {
                closeEmailModal();
            }, 2000);
        } else {
            statusEl.innerHTML = '<span style="color:#ef4444">❌ ' + (data.message || 'Gagal mengirim email') + '</span>';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        statusEl.innerHTML = '<span style="color:#ef4444">❌ Terjadi kesalahan: ' + error.message + '</span>';
    });
}

document.addEventListener('keydown', e => {
    if (e.key === 'Escape' && document.getElementById('emailModal').style.display === 'flex') {
        closeEmailModal();
    }
});
</script>
@endpush
@endsection