@extends('layouts.app')

@section('title', 'Member Portal')
@section('page-title', 'Member Portal')
@section('page-subtitle', $customer->account_number)

@section('content')
@php
    $currency = $customer->tenant->settings['currency'] ?? 'NGN';
    $overview = $accountOverview;
    $locked = $customer->identityFieldsLocked();
    $activeLoans = $customer->loans->whereIn('status', ['active', 'disbursed'])->where('balance', '>', 0);
    $activeSavingsAccounts = $customer->savingsAccounts->where('status', 'active');
    $memberTransfers = $memberTransfers ?? collect();
    $billProviders = $billPaymentProviders ?? [];
    $billPackages = $billPaymentPackages ?? [];
    $billDriver = app(\App\Services\PlatformSettings::class)->billPaymentDriver();
    $notificationChannels = \App\Services\MemberNotificationAutomationService::channels();
    $notificationPreferences = $customer->notificationPreferences();
    $selectedNotificationChannels = old('notification_channels', array_keys(array_filter($notificationPreferences)));
    $productPayload = $products->map(fn ($product) => [
        'id' => $product->id,
        'name' => $product->name,
        'interest_rate' => $product->interest_rate,
        'interest_method' => $product->interest_method,
        'repayment_frequency' => $product->repayment_frequency,
        'term_value' => $product->term_value,
        'term_unit' => match ($product->repayment_frequency) {
            'daily' => 'days',
            'weekly', 'biweekly' => 'weeks',
            'yearly' => 'years',
            default => 'months',
        },
        'minimum_amount' => $product->minimum_amount,
        'maximum_amount' => $product->maximum_amount,
        'processing_fee_type' => $product->processing_fee_type ?? 'fixed',
        'processing_fee_value' => $product->processing_fee_value ?? 0,
        'processing_fee_timing' => $product->processing_fee_timing ?? 'before_disbursement',
        'processing_fee_timing_label' => $product->processingFeeTimingLabel(),
        'guarantor_requirement' => $product->guarantor_requirement ?? 'optional',
        'collateral_requirement' => $product->collateral_requirement ?? 'optional',
    ])->values();
    $savingsProductPayload = ($savingsProducts ?? collect())->map(fn ($product) => [
        'id' => $product->id,
        'name' => $product->name,
        'type' => $product->type,
        'type_label' => $product->typeLabel(),
        'description' => $product->description,
        'minimum_opening_balance' => $product->minimum_opening_balance,
        'contribution_frequency' => $product->contribution_frequency,
        'processing_fee_type' => $product->processing_fee_type ?? 'fixed',
        'processing_fee_value' => $product->processing_fee_value ?? 0,
        'processing_fee_timing' => $product->processing_fee_timing ?? 'manual',
        'processing_fee_timing_label' => $product->processingFeeTimingLabel(),
        'duration_days' => $product->duration_days,
        'withdrawal_policy' => $product->withdrawal_policy,
    ])->values();
    $repaymentDefaults = $activeLoans->mapWithKeys(function ($loan) {
        $schedule = $loan->schedules->whereIn('status', ['pending', 'partial', 'overdue'])->sortBy('due_date')->first();

        return [$loan->id => $schedule ? max(0, (float) $schedule->total_due - (float) $schedule->paid_amount) : (float) $loan->balance];
    });
@endphp

<div class="member-portal-shell">
    <section class="member-portal-hero mb-4">
        <div class="member-bank-card">
            <div class="text-uppercase small fw-bold opacity-75">Welcome back</div>
            <h2>{{ $customer->fullName() }}</h2>
            <p class="mb-3">Save, borrow, repay, invest, pay bills, and manage your profile from one mobile banking-style portal.</p>
            <div class="member-bank-balance">
                <span>Available savings balance</span>
                <strong>{{ $currency }} {{ number_format($overview['savings_balance'], 2) }}</strong>
            </div>
        </div>
        <div class="member-portal-identity">
            <span>Member account</span>
            <strong>{{ $customer->account_number }}</strong>
            <div class="mt-2 mb-3">
                <span class="badge text-bg-light text-dark">{{ ucfirst($customer->kyc_status) }} KYC</span>
                @if($locked)<span class="badge text-bg-success">Verified fields locked</span>@endif
            </div>
            <div class="member-quick-actions">
                <a href="#member-savings"><i class="bi bi-plus-circle"></i><span>Save</span></a>
                <a href="#member-transfers"><i class="bi bi-arrow-left-right"></i><span>Transfer</span></a>
                <a href="#member-loans"><i class="bi bi-cash-coin"></i><span>Loan</span></a>
                <a href="#member-bills"><i class="bi bi-phone"></i><span>Pay bills</span></a>
            </div>
        </div>
    </section>

    <div class="row g-3 mb-4">
        <div class="col-md-3"><div class="card metric-card"><div class="card-body"><div class="text-muted small">Savings balance</div><div class="h4 mb-0">{{ $currency }} {{ number_format($overview['savings_balance'], 2) }}</div></div></div></div>
        <div class="col-md-3"><div class="card metric-card"><div class="card-body"><div class="text-muted small">Loan balance</div><div class="h4 mb-0">{{ $currency }} {{ number_format($overview['loan_balance'], 2) }}</div></div></div></div>
        <div class="col-md-3"><div class="card metric-card"><div class="card-body"><div class="text-muted small">Due now</div><div class="h4 mb-0">{{ $currency }} {{ number_format($overview['due_amount'], 2) }}</div></div></div></div>
        <div class="col-md-3"><div class="card metric-card"><div class="card-body"><div class="text-muted small">Next due</div><div class="h4 mb-0">{{ app_day_month($overview['next_due_date']) ?? '-' }}</div></div></div></div>
    </div>

    <div class="card border-0 shadow-sm member-portal-panel">
        <div class="card-header bg-white">
            <ul class="nav nav-pills member-portal-tabs" role="tablist">
                <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#member-overview" type="button"><i class="bi bi-grid me-1"></i> Overview</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#member-profile" type="button"><i class="bi bi-person me-1"></i> Profile</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="savings" data-bs-toggle="tab" data-bs-target="#member-savings" type="button"><i class="bi bi-wallet2 me-1"></i> Savings</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="transfers" data-bs-toggle="tab" data-bs-target="#member-transfers" type="button"><i class="bi bi-arrow-left-right me-1"></i> Transfers</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="loans" data-bs-toggle="tab" data-bs-target="#member-loans" type="button"><i class="bi bi-cash-coin me-1"></i> Loans</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#member-investments" type="button"><i class="bi bi-piggy-bank me-1"></i> Investments</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="bills" data-bs-toggle="tab" data-bs-target="#member-bills" type="button"><i class="bi bi-phone me-1"></i> Bills</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#member-transactions" type="button"><i class="bi bi-clock-history me-1"></i> Transactions</button></li>
            </ul>
        </div>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="member-overview">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-lg-7">
                        <div class="member-section-title">
                            <h3>Account overview</h3>
                            <p>Your active balances, next repayment, and recent movement.</p>
                        </div>
                        @include('tenant.partials.member-transaction-history', ['transactions' => $overview['transactions']->take(6), 'currency' => $currency])
                    </div>
                    <div class="col-lg-5">
                        @if($notifications->isNotEmpty())
                            <div class="member-side-panel mb-3">
                                <h3>Notifications</h3>
                                <div class="vstack gap-3">
                                    @foreach($notifications as $notification)
                                        <div>
                                            <div class="fw-semibold">{{ $notification->title }}</div>
                                            <div class="small text-muted">{{ $notification->body }}</div>
                                            <div class="small text-muted mt-1">{{ app_datetime($notification->created_at) }}</div>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @endif

                        <div class="member-side-panel">
                            <h3>Virtual account</h3>
                            @if($customer->hasActiveVirtualAccount())
                                <div class="text-muted small">Bank</div>
                                <div class="fw-semibold">{{ $customer->virtual_account_bank_name ?: '-' }}</div>
                                <div class="text-muted small mt-2">Account number</div>
                                <div class="h4 mb-0">{{ $customer->virtual_account_number }}</div>
                                <div class="text-muted small mt-2">Account name</div>
                                <div>{{ $customer->virtual_account_name ?: $customer->fullName() }}</div>
                            @else
                                <div class="text-muted small">A virtual account will appear here after the company creates one for you.</div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-profile">
                <div class="p-3 p-lg-4">
                    <div class="member-section-title">
                        <h3>Profile and KYC</h3>
                        <p>Complete your information. Once your identity is verified and approved, core identity fields are locked.</p>
                    </div>

                    @if($locked)
                        <div class="alert alert-success border-0">Your KYC has been approved. Name, DOB, gender, ID, BVN, and NIN fields are locked for safety.</div>
                    @elseif(($customer->tenant->settings['kyc_provider'] ?? 'local') === 'didit')
                        <div class="alert alert-info border-0 d-flex flex-column flex-md-row justify-content-between gap-2 align-items-md-center">
                            <div>Didit KYC is enabled for this company. Start verification after confirming your profile information.</div>
                            <form method="POST" action="{{ route('member.kyc.start') }}">
                                @csrf
                                <button class="btn btn-primary btn-sm"><i class="bi bi-shield-check me-1"></i> Start KYC</button>
                            </form>
                        </div>
                    @endif

                    <form method="POST" action="{{ route('member.profile.update') }}" class="row g-3">
                        @csrf
                        @method('PATCH')
                        <div class="col-md-4"><label class="form-label">First name</label><input name="first_name" value="{{ old('first_name', $customer->first_name) }}" class="form-control" @readonly($locked) required></div>
                        <div class="col-md-4"><label class="form-label">Middle name</label><input name="middle_name" value="{{ old('middle_name', $customer->middle_name) }}" class="form-control" @readonly($locked)></div>
                        <div class="col-md-4"><label class="form-label">Last name</label><input name="last_name" value="{{ old('last_name', $customer->last_name) }}" class="form-control" @readonly($locked) required></div>
                        <div class="col-md-4"><label class="form-label">Email</label><input name="email" type="email" value="{{ old('email', $customer->email) }}" class="form-control"></div>
                        <div class="col-md-4"><label class="form-label">Phone</label><input name="phone" value="{{ old('phone', $customer->phone) }}" class="form-control" required></div>
                        <div class="col-md-4"><label class="form-label">Occupation</label><input name="occupation" value="{{ old('occupation', $customer->occupation) }}" class="form-control"></div>
                        <div class="col-md-4">
                            <label class="form-label">Gender</label>
                            <select name="gender" class="form-select" @disabled($locked)>
                                <option value="">Select gender</option>
                                <option value="male" @selected(old('gender', $customer->gender) === 'male')>Male</option>
                                <option value="female" @selected(old('gender', $customer->gender) === 'female')>Female</option>
                            </select>
                        </div>
                        <div class="col-md-4"><label class="form-label">Date of birth</label><input name="date_of_birth" type="date" value="{{ old('date_of_birth', $customer->date_of_birth?->format('Y-m-d')) }}" class="form-control" data-date-of-birth @readonly($locked)></div>
                        <div class="col-md-4"><label class="form-label">Age</label><input value="{{ $customer->age() }}" class="form-control bg-light" data-age-field readonly></div>
                        <div class="col-md-4"><label class="form-label">ID type</label><input name="id_type" value="{{ old('id_type', $customer->id_type) }}" class="form-control" @readonly($locked)></div>
                        <div class="col-md-4"><label class="form-label">ID number</label><input name="id_number" value="{{ old('id_number', $customer->id_number) }}" class="form-control" @readonly($locked)></div>
                        <div class="col-md-4">
                            <label class="form-label">BVN @if($customer->bvn_verified_at)<span class="badge text-bg-success">Verified</span>@endif</label>
                            <div class="input-group">
                                <input name="bvn" value="{{ old('bvn', $locked ? $customer->maskedBvn() : $customer->bvn) }}" class="form-control" inputmode="numeric" maxlength="11" data-identity-number="BVN" @readonly($locked)>
                                <button class="btn btn-outline-primary" type="button" data-verify-identity="bvn" @disabled($locked)>Verify</button>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">NIN @if($customer->nin_verified_at)<span class="badge text-bg-success">Verified</span>@endif</label>
                            <div class="input-group">
                                <input name="nin" value="{{ old('nin', $locked ? $customer->maskedNin() : $customer->nin) }}" class="form-control" inputmode="numeric" maxlength="11" data-identity-number="NIN" @readonly($locked)>
                                <button class="btn btn-outline-primary" type="button" data-verify-identity="nin" @disabled($locked)>Verify</button>
                            </div>
                        </div>
                        <div class="col-md-4 d-flex align-items-end"><div class="small text-muted" data-identity-feedback>Enter 11 digits, then click Verify for an immediate check.</div></div>
                        <div class="col-12"><label class="form-label">Address</label><textarea name="address" rows="3" class="form-control">{{ old('address', $customer->address) }}</textarea></div>
                        <div class="col-md-6"><label class="form-label">City</label><input name="city" value="{{ old('city', $customer->city) }}" class="form-control"></div>
                        <div class="col-md-6"><label class="form-label">State</label><input name="state" value="{{ old('state', $customer->state) }}" class="form-control"></div>
                        <div class="col-md-6"><label class="form-label">Guarantor name</label><input name="guarantor_name" value="{{ old('guarantor_name', $customer->guarantor_name) }}" class="form-control"></div>
                        <div class="col-md-6"><label class="form-label">Guarantor phone</label><input name="guarantor_phone" value="{{ old('guarantor_phone', $customer->guarantor_phone) }}" class="form-control"></div>
                        <div class="col-md-6"><label class="form-label">Relationship</label><input name="guarantor_relationship" value="{{ old('guarantor_relationship', $customer->guarantor_relationship) }}" class="form-control"></div>
                        <div class="col-md-6"><label class="form-label">Guarantor address</label><input name="guarantor_address" value="{{ old('guarantor_address', $customer->guarantor_address) }}" class="form-control"></div>
                        <div class="col-12"><button class="btn btn-primary"><i class="bi bi-save me-1"></i> Save profile</button></div>
                    </form>

                    <div class="member-notification-preferences mt-4">
                        <div class="member-section-title">
                            <h3>Notification preferences</h3>
                            <p>Choose how you want to receive alerts. You can disable paid channels like SMS or WhatsApp anytime.</p>
                        </div>
                        <form method="POST" action="{{ route('member.notification-preferences.update') }}" class="vstack gap-3">
                            @csrf
                            @method('PATCH')
                            <div class="notification-preference-grid">
                                @foreach($notificationChannels as $channelKey => $channel)
                                    <label class="notification-preference-option">
                                        <input class="form-check-input" type="checkbox" name="notification_channels[]" value="{{ $channelKey }}" @checked(in_array($channelKey, $selectedNotificationChannels, true))>
                                        <span>
                                            <i class="bi {{ $channel['icon'] }}"></i>
                                            <strong>{{ $channel['label'] }}</strong>
                                            <small>{{ in_array($channelKey, ['sms', 'whatsapp'], true) ? 'May include charges' : 'No direct charge' }}</small>
                                        </span>
                                    </label>
                                @endforeach
                            </div>
                            <button class="btn btn-primary align-self-start" type="submit"><i class="bi bi-save me-1"></i> Save notification choices</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-savings">
                <div class="p-3 p-lg-4 pb-0">
                    <div class="member-savings-hero mb-3">
                        <div>
                            <span>Self-service savings</span>
                            <h3>Save, lock, and track your money from your portal</h3>
                            <p>Open flexible savings, target savings, thrift / Isusu, or cooperative plans by yourself. Fund active plans online and follow your progress.</p>
                        </div>
                        <div class="member-savings-hero-action">
                            <strong>{{ $currency }} {{ number_format($overview['savings_balance'], 2) }}</strong>
                            <small>Total savings balance</small>
                        </div>
                    </div>

                    @if(($savingsProducts ?? collect())->isNotEmpty())
                        <div class="member-savings-product-grid mb-1">
                            @foreach($savingsProducts as $product)
                                @php
                                    $experienceLabel = match ($product->type) {
                                        'target' => 'Target / Lock',
                                        'thrift_isusu' => 'Thrift / Isusu',
                                        'cooperative' => 'Cooperative',
                                        default => 'Flexible Save',
                                    };
                                @endphp
                                <button type="button" class="member-savings-product-card" data-member-savings-product-card value="{{ $product->id }}">
                                    <span>{{ $experienceLabel }}</span>
                                    <strong>{{ $product->name }}</strong>
                                    <small>{{ $product->withdrawalPolicyLabel() }}</small>
                                </button>
                            @endforeach
                        </div>
                    @endif
                </div>

                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-lg-7">
                        <div class="member-section-title"><h3>Savings accounts</h3><p>View balances, targets, contribution plans, and last transactions.</p></div>
                        <div class="member-savings-card-grid mb-4">
                            @forelse($customer->savingsAccounts->sortByDesc('created_at') as $account)
                                @php
                                    $goalAmount = (float) ($account->target_amount ?: $account->planned_total_amount ?: 0);
                                    $progress = $goalAmount > 0 ? min(100, round(((float) $account->balance / $goalAmount) * 100)) : null;
                                    $lastTransaction = $account->transactions->sortByDesc('transacted_at')->first();
                                    $isLocked = filled($account->locked_until) || filled($account->maturity_date);
                                @endphp
                                <article class="member-savings-plan-card">
                                    <div class="member-savings-plan-head">
                                        <div>
                                            <span>{{ $account->typeLabel() }}</span>
                                            <strong>{{ $account->product_name }}</strong>
                                            <small>{{ $account->account_number }}</small>
                                        </div>
                                        <em class="{{ $account->status === 'active' ? 'active' : '' }}">{{ ucfirst(str_replace('_', ' ', $account->status)) }}</em>
                                    </div>
                                    <div class="member-savings-plan-balance">
                                        <span>Balance</span>
                                        <strong>{{ $currency }} {{ number_format($account->balance, 2) }}</strong>
                                    </div>
                                    @if($goalAmount > 0)
                                        <div class="member-savings-progress">
                                            <div><span>{{ $progress }}%</span><small>{{ $currency }} {{ number_format(max(0, $goalAmount - (float) $account->balance), 2) }} left</small></div>
                                            <div class="member-savings-progress-bar"><span style="width: {{ $progress }}%"></span></div>
                                            <small>Goal: {{ $currency }} {{ number_format($goalAmount, 2) }}</small>
                                        </div>
                                    @elseif($account->contribution_amount)
                                        <div class="member-savings-progress neutral">
                                            <div><span>{{ $currency }} {{ number_format($account->contribution_amount, 2) }}</span><small>{{ ucfirst($account->contribution_frequency ?: 'contribution') }}</small></div>
                                            <div class="member-savings-progress-bar"><span style="width: 35%"></span></div>
                                            <small>Contribution plan</small>
                                        </div>
                                    @else
                                        <div class="member-savings-progress neutral">
                                            <div><span>Flexible</span><small>Save anytime</small></div>
                                            <div class="member-savings-progress-bar"><span style="width: 12%"></span></div>
                                            <small>No fixed goal yet</small>
                                        </div>
                                    @endif
                                    <div class="member-savings-plan-meta">
                                        <div><i class="bi {{ $isLocked ? 'bi-lock' : 'bi-unlock' }}"></i><span>{{ $isLocked ? 'Locked / maturing' : 'Flexible access' }}</span></div>
                                        <div><i class="bi bi-calendar-check"></i><span>{{ app_date($account->maturity_date, 'No maturity date') }}</span></div>
                                        <div><i class="bi bi-clock-history"></i><span>{{ app_date($lastTransaction?->transacted_at, 'No transaction yet') }}</span></div>
                                    </div>
                                </article>
                            @empty
                                <div class="member-savings-empty">
                                    <i class="bi bi-wallet2"></i>
                                    <strong>No savings plan yet</strong>
                                    <span>Choose a savings product and open your first plan.</span>
                                </div>
                            @endforelse
                        </div>
                        <div class="table-responsive">
                            <table class="table mb-0">
                                <thead><tr><th>Account</th><th>Product</th><th>Type</th><th>Status</th><th class="text-end">Balance</th><th>Last transaction</th></tr></thead>
                                <tbody>
                                    @forelse($customer->savingsAccounts as $account)
                                        <tr>
                                            <td>{{ $account->account_number }}</td>
                                            <td>
                                                <div class="fw-semibold">{{ $account->product_name }}</div>
                                                @if($account->isTargetSavings() && $account->target_amount)
                                                    <div class="small text-muted">{{ $account->targetProgressPercent() }}% of {{ $currency }} {{ number_format($account->target_amount, 2) }}</div>
                                                @elseif($account->contribution_amount)
                                                    <div class="small text-muted">{{ $currency }} {{ number_format($account->contribution_amount, 2) }} {{ $account->contribution_frequency ?: '' }}</div>
                                                @endif
                                                @if($account->planned_total_amount)
                                                    <div class="small text-muted">Plan total: {{ $currency }} {{ number_format($account->planned_total_amount, 2) }}</div>
                                                @endif
                                                @if($account->maturity_date)
                                                    <div class="small text-muted">Matures: {{ app_date($account->maturity_date) }}</div>
                                                @endif
                                                @if((float) $account->processing_fee_amount > 0)
                                                    <div class="small text-muted">Processing fee: {{ $currency }} {{ number_format($account->processing_fee_amount, 2) }}</div>
                                                @endif
                                            </td>
                                            <td><span class="badge text-bg-light text-dark">{{ $account->typeLabel() }}</span></td>
                                            <td><span class="badge {{ $account->status === 'active' ? 'text-bg-success' : ($account->status === 'pending' ? 'text-bg-warning' : 'text-bg-secondary') }}">{{ ucfirst(str_replace('_', ' ', $account->status)) }}</span></td>
                                            <td class="text-end">{{ $currency }} {{ number_format($account->balance, 2) }}</td>
                                            <td>{{ app_date($account->transactions->sortByDesc('transacted_at')->first()?->transacted_at) ?? '-' }}</td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="6" class="text-center text-muted py-4">No savings account yet.</td></tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-lg-5">
                        <div class="member-side-panel mb-3">
                            <h3>Create a savings plan</h3>
                            @if(($savingsProducts ?? collect())->isNotEmpty())
                                <form method="POST" action="{{ route('member.savings.accounts.store') }}" class="vstack gap-3" data-member-open-savings-form>
                                    @csrf
                                    <select name="savings_product_id" class="form-select" required data-member-savings-product-selector>
                                        <option value="">Select savings product</option>
                                        @foreach($savingsProducts as $product)
                                            <option value="{{ $product->id }}">{{ $product->name }}</option>
                                        @endforeach
                                    </select>
                                    <div class="alert alert-info border-0 mb-0" data-member-savings-product-summary>Select a plan to see required fields.</div>
                                    <div class="row g-2">
                                        <div class="col-md-6"><input name="start_date" type="date" value="{{ now()->toDateString() }}" class="form-control" data-member-savings-start-date></div>
                                        <div class="col-md-6 d-none" data-member-target-field><input name="target_amount" type="number" min="0.01" step="0.01" class="form-control" placeholder="Target amount"></div>
                                        <div class="col-md-6 d-none" data-member-target-field><input name="target_date" type="date" class="form-control"></div>
                                        <div class="col-md-6 d-none" data-member-contribution-field><input name="contribution_amount" type="number" min="0.01" step="0.01" class="form-control" placeholder="Contribution amount"></div>
                                        <div class="col-md-6 d-none" data-member-contribution-field><input name="contribution_periods" type="number" min="1" max="10000" class="form-control" placeholder="No. of contributions" data-member-contribution-periods></div>
                                        <div class="col-md-6 d-none" data-member-contribution-field>
                                            <select name="contribution_frequency" class="form-select">
                                                <option value="">Use product frequency</option>
                                                @foreach($savingsContributionFrequencies as $value => $label)
                                                    <option value="{{ $value }}">{{ $label }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="col-md-6 d-none" data-member-plan-preview-field><input class="form-control bg-light" readonly data-member-maturity-preview placeholder="Maturity date"></div>
                                        <div class="col-md-6 d-none" data-member-plan-preview-field><input class="form-control bg-light" readonly data-member-total-preview placeholder="Total amount to save"></div>
                                        <div class="col-md-6 d-none" data-member-cooperative-field><input name="cooperative_group_name" class="form-control" placeholder="Cooperative / group name"></div>
                                    </div>
                                    <div class="member-autodebit-box">
                                        <label class="form-label mb-1">Savings auto debit</label>
                                        <select name="auto_debit_mode" class="form-select" data-member-savings-auto-mode>
                                            @foreach($savingsAutoDebitModes as $value => $label)
                                                <option value="{{ $value }}" @selected(old('auto_debit_mode', \App\Models\SavingsAccount::AUTO_DEBIT_MANUAL_ONLY) === $value)>{{ $label }}</option>
                                            @endforeach
                                        </select>
                                        <select name="auto_debit_savings_account_id" class="form-select mt-2 d-none" data-member-savings-auto-source>
                                            <option value="">Debit from which savings account?</option>
                                            @foreach($activeSavingsAccounts as $account)
                                                <option value="{{ $account->id }}" @selected(old('auto_debit_savings_account_id') == $account->id)>{{ $account->account_number }} - {{ $account->product_name }} ({{ $currency }} {{ number_format($account->balance, 2) }})</option>
                                            @endforeach
                                        </select>
                                        <small class="text-muted d-block mt-1">Use this for target, thrift, Isusu, cooperative, or locked savings that should collect automatically.</small>
                                    </div>
                                    <button class="btn btn-primary"><i class="bi bi-plus-circle me-1"></i> Open savings plan</button>
                                </form>
                            @else
                                <div class="text-muted small">No member savings products are available right now.</div>
                            @endif
                        </div>

                        <div class="member-side-panel">
                            <h3>Save now</h3>
                            @if($gatewayEnabled && $activeSavingsAccounts->isNotEmpty())
                                <form method="POST" action="{{ route('member.savings.deposit') }}" class="vstack gap-3">
                                    @csrf
                                    <select name="savings_account_id" class="form-select" required data-member-savings-deposit-account>
                                        @foreach($activeSavingsAccounts as $account)
                                            <option value="{{ $account->id }}" data-default-amount="{{ $account->contribution_amount ?: '' }}">{{ $account->account_number }} - {{ $account->product_name }}</option>
                                        @endforeach
                                    </select>
                                    <input name="amount" type="number" min="0.01" step="0.01" class="form-control" placeholder="Amount to save" required data-member-savings-deposit-amount>
                                    <button class="btn btn-success"><i class="bi bi-credit-card me-1"></i> Pay into savings</button>
                                    <small class="text-muted">After payment is confirmed, the company will approve and post the deposit to your savings balance.</small>
                                </form>
                            @elseif(! $gatewayEnabled)
                                <div class="text-muted small">Online savings deposits will be available after the company enables a payment gateway.</div>
                            @else
                                <div class="text-muted small">No approved savings account is active yet.</div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-loans">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-xl-7">
                        <div class="member-section-title"><h3>Apply for a loan</h3><p>Select a loan product and complete the requirements.</p></div>
                        @if($products->isNotEmpty())
                            <form method="POST" action="{{ route('member.loans.apply') }}" class="row g-3">
                                @csrf
                                <div class="col-12"><div class="alert alert-info border-0 mb-0" data-member-product-summary>Select a product to see term and requirements.</div></div>
                                <div class="col-md-6"><label class="form-label">Loan product</label><select name="loan_product_id" class="form-select" required data-member-loan-product-selector><option value="">Select product</option>@foreach($products as $product)<option value="{{ $product->id }}">{{ $product->name }} - {{ $product->interest_rate }}%</option>@endforeach</select></div>
                                <div class="col-md-6"><label class="form-label">Amount</label><input name="principal" type="number" min="1" step="0.01" class="form-control" required></div>
                                <div class="col-md-6 d-none" data-member-custom-interest-section><label class="form-label">Interest rate for this loan (%)</label><input name="custom_interest_rate" type="number" min="0" step="0.01" class="form-control"></div>
                                <div class="col-md-6"><label class="form-label">First repayment date</label><input name="first_repayment_date" type="date" class="form-control" data-member-first-repayment></div>
                                <div class="col-md-6"><label class="form-label">Purpose</label><input name="purpose" class="form-control"></div>
                                <div class="col-12">
                                    <div class="member-autodebit-box">
                                        <label class="form-label mb-1">Repayment auto debit</label>
                                        <div class="row g-2">
                                            <div class="col-md-6">
                                                <select name="auto_debit_mode" class="form-select" data-member-loan-auto-mode>
                                                    @foreach($loanAutoDebitModes as $value => $label)
                                                        <option value="{{ $value }}" @selected(old('auto_debit_mode', \App\Models\Loan::AUTO_DEBIT_MANUAL_ONLY) === $value)>{{ $label }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <select name="auto_debit_savings_account_id" class="form-select d-none" data-member-loan-auto-source>
                                                    <option value="">Debit from which savings account?</option>
                                                    @foreach($activeSavingsAccounts as $account)
                                                        <option value="{{ $account->id }}" @selected(old('auto_debit_savings_account_id') == $account->id)>{{ $account->account_number }} - {{ $account->product_name }} ({{ $currency }} {{ number_format($account->balance, 2) }})</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>
                                        <small class="text-muted d-block mt-1">Manual with default auto debit only charges the selected account when a repayment is overdue.</small>
                                    </div>
                                </div>
                                <div class="col-12 d-none" data-member-custom-term-section>
                                    <div class="border rounded p-3 bg-light">
                                        <div class="fw-semibold mb-2">Custom loan term</div>
                                        <div class="row g-2">
                                            <div class="col-md-4"><label class="form-label">Number of payments</label><input name="custom_term_value" type="number" min="1" class="form-control"></div>
                                            <input type="hidden" name="custom_term_unit" value="months">
                                            <div class="col-md-8"><label class="form-label">Repayment calendar</label><select name="custom_repayment_frequency" class="form-select">@foreach($customRepaymentFrequencies as $value => $label)<option value="{{ $value }}" @selected($value === 'monthly')>{{ $label }}</option>@endforeach</select></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12" data-member-collateral-section><label class="form-label">Collateral <span class="badge text-bg-light text-dark" data-member-collateral-badge>Optional</span></label><textarea name="collateral" class="form-control"></textarea></div>
                                <div class="col-12" data-member-guarantor-section>
                                    <div class="border rounded p-3">
                                        <div class="fw-semibold mb-2">Guarantor <span class="badge text-bg-light text-dark" data-member-guarantor-badge>Optional</span></div>
                                        <div class="row g-3">
                                            <div class="col-md-6"><label class="form-label">Guarantor name</label><input name="guarantor_name" value="{{ $customer->guarantor_name }}" class="form-control"></div>
                                            <div class="col-md-6"><label class="form-label">Guarantor phone</label><input name="guarantor_phone" value="{{ $customer->guarantor_phone }}" class="form-control"></div>
                                            <div class="col-md-6"><label class="form-label">Relationship</label><input name="guarantor_relationship" value="{{ $customer->guarantor_relationship }}" class="form-control"></div>
                                            <div class="col-md-6"><label class="form-label">Guarantor ID</label><input name="guarantor_id_number" class="form-control"></div>
                                            <div class="col-12"><label class="form-label">Guarantor address</label><textarea name="guarantor_address" class="form-control">{{ $customer->guarantor_address }}</textarea></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12"><button class="btn btn-primary">Submit loan application</button></div>
                            </form>
                        @else
                            <div class="text-muted">No active loan products are available right now.</div>
                        @endif
                    </div>

                    <div class="col-xl-5">
                        <div class="member-side-panel mb-3">
                            <h3>Repay loan</h3>
                            @if($gatewayEnabled && $activeLoans->isNotEmpty())
                                <form method="POST" action="{{ route('member.loans.repay') }}" class="vstack gap-3">
                                    @csrf
                                    <select name="loan_id" class="form-select" required data-member-repayment-loan>
                                        @foreach($activeLoans as $loan)
                                            <option value="{{ $loan->id }}">{{ $loan->loan_number }} - {{ $currency }} {{ number_format($loan->balance, 2) }}</option>
                                        @endforeach
                                    </select>
                                    <input name="amount" type="number" min="0.01" step="0.01" class="form-control" placeholder="Amount" required data-member-repayment-amount>
                                    <button class="btn btn-primary"><i class="bi bi-credit-card me-1"></i> Pay repayment</button>
                                </form>
                            @elseif(! $gatewayEnabled)
                                <div class="text-muted small">Online repayments will be available after the company enables a payment gateway.</div>
                            @else
                                <div class="text-muted small">No active loans are ready for repayment.</div>
                            @endif
                        </div>

                        <div class="member-side-panel">
                            <h3>Loans and schedules</h3>
                            <div class="vstack gap-3">
                                @forelse($customer->loans->sortByDesc('created_at') as $loan)
                                    @php($nextDue = $loan->schedules->whereIn('status', ['pending', 'partial', 'overdue'])->sortBy('due_date')->first())
                                    <div class="border rounded p-3">
                                        <div class="d-flex justify-content-between gap-2">
                                            <div class="fw-semibold">{{ $loan->loan_number }}</div>
                                            <span class="badge text-bg-light text-dark">{{ ucfirst(str_replace('_', ' ', $loan->status)) }}</span>
                                        </div>
                                        <div class="small text-muted mt-1">Balance: {{ $currency }} {{ number_format($loan->balance, 2) }}</div>
                                        <div class="small text-muted">Next due: {{ app_date($nextDue?->due_date) ?? '-' }} @if($nextDue) · {{ $currency }} {{ number_format(max(0, (float) $nextDue->total_due - (float) $nextDue->paid_amount), 2) }} @endif</div>
                                    </div>
                                @empty
                                    <div class="text-muted small">No loans yet.</div>
                                @endforelse
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-investments">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-lg-7">
                        <div class="member-section-title"><h3>Investments</h3><p>Track investment balances and submit new investment requests for approval.</p></div>
                        @if($overview['investment']['ready'])
                            <div class="table-responsive">
                                <table class="table mb-0">
                                    <thead><tr><th>Account</th><th>Status</th><th class="text-end">Balance</th></tr></thead>
                                    <tbody>
                                        @forelse($overview['investment']['accounts'] as $account)
                                            <tr><td>{{ $account->account_number ?? $account->reference ?? '-' }}</td><td>{{ ucfirst($account->status ?? 'active') }}</td><td class="text-end">{{ $currency }} {{ number_format((float) ($account->balance ?? $account->principal ?? 0), 2) }}</td></tr>
                                        @empty
                                            <tr><td colspan="3" class="text-center text-muted py-4">No investment accounts yet.</td></tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        @else
                            <div class="alert alert-light border">Investment product tables are not active yet. You can still send an investment request to the company team.</div>
                        @endif
                    </div>
                    <div class="col-lg-5">
                        <div class="member-side-panel">
                            <h3>Request investment</h3>
                            <form method="POST" action="{{ route('member.investments.request') }}" class="vstack gap-3">
                                @csrf
                                <select name="investment_product_id" class="form-select">
                                    <option value="">Select investment product</option>
                                    @foreach($investmentProducts as $product)
                                        <option value="{{ $product->id }}">{{ $product->name }} - {{ $product->termLabel() }} @if((float) $product->interest_rate > 0) / {{ $product->interest_rate }}% @endif</option>
                                    @endforeach
                                </select>
                                <input name="amount" type="number" min="1" step="0.01" class="form-control" placeholder="Amount" required>
                                <input name="term" class="form-control" placeholder="Preferred term e.g. 6 months">
                                <textarea name="notes" rows="4" class="form-control" placeholder="Any note for the company team"></textarea>
                                <button class="btn btn-primary">Submit for approval</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-transfers">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-xl-5">
                        <div class="member-bills-hero mb-3">
                            <div>
                                <span>Transfers</span>
                                <h3>Send money to another member or request a bank transfer</h3>
                                <p>Internal transfers move between member savings accounts. Bank transfers are reviewed by the company before payout.</p>
                            </div>
                            <i class="bi bi-arrow-left-right"></i>
                        </div>
                        <div class="member-side-panel">
                            <h3>Start transfer</h3>
                            @if($activeSavingsAccounts->isNotEmpty())
                                <form method="POST" action="{{ route('member.transfers.store') }}" class="vstack gap-3" data-member-transfer-form>
                                    @csrf
                                    <div>
                                        <label class="form-label">From savings account</label>
                                        <select name="savings_account_id" class="form-select" required>
                                            @foreach($activeSavingsAccounts as $account)
                                                <option value="{{ $account->id }}">{{ $account->account_number }} - {{ $account->product_name }} ({{ $currency }} {{ number_format($account->balance, 2) }})</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div>
                                        <label class="form-label">Transfer type</label>
                                        <select name="transfer_type" class="form-select" data-member-transfer-type required>
                                            <option value="internal">Within this company</option>
                                            <option value="bank">To bank account</option>
                                        </select>
                                    </div>
                                    <div data-member-transfer-internal>
                                        <label class="form-label">Recipient member / savings account number</label>
                                        <input name="recipient_identifier" class="form-control" placeholder="Enter member account number or savings account number">
                                        <div class="form-text">The recipient must belong to this company and have an active savings account.</div>
                                    </div>
                                    <div class="row g-3 d-none" data-member-transfer-bank>
                                        <div class="col-md-12">
                                            <label class="form-label">Bank name</label>
                                            <input name="recipient_bank_name" class="form-control" list="memberTransferBanks" placeholder="e.g. Providus Bank">
                                            <datalist id="memberTransferBanks">
                                                @foreach(['Access Bank', 'First Bank', 'GTBank', 'UBA', 'Zenith Bank', 'Sterling Bank', 'Stanbic IBTC', 'Fidelity Bank', 'Union Bank', 'Providus Bank', 'Wema Bank', 'Kuda', 'Moniepoint', 'OPay', 'PalmPay'] as $bank)
                                                    <option value="{{ $bank }}"></option>
                                                @endforeach
                                            </datalist>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Account number</label>
                                            <input name="recipient_account_number" class="form-control" placeholder="10 digit account number">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Account name</label>
                                            <input name="recipient_account_name" class="form-control" placeholder="Recipient account name">
                                        </div>
                                    </div>
                                    <div>
                                        <label class="form-label">Amount</label>
                                        <input name="amount" type="number" min="1" step="0.01" class="form-control" placeholder="Amount to transfer" required>
                                    </div>
                                    <div>
                                        <label class="form-label">Narration</label>
                                        <textarea name="narration" rows="3" class="form-control" placeholder="Optional note"></textarea>
                                    </div>
                                    <button class="btn btn-success"><i class="bi bi-send-check me-1"></i> Submit transfer</button>
                                </form>
                            @else
                                <div class="text-muted small">You need an active savings account before you can initiate transfers.</div>
                            @endif
                        </div>
                    </div>
                    <div class="col-xl-7">
                        <div class="member-section-title">
                            <h3>Transfer history</h3>
                            <p>Track internal transfers, bank transfer requests, approvals, and posted status.</p>
                        </div>
                        <div class="table-responsive">
                            <table class="table align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Reference</th>
                                        <th>Destination</th>
                                        <th>Status</th>
                                        <th class="text-end">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @forelse($memberTransfers as $transfer)
                                        @php
                                            $isIncoming = (int) $transfer->recipient_customer_id === (int) $customer->id;
                                            $recipientText = $isIncoming
                                                ? 'From '.($transfer->sender?->fullName() ?: 'Member')
                                                : ($transfer->recipient_bank_name ? $transfer->recipient_bank_name.' - '.$transfer->recipient_account_number : 'To '.($transfer->recipient?->fullName() ?: $transfer->recipient_account_number));
                                        @endphp
                                        <tr>
                                            <td>{{ app_datetime($transfer->posted_at ?? $transfer->created_at) }}</td>
                                            <td>
                                                <strong>{{ $transfer->reference }}</strong>
                                                <span class="d-block small text-muted">{{ $isIncoming ? 'Incoming' : $transfer->typeLabel() }}</span>
                                            </td>
                                            <td>{{ $recipientText }}</td>
                                            <td><span class="badge text-bg-{{ $transfer->statusBadge() }}">{{ $transfer->statusLabel() }}</span></td>
                                            <td class="text-end fw-bold {{ $isIncoming ? 'text-success' : 'text-danger' }}">
                                                {{ $isIncoming ? '+' : '-' }}{{ $currency }} {{ number_format((float) ($isIncoming ? $transfer->amount : $transfer->total_amount), 2) }}
                                            </td>
                                        </tr>
                                    @empty
                                        <tr><td colspan="5" class="text-center text-muted py-4">No transfer yet.</td></tr>
                                    @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-bills">
                <div class="row g-4 p-3 p-lg-4">
                    <div class="col-xl-7">
                        <div class="member-bills-hero mb-3">
                            <div>
                                <span>Bill payments</span>
                                <h3>Buy airtime, data, electricity, cable TV, and internet from your balance</h3>
                                <p>Select a savings account, choose the bill type, and the amount is debited immediately from your available balance.</p>
                            </div>
                            <i class="bi bi-phone-vibrate"></i>
                        </div>

                        <div class="member-bill-service-grid">
                            @foreach($billPaymentServiceTypes as $key => $service)
                                <button type="button" class="member-bill-service-card" data-member-bill-service-card value="{{ $key }}">
                                    <i class="bi {{ $service['icon'] }}"></i>
                                    <span>{{ $service['label'] }}</span>
                                </button>
                            @endforeach
                        </div>
                    </div>
                    <div class="col-xl-5">
                        <div class="member-side-panel">
                            <h3>Pay a bill</h3>
                            @if($activeSavingsAccounts->isNotEmpty())
                                <form method="POST" action="{{ route('member.bill-payments.store') }}" class="vstack gap-3" data-member-bill-form>
                                    @csrf
                                    <select name="savings_account_id" class="form-select" required>
                                        @foreach($activeSavingsAccounts as $account)
                                            <option value="{{ $account->id }}">{{ $account->account_number }} - {{ $account->product_name }} ({{ $currency }} {{ number_format($account->balance, 2) }})</option>
                                        @endforeach
                                    </select>
                                    <select name="service_type" class="form-select" required data-member-bill-service>
                                        @foreach($billPaymentServiceTypes as $key => $service)
                                            <option value="{{ $key }}">{{ $service['label'] }}</option>
                                        @endforeach
                                    </select>
                                    <select name="provider" class="form-select" required data-member-bill-provider></select>
                                    <input name="package_name" list="memberBillPackageOptions" class="form-control" placeholder="{{ $billDriver === 'flutterwave' ? 'Package / BILLER_CODE|ITEM_CODE' : 'Package / VTpass variation code' }}" data-member-bill-package>
                                    <datalist id="memberBillPackageOptions" data-member-bill-package-options></datalist>
                                    <input name="customer_identifier" class="form-control" placeholder="Phone, meter, smartcard, or customer ID" required>
                                    <input name="amount" type="number" min="1" step="0.01" class="form-control" placeholder="Amount" required>
                                    <textarea name="notes" rows="2" class="form-control" placeholder="Optional note"></textarea>
                                    <button class="btn btn-success"><i class="bi bi-check2-circle me-1"></i> Pay from balance</button>
                                    <small class="text-muted">Live VTU fulfillment can be connected through your tenant bill-payment provider settings.</small>
                                </form>
                            @else
                                <div class="text-muted small">You need an active savings account with available balance before paying bills.</div>
                            @endif
                        </div>
                    </div>
                    <div class="col-12">
                        @include('tenant.partials.member-transaction-history', ['transactions' => $overview['transactions']->where('category', 'Bill Payment'), 'currency' => $currency])
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="member-transactions">
                @include('tenant.partials.member-transaction-history', ['transactions' => $overview['transactions'], 'currency' => $currency])
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const showMemberPortalTab = (hash, shouldPush = false) => {
        if (!hash || !window.bootstrap) return false;

        const normalizedHash = hash.startsWith('#') ? hash : `#${hash}`;
        const targetId = normalizedHash.slice(1);
        let tab = document.querySelector(`[data-bs-target="${normalizedHash}"]`);
        const directTarget = document.getElementById(targetId);

        if (!tab && directTarget?.matches('[data-bs-toggle="tab"]')) {
            tab = directTarget;
        }

        if (!tab) return false;

        new bootstrap.Tab(tab).show();

        if (shouldPush) {
            history.replaceState(null, '', normalizedHash);
        }

        return true;
    };

    if (window.location.hash) {
        showMemberPortalTab(window.location.hash);
    }

    document.querySelectorAll('a[href*="#"]').forEach((link) => {
        link.addEventListener('click', (event) => {
            const url = new URL(link.href, window.location.href);
            const isCurrentPage = url.origin === window.location.origin && url.pathname === window.location.pathname;

            if (!isCurrentPage || !url.hash) return;

            if (showMemberPortalTab(url.hash, true)) {
                event.preventDefault();
                document.body.classList.remove('mobile-menu-open');
            }
        });
    });

    const dob = document.querySelector('[data-date-of-birth]');
    const age = document.querySelector('[data-age-field]');
    const updateAge = () => {
        if (!dob || !age || !dob.value) {
            if (age) age.value = '';
            return;
        }
        const birthDate = new Date(dob.value + 'T00:00:00');
        const today = new Date();
        let years = today.getFullYear() - birthDate.getFullYear();
        const monthDelta = today.getMonth() - birthDate.getMonth();
        if (monthDelta < 0 || (monthDelta === 0 && today.getDate() < birthDate.getDate())) years--;
        age.value = Number.isFinite(years) && years >= 0 ? years : '';
    };
    dob?.addEventListener('change', updateAge);
    updateAge();

    document.querySelectorAll('[data-verify-identity]').forEach((button) => {
        button.addEventListener('click', () => {
            const field = document.querySelector(`[name="${button.dataset.verifyIdentity}"]`);
            const feedback = document.querySelector('[data-identity-feedback]');
            const label = field?.dataset.identityNumber || 'Identity number';
            const value = String(field?.value || '').trim();
            if (/^\d{11}$/.test(value)) {
                feedback.textContent = `${label} format verified. Save your profile to run the configured KYC workflow.`;
                feedback.classList.remove('text-danger', 'text-muted');
                feedback.classList.add('text-success');
                return;
            }
            feedback.textContent = `${label} must be exactly 11 digits.`;
            feedback.classList.remove('text-success', 'text-muted');
            feedback.classList.add('text-danger');
            field?.focus();
        });
    });

    const savingsProducts = @json($savingsProductPayload);
    const savingsById = new Map(savingsProducts.map((product) => [String(product.id), product]));
    const savingsSelector = document.querySelector('[data-member-savings-product-selector]');
    const savingsSummary = document.querySelector('[data-member-savings-product-summary]');
    const portalCurrency = @json($currency);
    const formatPortalMoney = (amount) => `${portalCurrency} ${Number(amount || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    const toggleAutoDebitSource = (modeSelector, sourceSelector) => {
        const mode = document.querySelector(modeSelector);
        const source = document.querySelector(sourceSelector);
        const sync = () => {
            const enabled = mode && mode.value !== 'manual_only';
            source?.classList.toggle('d-none', !enabled);
            if (source) source.required = Boolean(enabled);
        };
        mode?.addEventListener('change', sync);
        sync();
    };
    toggleAutoDebitSource('[data-member-savings-auto-mode]', '[data-member-savings-auto-source]');
    toggleAutoDebitSource('[data-member-loan-auto-mode]', '[data-member-loan-auto-source]');

    const billProviders = @json($billProviders);
    const billPackages = @json($billPackages);
    const billService = document.querySelector('[data-member-bill-service]');
    const billProvider = document.querySelector('[data-member-bill-provider]');
    const billPackage = document.querySelector('[data-member-bill-package]');
    const billPackageOptions = document.querySelector('[data-member-bill-package-options]');
    const syncBillOptions = () => {
        const type = billService?.value || 'airtime';
        if (billProvider) {
            billProvider.innerHTML = '';
            (billProviders[type] || []).forEach((provider) => {
                billProvider.add(new Option(provider, provider));
            });
        }
        if (billPackage) {
            billPackage.value = '';
        }
        if (billPackageOptions) {
            billPackageOptions.innerHTML = '';
            (billPackages[type] || []).forEach((packageName) => {
                const option = document.createElement('option');
                option.value = packageName;
                billPackageOptions.appendChild(option);
            });
        }
        document.querySelectorAll('[data-member-bill-service-card]').forEach((card) => {
            card.classList.toggle('active', card.value === type);
        });
    };
    document.querySelectorAll('[data-member-bill-service-card]').forEach((card) => {
        card.addEventListener('click', () => {
            if (!billService) return;
            billService.value = card.value;
            billService.dispatchEvent(new Event('change', { bubbles: true }));
        });
    });
    billService?.addEventListener('change', syncBillOptions);
    syncBillOptions();

    const transferType = document.querySelector('[data-member-transfer-type]');
    const transferInternal = document.querySelector('[data-member-transfer-internal]');
    const transferBank = document.querySelector('[data-member-transfer-bank]');
    const syncTransferFields = () => {
        const isBank = transferType?.value === 'bank';
        transferInternal?.classList.toggle('d-none', isBank);
        transferBank?.classList.toggle('d-none', !isBank);
        transferInternal?.querySelectorAll('input').forEach((input) => {
            input.required = !isBank;
        });
        transferBank?.querySelectorAll('input[name="recipient_bank_name"], input[name="recipient_account_number"], input[name="recipient_account_name"]').forEach((input) => {
            input.required = isBank;
        });
    };
    transferType?.addEventListener('change', syncTransferFields);
    syncTransferFields();

    const savingsFeeEstimate = (product) => {
        const contributionInput = document.querySelector('[data-member-open-savings-form] [name="contribution_amount"]');
        const targetInput = document.querySelector('[data-member-open-savings-form] [name="target_amount"]');
        const contribution = Number(contributionInput?.value || 0);
        const target = Number(targetInput?.value || 0);
        const base = contribution > 0 ? contribution : (target > 0 ? target : Number(product.minimum_opening_balance || 0));

        if (product.processing_fee_type === 'percentage') {
            return base * (Number(product.processing_fee_value || 0) / 100);
        }

        if (product.processing_fee_type === 'contribution_amount') {
            return contribution;
        }

        return Number(product.processing_fee_value || 0);
    };
    const savingsIntervalDays = { daily: 1, weekly: 7, biweekly: 14, monthly: 30, quarterly: 90, yearly: 365 };
    const addSavingsPeriods = (startDate, frequency, periods) => {
        const date = new Date(`${startDate}T00:00:00`);

        switch (frequency) {
            case 'daily': date.setDate(date.getDate() + periods); break;
            case 'weekly': date.setDate(date.getDate() + (periods * 7)); break;
            case 'biweekly': date.setDate(date.getDate() + (periods * 14)); break;
            case 'quarterly': date.setMonth(date.getMonth() + (periods * 3)); break;
            case 'yearly': date.setFullYear(date.getFullYear() + periods); break;
            default: date.setMonth(date.getMonth() + periods); break;
        }

        return date.toISOString().slice(0, 10);
    };
    const syncMemberSavingsPlanPreview = (product) => {
        const form = document.querySelector('[data-member-open-savings-form]');
        const startInput = form?.querySelector('[name="start_date"]');
        const contributionInput = form?.querySelector('[name="contribution_amount"]');
        const frequencyInput = form?.querySelector('[name="contribution_frequency"]');
        const periodsInput = form?.querySelector('[name="contribution_periods"]');
        const maturityPreview = document.querySelector('[data-member-maturity-preview]');
        const totalPreview = document.querySelector('[data-member-total-preview]');
        const frequency = frequencyInput?.value || product?.contribution_frequency || 'monthly';

        if (periodsInput && !periodsInput.value && Number(product?.duration_days || 0) > 0) {
            periodsInput.value = Math.max(1, Math.ceil(Number(product.duration_days) / (savingsIntervalDays[frequency] || 30)));
        }

        const periods = Number(periodsInput?.value || 0);
        const contribution = Number(contributionInput?.value || 0);

        if (maturityPreview) {
            maturityPreview.value = startInput?.value && periods > 0 ? addSavingsPeriods(startInput.value, frequency, periods) : '';
        }

        if (totalPreview) {
            totalPreview.value = contribution > 0 && periods > 0 ? formatPortalMoney(contribution * periods) : '';
        }
    };
    const setSavingsRequired = (name, required) => {
        const field = document.querySelector(`[data-member-open-savings-form] [name="${name}"]`);
        if (field) field.required = required;
    };
    const loadSavingsProduct = () => {
        const product = savingsById.get(String(savingsSelector?.value || ''));
        document.querySelectorAll('[data-member-target-field], [data-member-contribution-field], [data-member-plan-preview-field], [data-member-cooperative-field]').forEach((field) => field.classList.add('d-none'));
        document.querySelectorAll('[data-member-savings-product-card]').forEach((card) => {
            card.classList.toggle('active', product && String(card.value) === String(product.id));
        });
        setSavingsRequired('target_amount', false);
        setSavingsRequired('contribution_amount', false);
        setSavingsRequired('contribution_periods', false);
        setSavingsRequired('cooperative_group_name', false);

        if (!product) {
            if (savingsSummary) savingsSummary.textContent = 'Select a plan to see required fields.';
            return;
        }

        const contributionText = product.type === 'regular'
            ? 'Contribution amount is entered when making deposits'
            : 'Contribution amount is set when opening this plan';
        const feeText = product.processing_fee_type === 'contribution_amount'
            ? `Processing fee: ${formatPortalMoney(savingsFeeEstimate(product))} (one contribution amount)`
            : `Processing fee: ${formatPortalMoney(savingsFeeEstimate(product))}`;
        const feeTimingText = product.processing_fee_timing_label || String(product.processing_fee_timing || 'manual').replaceAll('_', ' ');
        if (savingsSummary) savingsSummary.textContent = `${product.name}: ${product.type_label}. ${contributionText}. ${feeText}. Fee timing: ${feeTimingText}. Withdrawal: ${String(product.withdrawal_policy).replaceAll('_', ' ')}.`;

        const needsContributionAmount = ['thrift_isusu', 'cooperative'].includes(product.type) || product.processing_fee_type === 'contribution_amount';

        if (needsContributionAmount) {
            document.querySelectorAll('[data-member-contribution-field], [data-member-plan-preview-field]').forEach((field) => field.classList.remove('d-none'));
            setSavingsRequired('contribution_amount', true);
            setSavingsRequired('contribution_periods', true);
        }

        if (product.type === 'target') {
            document.querySelectorAll('[data-member-target-field], [data-member-contribution-field], [data-member-plan-preview-field]').forEach((field) => field.classList.remove('d-none'));
            setSavingsRequired('target_amount', true);
            setSavingsRequired('contribution_amount', true);
            setSavingsRequired('contribution_periods', true);
        }

        if (product.type === 'thrift_isusu') {
            document.querySelectorAll('[data-member-contribution-field], [data-member-plan-preview-field]').forEach((field) => field.classList.remove('d-none'));
            setSavingsRequired('contribution_amount', true);
            setSavingsRequired('contribution_periods', true);
        }

        if (product.type === 'cooperative') {
            document.querySelectorAll('[data-member-contribution-field], [data-member-plan-preview-field], [data-member-cooperative-field]').forEach((field) => field.classList.remove('d-none'));
            setSavingsRequired('cooperative_group_name', true);
            setSavingsRequired('contribution_amount', true);
            setSavingsRequired('contribution_periods', true);
        }

        syncMemberSavingsPlanPreview(product);
    };
    document.querySelectorAll('[data-member-savings-product-card]').forEach((button) => {
        button.addEventListener('click', () => {
            if (!savingsSelector) return;
            savingsSelector.value = button.value;
            savingsSelector.dispatchEvent(new Event('change', { bubbles: true }));
        });
    });
    savingsSelector?.addEventListener('change', loadSavingsProduct);
    document.querySelector('[data-member-open-savings-form] [name="contribution_amount"]')?.addEventListener('input', loadSavingsProduct);
    document.querySelector('[data-member-open-savings-form] [name="target_amount"]')?.addEventListener('input', loadSavingsProduct);
    document.querySelector('[data-member-open-savings-form] [name="contribution_frequency"]')?.addEventListener('change', loadSavingsProduct);
    document.querySelector('[data-member-open-savings-form] [name="contribution_periods"]')?.addEventListener('input', loadSavingsProduct);
    document.querySelector('[data-member-open-savings-form] [name="start_date"]')?.addEventListener('change', loadSavingsProduct);
    loadSavingsProduct();

    const savingsDepositSelect = document.querySelector('[data-member-savings-deposit-account]');
    const savingsDepositAmount = document.querySelector('[data-member-savings-deposit-amount]');
    const syncSavingsDepositAmount = () => {
        const selected = savingsDepositSelect?.selectedOptions?.[0];
        const amount = Number(selected?.dataset.defaultAmount || 0);

        if (savingsDepositAmount && amount > 0) {
            savingsDepositAmount.value = amount.toFixed(2);
        }
    };
    savingsDepositSelect?.addEventListener('change', syncSavingsDepositAmount);
    syncSavingsDepositAmount();

    const products = @json($productPayload);
    const byId = new Map(products.map((product) => [String(product.id), product]));
    const selector = document.querySelector('[data-member-loan-product-selector]');
    const summary = document.querySelector('[data-member-product-summary]');
    const firstRepayment = document.querySelector('[data-member-first-repayment]');
    const customInterestSection = document.querySelector('[data-member-custom-interest-section]');
    const customSection = document.querySelector('[data-member-custom-term-section]');
    const collateralSection = document.querySelector('[data-member-collateral-section]');
    const guarantorSection = document.querySelector('[data-member-guarantor-section]');
    const collateralBadge = document.querySelector('[data-member-collateral-badge]');
    const guarantorBadge = document.querySelector('[data-member-guarantor-badge]');
    const requiredText = { required: 'Required', optional: 'Optional', hidden: 'Hidden' };
    const repaymentOffsets = { daily: 1, weekly: 7, biweekly: 14, monthly: 30, quarterly: 90, yearly: 365 };

    const setRequired = (name, required) => {
        const field = document.querySelector(`[name="${name}"]`);
        if (field) field.required = required;
    };
    const setSection = (section, badge, rule, requiredFields) => {
        section?.classList.toggle('d-none', rule === 'hidden');
        if (badge) badge.textContent = requiredText[rule] || 'Optional';
        requiredFields.forEach((name) => setRequired(name, rule === 'required'));
    };
    const isoDateAfterDays = (days) => {
        const date = new Date();
        date.setDate(date.getDate() + days);
        return date.toISOString().slice(0, 10);
    };
    const loadProduct = () => {
        const product = byId.get(String(selector?.value || ''));
        if (!product) {
            summary.textContent = 'Select a product to see term and requirements.';
            customInterestSection?.classList.add('d-none');
            customSection?.classList.add('d-none');
            setRequired('custom_interest_rate', false);
            setSection(collateralSection, collateralBadge, 'optional', ['collateral']);
            setSection(guarantorSection, guarantorBadge, 'optional', ['guarantor_name', 'guarantor_phone']);
            return;
        }
        const maxText = Number(product.maximum_amount) > 0 ? `Max ${Number(product.maximum_amount).toLocaleString()}` : 'No maximum';
        const feeText = Number(product.processing_fee_value) > 0 ? `${product.processing_fee_value} ${product.processing_fee_type === 'percentage' ? '%' : 'fixed'} processing fee` : 'No processing fee';
        const feeTimingText = Number(product.processing_fee_value) > 0 ? `fee timing: ${product.processing_fee_timing_label || String(product.processing_fee_timing || 'before_disbursement').replaceAll('_', ' ')}` : 'no fee timing needed';
        const interestText = product.interest_method === 'custom' ? 'custom interest rate per loan' : `${product.interest_rate}% ${String(product.interest_method).replace('_', ' ')} interest`;
        summary.textContent = `${product.name}: ${interestText}, ${product.repayment_frequency === 'custom' ? 'custom term per loan' : `${product.term_value} ${product.term_unit}`}, ${maxText}, ${feeText}, ${feeTimingText}.`;
        customInterestSection?.classList.toggle('d-none', product.interest_method !== 'custom');
        setRequired('custom_interest_rate', product.interest_method === 'custom');
        customSection?.classList.toggle('d-none', product.repayment_frequency !== 'custom');
        setRequired('custom_term_value', product.repayment_frequency === 'custom');
        setRequired('custom_repayment_frequency', product.repayment_frequency === 'custom');
        setSection(collateralSection, collateralBadge, product.collateral_requirement || 'optional', ['collateral']);
        setSection(guarantorSection, guarantorBadge, product.guarantor_requirement || 'optional', ['guarantor_name', 'guarantor_phone']);
        if (firstRepayment && !firstRepayment.value) firstRepayment.value = isoDateAfterDays(repaymentOffsets[product.repayment_frequency] || 30);
    };
    selector?.addEventListener('change', loadProduct);
    loadProduct();

    const defaults = @json($repaymentDefaults);
    const loanSelect = document.querySelector('[data-member-repayment-loan]');
    const amountInput = document.querySelector('[data-member-repayment-amount]');
    const syncRepaymentAmount = () => {
        if (loanSelect && amountInput) amountInput.value = Number(defaults[loanSelect.value] || 0).toFixed(2);
    };
    loanSelect?.addEventListener('change', syncRepaymentAmount);
    syncRepaymentAmount();
});
</script>
@endsection
