@extends('layouts.admin')

@section('title', 'Banking Overview')

@section('page-title', 'Banking Overview')

@section('breadcrumbs')
    <span class="text-primary font-medium">Banking Overview</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Success/Error Messages -->
    @if(session('success'))
        <div class="mb-4 p-4 bg-green-50 border border-green-200 rounded-lg text-green-800">
            {{ session('success') }}
        </div>
    @endif
    @if(session('error'))
        <div class="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg text-red-800">
            {{ session('error') }}
        </div>
    @endif

    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900 text-gray-900">Banking Overview</h1>
        <a href="{{ route('admin.banking.create') }}" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
            <span class="material-symbols-outlined text-lg">add</span>
            <span>Add Bank Account</span>
        </a>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Cash In Hand</p>
                    <p class="text-2xl font-bold text-gray-900 text-gray-900 mt-1">{{ number_format($cashInHand ?? 0, 2) }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-green-600">payments</span>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Bank Balance</p>
                    <p class="text-2xl font-bold text-blue-600 mt-1">{{ number_format($bankBalance ?? 0, 2) }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-blue-600">account_balance</span>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total Accounts</p>
                    <p class="text-2xl font-bold text-gray-900 text-gray-900 mt-1">{{ $totalAccounts ?? 0 }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-purple-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-purple-600">credit_card</span>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total Balance</p>
                    <p class="text-2xl font-bold text-green-600 mt-1">{{ number_format($totalBalance ?? 0, 2) }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-green-600">account_balance_wallet</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Bank Accounts Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-6">
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex flex-col justify-between gap-4 sm:flex-row sm:items-center">
                <div>
                    <h2 class="text-lg font-bold text-gray-900">Bank Accounts</h2>
                    <p class="text-sm text-gray-500 mt-1">Manage your bank accounts for payments and transactions.</p>
                </div>
                <a href="{{ route('admin.banking.create') }}" class="flex items-center justify-center gap-2 rounded-lg bg-primary px-5 py-2.5 text-sm font-bold text-white shadow-md shadow-primary/20 transition-all hover:bg-blue-600 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2">
                    <span class="material-symbols-outlined text-[20px]">add</span>
                    <span>Add Bank Account</span>
                </a>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-3 px-4 text-xs font-semibold uppercase text-gray-500">Account Name</th>
                        <th class="py-3 px-4 text-xs font-semibold uppercase text-gray-500">Bank Name</th>
                        <th class="py-3 px-4 text-xs font-semibold uppercase text-gray-500">Account Number</th>
                        <th class="py-3 px-4 text-xs font-semibold uppercase text-gray-500">Currency</th>
                        <th class="py-3 px-4 text-xs font-semibold uppercase text-gray-500">Balance</th>
                        <th class="py-3 px-4 text-xs font-semibold uppercase text-gray-500 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($bankAccounts ?? [] as $account)
                        <tr data-account-id="{{ $account->id }}" data-account-name="{{ $account->account_name }}" data-bank-name="{{ $account->bank_name }}" data-account-number="{{ $account->account_number }}" data-routing-number="{{ $account->bank_code ?? '' }}" data-swift-code="{{ $account->swift_code ?? '' }}" data-bank-address="{{ $account->branch_address ?? '' }}" data-currency="{{ $account->currency }}" data-branch-name="{{ $account->branch_name ?? '' }}" data-opening-balance="{{ $account->opening_balance ?? 0 }}" data-is-active="{{ $account->is_active ? '1' : '0' }}" class="hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-4 text-sm text-gray-900 font-medium">{{ $account->account_name }}</td>
                            <td class="py-4 px-4 text-sm text-gray-600">{{ $account->bank_name }}</td>
                            <td class="py-4 px-4 text-sm text-gray-600 font-mono">{{ $account->account_number }}</td>
                            <td class="py-4 px-4 text-sm text-gray-600">{{ $account->currency }}</td>
                            <td class="py-4 px-4 text-sm font-medium text-gray-900">{{ \App\Models\Currency::formatAmount($account->current_balance ?? 0, $account->currency) }}</td>
                            <td class="py-4 px-4 text-right">
                                <div class="relative inline-block text-left">
                                    <button type="button" data-admin-fixed-menu-trigger="action-menu-{{ $account->id }}" onclick="adminFixedActionMenuToggle(event || window.event, 'action-menu-{{ $account->id }}')" class="flex h-8 w-8 items-center justify-center rounded-lg text-gray-400 hover:bg-primary/10 hover:text-primary transition-colors" title="More actions">
                                        <span class="material-symbols-outlined text-[18px]">more_vert</span>
                                    </button>
                                    <div id="action-menu-{{ $account->id }}" data-admin-fixed-action-menu class="hidden w-48 overflow-hidden rounded-lg border border-gray-200 bg-white shadow-lg ring-1 ring-black/5">
                                        <div class="py-1" role="menu">
                                            @if(!($account->is_default ?? false))
                                                <form method="POST" action="{{ route('admin.banking.set-default', $account->id) }}" class="block">
                                                    @csrf
                                                    <button type="submit" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors" role="menuitem">
                                                        <span class="material-symbols-outlined text-[16px] align-middle mr-2">star</span>
                                                        Make as Default
                                                    </button>
                                                </form>
                                            @else
                                                <div class="px-4 py-2 text-sm text-gray-500">
                                                    <span class="material-symbols-outlined text-[16px] align-middle mr-2 text-yellow-500">star</span>
                                                    Default Account
                                                </div>
                                            @endif
                                            <button type="button" onclick="editBankAccount({{ $account->id }})" class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors" role="menuitem">
                                                <span class="material-symbols-outlined text-[16px] align-middle mr-2">edit</span>
                                                Edit
                                            </button>
                                            @if(!($account->is_default ?? false))
                                                <button type="button" onclick="openDeleteBankAccountModal({{ $account->id }}, {{ json_encode($account->account_name) }}, {{ json_encode($account->bank_name) }})" class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors border-t border-gray-100" role="menuitem">
                                                    <span class="material-symbols-outlined text-[16px] align-middle mr-2">delete</span>
                                                    Delete
                                                </button>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6" class="py-8 px-4 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">account_balance</span>
                                <p>No bank accounts found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Balance trend (live data from bank movements + stored balances) -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between mb-2">
            <div>
                <h2 class="text-lg font-bold text-gray-900">Balance Trend</h2>
                <p class="text-xs text-gray-500 mt-1" id="balance-trend-subtitle">{{ $balanceTrend['subtitle'] ?? '' }}</p>
            </div>
            <div class="flex flex-wrap gap-2 shrink-0" role="group" aria-label="Chart period">
                <button type="button" data-balance-trend-days="30" class="balance-trend-period rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-semibold text-gray-600 hover:border-primary hover:text-primary transition-colors">30d</button>
                <button type="button" data-balance-trend-days="90" class="balance-trend-period rounded-lg border border-primary bg-primary/5 px-3 py-1.5 text-xs font-semibold text-primary transition-colors">90d</button>
                <button type="button" data-balance-trend-days="180" class="balance-trend-period rounded-lg border border-gray-200 px-3 py-1.5 text-xs font-semibold text-gray-600 hover:border-primary hover:text-primary transition-colors">6 mo</button>
            </div>
        </div>
        <div id="balance-trend-chart-wrap" class="relative h-64 w-full min-h-[16rem]">
            <canvas id="balance-trend-chart" class="max-h-64" aria-label="Balance trend chart"></canvas>
        </div>
        <div id="balance-trend-error" class="hidden h-64 flex flex-col items-center justify-center text-center text-gray-500 px-4">
            <span class="material-symbols-outlined text-4xl mb-2 block text-amber-500">warning</span>
            <p class="text-sm" id="balance-trend-error-text">Could not load chart data.</p>
        </div>
    </div>
</div>

<!-- Delete bank account confirmation -->
<div id="delete-bank-modal" data-admin-modal class="hidden fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" role="dialog" aria-modal="true" aria-labelledby="delete-bank-title">
    <div class="bg-white rounded-xl shadow-2xl border border-gray-200 max-w-md w-full overflow-hidden" onclick="event.stopPropagation()">
        <div class="p-6">
            <div class="flex items-start gap-4">
                <div class="flex-shrink-0 flex h-12 w-12 items-center justify-center rounded-full bg-red-100 ring-1 ring-red-200">
                    <span class="material-symbols-outlined text-red-600 text-2xl">delete_forever</span>
                </div>
                <div class="min-w-0 flex-1">
                    <h3 id="delete-bank-title" class="text-lg font-semibold text-gray-900">Delete bank account?</h3>
                    <p class="mt-2 text-sm text-gray-600 leading-relaxed">
                        This will permanently remove <strong id="delete-bank-account-label" class="text-gray-900"></strong> from banking. This cannot be undone.
                    </p>
                    <p class="mt-2 text-xs text-gray-500">Transactions that reference this account may need to be reviewed separately.</p>
                </div>
            </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex flex-col-reverse sm:flex-row sm:justify-end gap-2">
            <button type="button" onclick="closeDeleteBankAccountModal()" class="w-full sm:w-auto px-4 py-2.5 rounded-lg border border-gray-300 text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors">
                Cancel
            </button>
            <form id="delete-bank-account-form" method="POST" class="w-full sm:w-auto">
                @csrf
                @method('DELETE')
                <button type="submit" class="w-full sm:w-auto px-4 py-2.5 rounded-lg text-sm font-semibold text-white bg-red-600 hover:bg-red-700 border border-red-600 shadow-sm transition-colors inline-flex items-center justify-center gap-2">
                    <span class="material-symbols-outlined text-lg">delete</span>
                    Delete account
                </button>
            </form>
        </div>
    </div>
</div>

<!-- Delete success -->
<div id="delete-bank-success-modal" data-admin-modal class="hidden fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm" role="dialog" aria-modal="true" aria-labelledby="delete-bank-success-title">
    <div class="bg-white rounded-xl shadow-2xl border border-gray-200 max-w-md w-full overflow-hidden" onclick="event.stopPropagation()">
        <div class="p-6">
            <div class="flex items-start gap-4">
                <div class="flex-shrink-0 flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 ring-1 ring-emerald-200">
                    <span class="material-symbols-outlined text-emerald-600 text-2xl">check_circle</span>
                </div>
                <div class="min-w-0 flex-1">
                    <h3 id="delete-bank-success-title" class="text-lg font-semibold text-gray-900">Account removed</h3>
                    <p class="mt-2 text-sm text-gray-600" id="delete-bank-success-message"></p>
                </div>
            </div>
        </div>
        <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end">
            <button type="button" onclick="closeDeleteBankSuccessModal()" class="px-5 py-2.5 rounded-lg text-sm font-semibold text-white bg-primary hover:bg-blue-600 transition-colors">
                OK
            </button>
        </div>
    </div>
</div>

<!-- Edit Bank Account Modal -->
<div id="edit-bank-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity bg-slate-900/50 backdrop-blur-sm" onclick="document.getElementById('edit-bank-modal').classList.add('hidden')"></div>
        <div class="inline-block align-bottom bg-white rounded-xl text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <form id="edit-bank-form" method="POST">
                @csrf
                @method('PUT')
                <div class="bg-white p-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4" style="font-size: 20px;">Edit Bank Account</h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">Account Name <span class="text-red-500">*</span></label>
                            <input id="edit-account-name" name="account_name" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="Main Business Account" type="text"/>
                        </div>
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">Bank Name <span class="text-red-500">*</span></label>
                            <input id="edit-bank-name" name="bank_name" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="Bank Name" type="text"/>
                        </div>
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">Branch Name</label>
                            <input id="edit-branch-name" name="branch_name" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="Branch Name" type="text"/>
                        </div>
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">Account Number <span class="text-red-500">*</span></label>
                            <input id="edit-account-number" name="account_number" required class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="1234567890" type="text"/>
                        </div>
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">IFSC/Routing Code</label>
                            <input id="edit-routing-code" name="routing_code" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="110000000" type="text"/>
                        </div>
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">Currency</label>
                            <input id="edit-currency" name="currency" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="USD" type="text"/>
                        </div>
                        <div>
                            <label class="block text-base font-medium text-slate-700 mb-1" style="font-size: 16px;">Opening Balance</label>
                            <input id="edit-opening-balance" name="opening_balance" type="number" step="0.01" class="w-full rounded-lg border border-gray-300 bg-white px-3 py-2.5 text-gray-900 focus:border-primary focus:ring-1 focus:ring-primary" placeholder="0.00"/>
                        </div>
                        <div class="flex items-center justify-between p-4 bg-gray-50/50 rounded-lg">
                            <div>
                                <p class="text-sm font-medium text-gray-900">Active Status</p>
                                <p class="text-xs text-gray-500">Enable this account for transactions</p>
                            </div>
                            <label class="relative inline-block w-10 mr-2 align-middle select-none transition duration-200 ease-in cursor-pointer">
                                <input type="checkbox" id="edit-is-active" name="is_active" value="1" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer checked:right-0 checked:border-primary transition-all duration-300"/>
                                <span class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300"></span>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-6 py-4 flex items-center justify-end gap-3 border-t border-gray-200">
                    <button type="button" onclick="document.getElementById('edit-bank-modal').classList.add('hidden')" class="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-lg transition-colors">Cancel</button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-primary hover:bg-primary/90 rounded-lg transition-colors shadow-sm">Update Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function openDeleteBankAccountModal(id, accountName, bankName) {
        const label = (accountName || '') + (bankName ? ' — ' + bankName : '');
        document.getElementById('delete-bank-account-label').textContent = label || 'this account';
        const form = document.getElementById('delete-bank-account-form');
        form.action = @json(route('admin.banking.destroy', ['id' => '__ID__'])).replace('__ID__', id);
        if (typeof window.adminFixedActionMenuCloseAll === 'function') {
            window.adminFixedActionMenuCloseAll();
        }
        document.getElementById('delete-bank-modal').classList.remove('hidden');
        document.getElementById('delete-bank-modal').classList.add('flex');
    }

    function closeDeleteBankAccountModal() {
        const el = document.getElementById('delete-bank-modal');
        if (el) {
            el.classList.add('hidden');
            el.classList.remove('flex');
        }
    }

    function closeDeleteBankSuccessModal() {
        const el = document.getElementById('delete-bank-success-modal');
        if (el) {
            el.classList.add('hidden');
            el.classList.remove('flex');
        }
    }

    document.getElementById('delete-bank-modal')?.addEventListener('click', function (e) {
        if (e.target === this) {
            closeDeleteBankAccountModal();
        }
    });
    document.getElementById('delete-bank-success-modal')?.addEventListener('click', function (e) {
        if (e.target === this) {
            closeDeleteBankSuccessModal();
        }
    });

    function editBankAccount(accountId) {
        // Find the table row with the account data
        const row = document.querySelector(`tr[data-account-id="${accountId}"]`);
        if (!row) {
            console.error('Account row not found');
            return;
        }
        
        // Get account data from data attributes
        const accountName = row.getAttribute('data-account-name');
        const bankName = row.getAttribute('data-bank-name');
        const accountNumber = row.getAttribute('data-account-number');
        const routingCode = row.getAttribute('data-routing-number');
        const branchName = row.getAttribute('data-branch-name');
        const currency = row.getAttribute('data-currency');
        const openingBalance = row.getAttribute('data-opening-balance');
        const isActive = row.getAttribute('data-is-active') === '1';
        
        // Populate the edit form
        document.getElementById('edit-account-name').value = accountName || '';
        document.getElementById('edit-bank-name').value = bankName || '';
        document.getElementById('edit-branch-name').value = branchName || '';
        document.getElementById('edit-account-number').value = accountNumber || '';
        document.getElementById('edit-routing-code').value = routingCode || '';
        document.getElementById('edit-currency').value = currency || 'USD';
        document.getElementById('edit-opening-balance').value = openingBalance || '0';
        document.getElementById('edit-is-active').checked = isActive;
        
        // Set the form action URL
        const form = document.getElementById('edit-bank-form');
        form.action = `/admin/banking/${accountId}`;
        
        if (typeof window.adminFixedActionMenuCloseAll === 'function') {
            window.adminFixedActionMenuCloseAll();
        }

        // Show the edit modal
        document.getElementById('edit-bank-modal').classList.remove('hidden');
    }

    @if(session('bank_account_deleted'))
    document.addEventListener('DOMContentLoaded', function () {
        const modal = document.getElementById('delete-bank-success-modal');
        const msg = document.getElementById('delete-bank-success-message');
        if (modal && msg) {
            msg.textContent = @json(session('bank_account_deleted')) + ' has been deleted successfully.';
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }
    });
    @endif
</script>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js" crossorigin="anonymous"></script>
<script>
(function () {
    const initial = @json($balanceTrend ?? ['success' => false]);
    const trendUrl = @json($balanceTrendUrl ?? '');
    let chartInstance = null;

    function getPrimaryColor() {
        const v = getComputedStyle(document.documentElement).getPropertyValue('--primary').trim();
        return v || '#340080';
    }

    function formatMoney(value, currency) {
        try {
            return new Intl.NumberFormat(undefined, { style: 'currency', currency: currency || 'USD', maximumFractionDigits: 2 }).format(value);
        } catch (e) {
            return Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
    }

    function setPeriodButtonsActive(days) {
        document.querySelectorAll('.balance-trend-period').forEach(function (btn) {
            const d = parseInt(btn.getAttribute('data-balance-trend-days'), 10);
            const on = d === days;
            btn.classList.toggle('border-primary', on);
            btn.classList.toggle('bg-primary/5', on);
            btn.classList.toggle('text-primary', on);
            btn.classList.toggle('font-semibold', on);
            btn.classList.toggle('border-gray-200', !on);
            btn.classList.toggle('text-gray-600', !on);
        });
    }

    function showChartUi(show) {
        const wrap = document.getElementById('balance-trend-chart-wrap');
        const err = document.getElementById('balance-trend-error');
        if (wrap) wrap.classList.toggle('hidden', !show);
        if (err) err.classList.toggle('hidden', show);
    }

    function renderTrend(payload) {
        const canvas = document.getElementById('balance-trend-chart');
        const sub = document.getElementById('balance-trend-subtitle');
        if (!canvas) return;
        if (typeof Chart === 'undefined') {
            showChartUi(false);
            const errText = document.getElementById('balance-trend-error-text');
            if (errText) errText.textContent = 'Chart could not be loaded. Check your network connection.';
            return;
        }

        if (!payload || !payload.success || !payload.labels || !payload.values || payload.labels.length === 0) {
            if (sub && payload && payload.subtitle) sub.textContent = payload.subtitle;
            showChartUi(false);
            const errText = document.getElementById('balance-trend-error-text');
            if (errText) errText.textContent = (payload && payload.subtitle) ? payload.subtitle : 'No data to display yet.';
            return;
        }

        showChartUi(true);
        if (sub) sub.textContent = payload.subtitle || '';

        if (chartInstance) {
            chartInstance.destroy();
            chartInstance = null;
        }

        const primary = getPrimaryColor();
        const fillRgba = (function (hex) {
            const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
            if (!m) return 'rgba(52, 0, 128, 0.14)';
            return 'rgba(' + parseInt(m[1], 16) + ',' + parseInt(m[2], 16) + ',' + parseInt(m[3], 16) + ',0.14)';
        })(primary);
        chartInstance = new Chart(canvas.getContext('2d'), {
            type: 'line',
            data: {
                labels: payload.labels,
                datasets: [{
                    label: 'Balance',
                    data: payload.values,
                    borderColor: primary,
                    backgroundColor: fillRgba,
                    fill: true,
                    tension: 0.35,
                    pointRadius: 0,
                    pointHitRadius: 8,
                    borderWidth: 2,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function (ctx) {
                                return formatMoney(ctx.parsed.y, payload.currency);
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        grid: { display: false },
                        ticks: { maxTicksLimit: 8, font: { size: 11 } }
                    },
                    y: {
                        border: { display: false },
                        ticks: {
                            font: { size: 11 },
                            callback: function (v) {
                                return formatMoney(v, payload.currency);
                            }
                        }
                    }
                }
            }
        });
    }

    function loadTrend(days) {
        setPeriodButtonsActive(days);
        if (!trendUrl) {
            renderTrend(initial);
            return;
        }
        const url = trendUrl + (trendUrl.indexOf('?') >= 0 ? '&' : '?') + 'days=' + encodeURIComponent(days);
        fetch(url, { headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' } })
            .then(function (r) { return r.json(); })
            .then(function (data) { renderTrend(data); })
            .catch(function () {
                showChartUi(false);
                const errText = document.getElementById('balance-trend-error-text');
                if (errText) errText.textContent = 'Could not load chart data. Try again.';
            });
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('.balance-trend-period').forEach(function (btn) {
            btn.addEventListener('click', function () {
                const d = parseInt(btn.getAttribute('data-balance-trend-days'), 10);
                if (!isNaN(d)) loadTrend(d);
            });
        });
        renderTrend(initial);
        setPeriodButtonsActive(initial.days || 90);
    });
})();
</script>
@endpush




