@extends('layouts.app')

@section('title', 'Investments')
@section('page-title', 'Investments')
@section('page-subtitle', 'Investment products, member investments, returns, and maturity tracking')

@section('content')
@php
    $canManageInvestments = auth()->user()->hasPermission('investments.manage');
    $canApproveInvestments = auth()->user()->hasPermission('investments.approve');
    $money = fn ($amount) => $currency.' '.number_format((float) $amount, 2);
    $investmentMetricCards = [
        ['Investment products', number_format($products->count()), 'Configured investment offers', 'bi-sliders', 'teal'],
        ['Total invested', $money($totalInvested), 'Principal opened', 'bi-piggy-bank', 'green'],
        ['Maturing soon', number_format($maturingSoon), 'Next 30 days', 'bi-calendar2-check', 'amber'],
    ];
    $productPayload = $products->map(fn ($product) => [
        'id' => $product->id,
        'name' => $product->name,
        'description' => $product->description,
        'investment_number_prefix' => $product->investment_number_prefix,
        'interest_rate' => $product->interest_rate,
        'return_type' => $product->return_type,
        'term_value' => $product->term_value,
        'term_unit' => $product->term_unit,
        'minimum_amount' => $product->minimum_amount,
        'maximum_amount' => $product->maximum_amount,
        'allow_member_request' => $product->allow_member_request ? '1' : '0',
        'show_on_member_portal' => $product->show_on_member_portal ? '1' : '0',
        'show_on_public_website' => $product->show_on_public_website ? '1' : '0',
        'is_active' => $product->is_active ? '1' : '0',
        'update_route' => route('tenant.investment-products.update', $product),
        'delete_route' => route('tenant.investment-products.destroy', $product),
    ])->values();
@endphp

@if($errors->any())
    <div class="alert alert-warning border-0">{{ $errors->first() }}</div>
@endif

<section class="finance-hero finance-hero-investments mb-4">
    <div class="finance-hero-copy">
        <span>Investment center</span>
        <h2>Offer fixed investments, returns, and maturity tracking.</h2>
        <p>Open member investments, preview returns, monitor maturity dates, and control which products members can request from their portal.</p>
    </div>
    <div class="finance-metric-grid">
        @foreach($investmentMetricCards as [$label, $value, $hint, $icon, $tone])
            <div class="finance-metric-card {{ $tone }}">
                <i class="bi {{ $icon }}"></i>
                <span>{{ $label }}</span>
                <strong>{{ $value }}</strong>
                <small>{{ $hint }}</small>
            </div>
        @endforeach
    </div>
</section>

<div class="card border-0 shadow-sm investment-workspace finance-workspace">
    <div class="finance-tabbar">
        <ul class="nav nav-pills finance-tabs" role="tablist">
            <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#investment-accounts" type="button"><i class="bi bi-piggy-bank me-1"></i> Accounts</button></li>
            @if($canManageInvestments)
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#open-investment" type="button"><i class="bi bi-plus-circle me-1"></i> Open investment</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#investment-products" type="button"><i class="bi bi-sliders me-1"></i> Products</button></li>
            @endif
        </ul>
    </div>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="investment-accounts">
            <div class="finance-pane-title">
                <div>
                    <span>Accounts</span>
                    <h3>Investment register</h3>
                    <p>Track principal, balance, maturity date, product, and account status.</p>
                </div>
            </div>
            @if($canApproveInvestments && $pendingInvestmentDeposits->isNotEmpty())
                <div class="p-3 pt-0">
                    <div class="pending-review-card">
                        <div class="pending-review-head">
                            <div>
                                <span>Pending deposits</span>
                                <strong>{{ $pendingInvestmentDeposits->count() }} investment deposit{{ $pendingInvestmentDeposits->count() === 1 ? '' : 's' }} waiting</strong>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table mb-0 align-middle">
                                <thead><tr><th>Member</th><th>Investment</th><th>Initiated by</th><th class="text-end">Amount</th><th></th></tr></thead>
                                <tbody>
                                    @foreach($pendingInvestmentDeposits as $transaction)
                                        <tr>
                                            <td>{{ $transaction->customer?->fullName() }}</td>
                                            <td>{{ $transaction->account?->account_number }}</td>
                                            <td>{{ $transaction->creator?->name ?? 'System / member' }}</td>
                                            <td class="text-end fw-semibold">{{ $money($transaction->amount) }}</td>
                                            <td class="text-end">
                                                <div class="dropdown">
                                                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                        <li><button class="dropdown-item" type="button" data-bs-toggle="modal" data-bs-target="#investmentPendingDeposit{{ $transaction->id }}"><i class="bi bi-eye me-2"></i>View</button></li>
                                                        <li>
                                                            <form method="POST" action="{{ route('tenant.investments.transactions.approve', $transaction) }}">
                                                                @csrf
                                                                <button class="dropdown-item text-success" type="submit"><i class="bi bi-check2-circle me-2"></i>Approve</button>
                                                            </form>
                                                        </li>
                                                        <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="modal" data-bs-target="#investmentPendingDeposit{{ $transaction->id }}"><i class="bi bi-x-circle me-2"></i>Reject</button></li>
                                                    </ul>
                                                </div>
                                            </td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        @foreach($pendingInvestmentDeposits as $transaction)
                            <div class="modal fade" id="investmentPendingDeposit{{ $transaction->id }}" tabindex="-1" aria-labelledby="investmentPendingDeposit{{ $transaction->id }}Label" aria-hidden="true">
                                <div class="modal-dialog modal-dialog-centered modal-lg">
                                    <div class="modal-content border-0 shadow">
                                        <div class="modal-header">
                                            <div>
                                                <h2 class="modal-title h5" id="investmentPendingDeposit{{ $transaction->id }}Label">Investment deposit details</h2>
                                                <div class="text-muted small">{{ $transaction->reference }}</div>
                                            </div>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="row g-3">
                                                <div class="col-md-4"><div class="detail-tile"><span>Member</span><strong>{{ $transaction->customer?->fullName() }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Member account</span><strong>{{ $transaction->customer?->account_number ?? '-' }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Investment account</span><strong>{{ $transaction->account?->account_number ?? '-' }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Amount</span><strong>{{ $money($transaction->amount) }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Method</span><strong>{{ ucfirst($transaction->method) }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Status</span><strong>{{ ucfirst($transaction->status ?? 'pending') }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Initiated by</span><strong>{{ $transaction->creator?->name ?? 'System / member' }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Approved by</span><strong>{{ $transaction->approver?->name ?? 'Not approved yet' }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Date</span><strong>{{ app_datetime($transaction->transacted_at) ?? '-' }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Balance before</span><strong>{{ $money($transaction->balance_before) }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Balance after approval</span><strong>{{ $money((float) $transaction->balance_before + (float) $transaction->amount) }}</strong></div></div>
                                                <div class="col-md-4"><div class="detail-tile"><span>Reference</span><strong>{{ $transaction->reference }}</strong></div></div>
                                                <div class="col-12">
                                                    <div class="detail-tile">
                                                        <span>Narration</span>
                                                        <strong>{{ $transaction->description ?: 'No narration supplied.' }}</strong>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                                            <form method="POST" action="{{ route('tenant.investments.transactions.approve', $transaction) }}">
                                                @csrf
                                                <button class="btn btn-success btn-sm">Approve deposit</button>
                                            </form>
                                            <form method="POST" action="{{ route('tenant.investments.transactions.reject', $transaction) }}" class="pending-modal-reject">
                                                @csrf
                                                <input name="rejected_reason" class="form-control form-control-sm" placeholder="Reason for rejection" required>
                                                <button class="btn btn-outline-danger btn-sm">Reject</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif
            <div class="table-responsive finance-table-shell">
                <table class="table align-middle mb-0 finance-table">
                    <thead><tr><th>Investment</th><th>Member</th><th>Product</th><th>Maturity</th><th class="text-end">Principal</th><th class="text-end">Balance</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                        @forelse($accounts as $account)
                            <tr>
                                <td><span class="finance-id-pill">{{ $account->account_number }}</span><div class="small text-muted mt-1">Opened {{ app_date($account->opened_at) ?? '-' }}</div></td>
                                <td>{{ $account->customer?->fullName() }}<div class="small text-muted">{{ $account->customer?->account_number }}</div></td>
                                <td>{{ $account->product_name }}</td>
                                <td>{{ app_date($account->maturity_date) ?? '-' }}</td>
                                <td class="text-end">{{ $money($account->amount) }}</td>
                                <td class="text-end">{{ $money($account->balance) }}</td>
                                <td><span class="finance-soft-badge status-{{ $account->status }}">{{ ucfirst(str_replace('_', ' ', $account->status)) }}</span></td>
                                <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="{{ route('tenant.investments.show', $account) }}">Open</a></td>
                            </tr>
                        @empty
                            <tr><td colspan="8" class="text-center text-muted py-5">No investment accounts yet.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            <div class="p-3">{{ $accounts->links() }}</div>
        </div>

        @if($canManageInvestments)
            <div class="tab-pane fade" id="open-investment">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-lg-7">
                        <div class="investment-section-title finance-section-title">
                            <h2>Open member investment</h2>
                            <p>Select a member, choose an investment product, and the system will calculate expected return and maturity date.</p>
                        </div>
                        <form method="POST" action="{{ route('tenant.investments.accounts.store') }}" class="row g-3 finance-form-panel" data-open-investment-form>
                            @csrf
                            <div class="col-md-6">
                                <label class="form-label">Member</label>
                                <select name="customer_id" class="form-select" required>
                                    <option value="">Select member</option>
                                    @foreach($customers as $customer)
                                        <option value="{{ $customer->id }}">{{ $customer->fullName() }} - {{ $customer->account_number }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Product</label>
                                <select name="investment_product_id" class="form-select" required data-open-investment-product>
                                    <option value="">Select product</option>
                                    @foreach($products->where('is_active', true) as $product)
                                        <option value="{{ $product->id }}">{{ $product->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Amount</label>
                                <input name="amount" type="number" step="0.01" min="0.01" class="form-control" required data-investment-amount>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Start date</label>
                                <input name="start_date" type="date" value="{{ today()->toDateString() }}" class="form-control" data-investment-start-date>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Auto rollover</label>
                                <select name="auto_rollover" class="form-select">
                                    <option value="0">No</option>
                                    <option value="1">Yes</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <div class="investment-preview" data-investment-preview>Select a product and amount to preview the maturity date and expected return.</div>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Notes</label>
                                <textarea name="notes" rows="3" class="form-control"></textarea>
                            </div>
                            <div class="col-12">
                                <button class="btn btn-primary"><i class="bi bi-send-check me-1"></i> Open investment</button>
                            </div>
                        </form>
                    </div>
                    <div class="col-lg-5">
                        <div class="investment-side-panel finance-guide-card">
                            <span>Flow</span>
                            <h3>How it works</h3>
                            <div class="finance-guide-list">
                                <div><i class="bi bi-sliders"></i><strong>Configure</strong><p>Set prefix, return rate, minimum amount, and maturity term.</p></div>
                                <div><i class="bi bi-person-plus"></i><strong>Open</strong><p>Open an investment for a member. The ID starts with the product prefix.</p></div>
                                <div><i class="bi bi-receipt"></i><strong>Post activity</strong><p>Record deposits, returns, withdrawals, or maturity payout from the detail page.</p></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="investment-products">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-lg-5">
                        <div class="investment-product-editor finance-editor-card">
                            <div class="d-flex justify-content-between gap-2 align-items-start mb-3">
                                <div>
                                    <div class="small text-primary fw-bold text-uppercase">Product setup</div>
                                    <h2 class="h5 mb-1">Investment products</h2>
                                    <div class="text-muted small">Create fixed investments, cooperative shares, and other member investment plans.</div>
                                </div>
                                <button class="btn btn-sm btn-dark" type="button" data-investment-product-new><i class="bi bi-plus-lg"></i></button>
                            </div>

                            <label class="form-label">Product to manage</label>
                            <select class="form-select mb-3" data-investment-product-selector>
                                <option value="">Create new product</option>
                                @foreach($products as $product)
                                    <option value="{{ $product->id }}">{{ $product->name }} {{ $product->is_active ? '' : '(inactive)' }}</option>
                                @endforeach
                            </select>

                            <form method="POST" action="{{ route('tenant.investment-products.store') }}" class="vstack gap-3" data-investment-product-form>
                                @csrf
                                <input type="hidden" name="_method" value="PATCH" data-investment-product-method disabled>
                                <div class="investment-product-section finance-product-section">
                                    <div class="investment-product-section-title"><i class="bi bi-pencil-square"></i><span>Basics</span></div>
                                    <label class="form-label">Product name</label>
                                    <input name="name" class="form-control" placeholder="e.g. 6 Month Fixed Investment" required>
                                    <label class="form-label mt-2">Description</label>
                                    <textarea name="description" class="form-control" rows="2"></textarea>
                                    <div class="row g-2 mt-1">
                                        <div class="col-6">
                                            <label class="form-label">ID prefix</label>
                                            <input name="investment_number_prefix" class="form-control text-uppercase" maxlength="20" pattern="[A-Za-z0-9]+" placeholder="INV">
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label">Status</label>
                                            <select name="is_active" class="form-select"><option value="1">Active</option><option value="0">Inactive</option></select>
                                        </div>
                                    </div>
                                </div>

                                <div class="investment-product-section finance-product-section">
                                    <div class="investment-product-section-title"><i class="bi bi-graph-up-arrow"></i><span>Rules</span></div>
                                    <div class="row g-2">
                                        <div class="col-6">
                                            <label class="form-label">Return rate (%)</label>
                                            <input name="interest_rate" type="number" step="0.01" min="0" value="0" class="form-control" required>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label">Return type</label>
                                            <select name="return_type" class="form-select">
                                                @foreach($returnTypes as $value => $label)
                                                    <option value="{{ $value }}">{{ $label }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label">Term</label>
                                            <input name="term_value" type="number" min="1" value="6" class="form-control" required>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label">Term unit</label>
                                            <select name="term_unit" class="form-select">
                                                @foreach($termUnits as $value => $label)
                                                    <option value="{{ $value }}">{{ $label }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label">Min amount</label>
                                            <input name="minimum_amount" type="number" step="0.01" min="0" value="0" class="form-control" required>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label">Max amount</label>
                                            <input name="maximum_amount" type="number" step="0.01" min="0" value="0" class="form-control" required>
                                        </div>
                                    </div>
                                </div>

                                <div class="investment-product-section finance-product-section">
                                    <div class="investment-product-section-title"><i class="bi bi-eye"></i><span>Visibility</span></div>
                                    <div class="row g-2">
                                        <div class="col-4"><label class="form-label">Requests</label><select name="allow_member_request" class="form-select"><option value="1">Allow</option><option value="0">Block</option></select></div>
                                        <div class="col-4"><label class="form-label">Portal</label><select name="show_on_member_portal" class="form-select"><option value="1">Show</option><option value="0">Hide</option></select></div>
                                        <div class="col-4"><label class="form-label">Website</label><select name="show_on_public_website" class="form-select"><option value="1">Show</option><option value="0">Hide</option></select></div>
                                    </div>
                                </div>

                                <div class="d-flex flex-wrap gap-2">
                                    <button class="btn btn-primary flex-grow-1" data-investment-product-submit>Save product</button>
                                    <button class="btn btn-outline-danger" type="submit" form="deleteInvestmentProductForm" data-investment-product-delete disabled>Delete / disable</button>
                                </div>
                            </form>
                            <form method="POST" id="deleteInvestmentProductForm" data-investment-product-delete-form>
                                @csrf
                                @method('DELETE')
                            </form>
                        </div>
                    </div>

                    <div class="col-lg-7">
                        <div class="row g-3">
                            @forelse($products as $product)
                                <div class="col-md-6">
                                    <div class="investment-product-card finance-product-card">
                                        <div class="d-flex justify-content-between gap-2">
                                            <div>
                                                <div class="fw-semibold">{{ $product->name }}</div>
                                                <div class="small text-muted">{{ $product->termLabel() }} | {{ $product->returnTypeLabel() }}</div>
                                            </div>
                                            <span class="badge {{ $product->is_active ? 'text-bg-success' : 'text-bg-secondary' }}">{{ $product->is_active ? 'Active' : 'Inactive' }}</span>
                                        </div>
                                        <p>{{ $product->description ?: 'Investment product configured for this tenant.' }}</p>
                                        <div class="small text-muted">ID starts with: <strong>{{ $product->investment_number_prefix ?: 'INV' }}</strong></div>
                                        <div class="small text-muted mt-1">Rate: {{ $product->interest_rate }}% | Min: {{ $money($product->minimum_amount) }} @if((float) $product->maximum_amount > 0) | Max: {{ $money($product->maximum_amount) }} @endif</div>
                                        <div class="d-flex flex-wrap gap-1 mt-2">
                                            <span class="badge {{ $product->allow_member_request ? 'text-bg-info' : 'text-bg-light text-dark' }}">Member {{ $product->allow_member_request ? 'can request' : 'blocked' }}</span>
                                            <span class="badge {{ $product->show_on_member_portal ? 'text-bg-primary' : 'text-bg-light text-dark' }}">Portal {{ $product->show_on_member_portal ? 'shown' : 'hidden' }}</span>
                                            <span class="badge {{ $product->show_on_public_website ? 'text-bg-dark' : 'text-bg-light text-dark' }}">Website {{ $product->show_on_public_website ? 'shown' : 'hidden' }}</span>
                                        </div>
                                    </div>
                                </div>
                            @empty
                                <div class="col-12"><div class="text-muted">No investment products yet.</div></div>
                            @endforelse
                        </div>
                    </div>
                </div>
            </div>
        @endif
    </div>
</div>

<style>
.investment-metric-card,
.investment-product-editor,
.investment-product-card,
.investment-side-panel {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #fff;
    box-shadow: 0 .5rem 1rem rgba(15, 23, 42, .04);
}
.investment-metric-card {
    min-height: 96px;
    padding: 1rem;
}
.investment-metric-card span {
    display: block;
    color: #64748b;
    font-size: .82rem;
}
.investment-metric-card strong {
    display: block;
    margin-top: .35rem;
    font-size: 1.18rem;
}
.investment-section-title h2,
.investment-side-panel h3 {
    font-size: 1.05rem;
}
.investment-section-title p,
.investment-product-card p {
    color: #64748b;
}
.investment-preview {
    border: 1px dashed #0d6efd;
    border-radius: 8px;
    padding: .9rem;
    background: #eff6ff;
    color: #1e3a8a;
}
.investment-side-panel {
    padding: 1.1rem;
}
.investment-side-panel .vstack div {
    display: flex;
    gap: .75rem;
}
.investment-side-panel span {
    width: 28px;
    height: 28px;
    display: inline-grid;
    place-items: center;
    border-radius: 50%;
    background: #0d6efd;
    color: #fff;
    font-weight: 700;
    flex: 0 0 auto;
}
.investment-side-panel p {
    margin: 0;
    color: #64748b;
}
.investment-product-editor,
.investment-product-card {
    padding: 1rem;
}
.investment-product-section {
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: .9rem;
}
.investment-product-section-title {
    display: flex;
    align-items: center;
    gap: .5rem;
    margin-bottom: .75rem;
    color: #0d6efd;
    font-weight: 700;
}
.pending-review-card {
    border: 1px solid #fde68a;
    border-radius: 8px;
    overflow: hidden;
    background: #fffbeb;
}
.pending-review-head {
    display: flex;
    justify-content: space-between;
    padding: .85rem 1rem;
    border-bottom: 1px solid #fde68a;
}
.pending-review-head span {
    display: block;
    color: #92400e;
    font-size: .78rem;
    font-weight: 800;
    text-transform: uppercase;
}
.pending-review-head strong {
    color: #451a03;
}
.detail-tile {
    height: 100%;
    padding: .8rem;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #f8fafc;
}
.detail-tile span {
    display: block;
    margin-bottom: .25rem;
    color: #64748b;
    font-size: .76rem;
    font-weight: 800;
    text-transform: uppercase;
}
.detail-tile strong {
    display: block;
    color: #172033;
    font-size: .92rem;
    font-weight: 800;
    overflow-wrap: anywhere;
}
.pending-modal-reject {
    display: grid;
    grid-template-columns: minmax(220px, 1fr) auto;
    gap: .5rem;
    align-items: center;
    min-width: min(100%, 420px);
}
@media (max-width: 767.98px) {
    .pending-modal-reject {
        grid-template-columns: 1fr;
        align-items: stretch;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const products = @json($productPayload);
    const byId = new Map(products.map((product) => [String(product.id), product]));
    const currency = @json($currency);
    const formatMoney = (amount) => `${currency} ${Number(amount || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    const addTerm = (startDate, value, unit) => {
        const date = new Date(`${startDate}T00:00:00`);
        const amount = Number(value || 1);
        if (unit === 'days') date.setDate(date.getDate() + amount);
        else if (unit === 'weeks') date.setDate(date.getDate() + (amount * 7));
        else if (unit === 'years') date.setFullYear(date.getFullYear() + amount);
        else date.setMonth(date.getMonth() + amount);
        return date.toISOString().slice(0, 10);
    };
    const expectedReturn = (amount, rate, value, unit, type) => {
        const years = unit === 'days' ? Number(value || 1) / 365 : unit === 'weeks' ? (Number(value || 1) * 7) / 365 : unit === 'years' ? Number(value || 1) : Number(value || 1) / 12;
        if (type === 'compound') return amount * ((1 + (Number(rate || 0) / 100)) ** Math.max(years, 0)) - amount;
        return amount * (Number(rate || 0) / 100) * Math.max(years, 0);
    };

    const openProduct = document.querySelector('[data-open-investment-product]');
    const amountInput = document.querySelector('[data-investment-amount]');
    const startInput = document.querySelector('[data-investment-start-date]');
    const preview = document.querySelector('[data-investment-preview]');
    const syncPreview = () => {
        const product = byId.get(String(openProduct?.value || ''));
        const amount = Number(amountInput?.value || 0);
        if (!preview || !product || amount <= 0 || !startInput?.value) {
            if (preview) preview.textContent = 'Select a product and amount to preview the maturity date and expected return.';
            return;
        }
        const maturity = addTerm(startInput.value, product.term_value, product.term_unit);
        const returns = expectedReturn(amount, product.interest_rate, product.term_value, product.term_unit, product.return_type);
        preview.textContent = `${product.name}: maturity ${maturity}, expected return ${formatMoney(returns)}, expected total ${formatMoney(amount + returns)}.`;
    };
    openProduct?.addEventListener('change', syncPreview);
    amountInput?.addEventListener('input', syncPreview);
    startInput?.addEventListener('change', syncPreview);
    syncPreview();

    const selector = document.querySelector('[data-investment-product-selector]');
    const form = document.querySelector('[data-investment-product-form]');
    const methodInput = document.querySelector('[data-investment-product-method]');
    const newButton = document.querySelector('[data-investment-product-new]');
    const submitButton = document.querySelector('[data-investment-product-submit]');
    const deleteButton = document.querySelector('[data-investment-product-delete]');
    const deleteForm = document.querySelector('[data-investment-product-delete-form]');
    const storeRoute = @json(route('tenant.investment-products.store'));
    const setField = (name, value) => {
        const field = form?.querySelector(`[name="${name}"]`);
        if (field) field.value = value ?? '';
    };
    const resetForm = () => {
        if (!form) return;
        form.reset();
        form.action = storeRoute;
        methodInput.disabled = true;
        submitButton.textContent = 'Save product';
        deleteButton.disabled = true;
        deleteForm.removeAttribute('action');
        setField('investment_number_prefix', 'INV');
        setField('interest_rate', '0');
        setField('return_type', 'fixed');
        setField('term_value', '6');
        setField('term_unit', 'months');
        setField('minimum_amount', '0');
        setField('maximum_amount', '0');
        setField('allow_member_request', '1');
        setField('show_on_member_portal', '1');
        setField('show_on_public_website', '1');
        setField('is_active', '1');
    };
    const loadProduct = (id) => {
        const product = byId.get(String(id));
        if (!product) {
            resetForm();
            return;
        }
        form.action = product.update_route;
        methodInput.disabled = false;
        submitButton.textContent = 'Update product';
        deleteButton.disabled = false;
        deleteForm.action = product.delete_route;
        Object.entries(product).forEach(([name, value]) => setField(name, value));
    };
    selector?.addEventListener('change', (event) => loadProduct(event.target.value));
    newButton?.addEventListener('click', () => {
        if (selector) selector.value = '';
        resetForm();
    });
    resetForm();
});
</script>
@endsection
