<?php
$currency = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$commercial_total = (float) $client_payments + (float) $client_outstanding + (float) ($client_payments + $client_outstanding) + (float) $total_estimate;
$project_total = array_sum($project_statuses);
$ticket_total = array_sum($ticket_statuses);
$invoice_total = array_sum($invoice_statuses);
$estimate_total = array_sum($estimate_statuses);
$proposal_total = array_sum($proposal_statuses);

$commercial_segments = array(
    array(
        'label' => lang('paid_amount'),
        'value' => (float) $client_payments,
        'color' => 'bg-emerald-500',
        'text' => 'text-emerald-600 dark:text-emerald-300',
        'format' => 'money',
    ),
    array(
        'label' => lang('due_amount'),
        'value' => (float) $client_outstanding,
        'color' => 'bg-rose-500',
        'text' => 'text-rose-600 dark:text-rose-300',
        'format' => 'money',
    ),
    array(
        'label' => lang('invoice_amount'),
        'value' => (float) ($client_payments + $client_outstanding),
        'color' => 'bg-sky-500',
        'text' => 'text-sky-600 dark:text-sky-300',
        'format' => 'money',
    ),
    array(
        'label' => lang('estimates') . ' ' . lang('amount'),
        'value' => (float) $total_estimate,
        'color' => 'bg-violet-500',
        'text' => 'text-violet-600 dark:text-violet-300',
        'format' => 'money',
    ),
);

$project_segments = array(
    array(
        'label' => lang('started'),
        'value' => (int) $project_statuses['started'],
        'color' => 'bg-amber-500',
        'text' => 'text-amber-600 dark:text-amber-300',
    ),
    array(
        'label' => lang('in_progress'),
        'value' => (int) $project_statuses['in_progress'],
        'color' => 'bg-blue-500',
        'text' => 'text-blue-600 dark:text-blue-300',
    ),
    array(
        'label' => lang('completed'),
        'value' => (int) $project_statuses['completed'],
        'color' => 'bg-emerald-500',
        'text' => 'text-emerald-600 dark:text-emerald-300',
    ),
    array(
        'label' => lang('cancel'),
        'value' => (int) $project_statuses['cancel'],
        'color' => 'bg-violet-500',
        'text' => 'text-violet-600 dark:text-violet-300',
    ),
);

$ticket_segments = array(
    array(
        'label' => lang('answered'),
        'value' => (int) $ticket_statuses['answered'],
        'color' => 'bg-cyan-500',
        'text' => 'text-cyan-600 dark:text-cyan-300',
    ),
    array(
        'label' => lang('in_progress'),
        'value' => (int) $ticket_statuses['in_progress'],
        'color' => 'bg-blue-500',
        'text' => 'text-blue-600 dark:text-blue-300',
    ),
    array(
        'label' => lang('open'),
        'value' => (int) $ticket_statuses['open'],
        'color' => 'bg-amber-500',
        'text' => 'text-amber-600 dark:text-amber-300',
    ),
    array(
        'label' => lang('closed'),
        'value' => (int) $ticket_statuses['closed'],
        'color' => 'bg-emerald-500',
        'text' => 'text-emerald-600 dark:text-emerald-300',
    ),
);

$invoice_segments = array(
    array(
        'label' => lang('fully_paid'),
        'value' => (int) $invoice_statuses['paid'],
        'color' => 'bg-emerald-500',
        'text' => 'text-emerald-600 dark:text-emerald-300',
    ),
    array(
        'label' => lang('not_paid'),
        'value' => (int) $invoice_statuses['unpaid'],
        'color' => 'bg-rose-500',
        'text' => 'text-rose-600 dark:text-rose-300',
    ),
    array(
        'label' => lang('partially_paid'),
        'value' => (int) $invoice_statuses['partially_paid'],
        'color' => 'bg-amber-500',
        'text' => 'text-amber-600 dark:text-amber-300',
    ),
    array(
        'label' => lang('overdue'),
        'value' => (int) $invoice_statuses['overdue'],
        'color' => 'bg-violet-500',
        'text' => 'text-violet-600 dark:text-violet-300',
    ),
    array(
        'label' => lang('draft'),
        'value' => (int) $invoice_statuses['draft'],
        'color' => 'bg-slate-500',
        'text' => 'text-slate-600 dark:text-slate-300',
    ),
    array(
        'label' => lang('cancelled'),
        'value' => (int) $invoice_statuses['cancelled'],
        'color' => 'bg-neutral-500',
        'text' => 'text-neutral-600 dark:text-neutral-300',
    ),
);

$estimate_segments = array(
    array(
        'label' => lang('draft'),
        'value' => (int) $estimate_statuses['draft'],
        'color' => 'bg-slate-500',
        'text' => 'text-slate-600 dark:text-slate-300',
    ),
    array(
        'label' => lang('pending'),
        'value' => (int) $estimate_statuses['pending'],
        'color' => 'bg-amber-500',
        'text' => 'text-amber-600 dark:text-amber-300',
    ),
    array(
        'label' => lang('accepted'),
        'value' => (int) $estimate_statuses['accepted'],
        'color' => 'bg-emerald-500',
        'text' => 'text-emerald-600 dark:text-emerald-300',
    ),
    array(
        'label' => lang('declined'),
        'value' => (int) $estimate_statuses['declined'],
        'color' => 'bg-rose-500',
        'text' => 'text-rose-600 dark:text-rose-300',
    ),
);

$proposal_segments = array(
    array(
        'label' => lang('draft'),
        'value' => (int) $proposal_statuses['draft'],
        'color' => 'bg-slate-500',
        'text' => 'text-slate-600 dark:text-slate-300',
    ),
    array(
        'label' => lang('pending'),
        'value' => (int) $proposal_statuses['pending'],
        'color' => 'bg-amber-500',
        'text' => 'text-amber-600 dark:text-amber-300',
    ),
    array(
        'label' => lang('sent'),
        'value' => (int) $proposal_statuses['sent'],
        'color' => 'bg-sky-500',
        'text' => 'text-sky-600 dark:text-sky-300',
    ),
    array(
        'label' => lang('accepted'),
        'value' => (int) $proposal_statuses['accepted'],
        'color' => 'bg-emerald-500',
        'text' => 'text-emerald-600 dark:text-emerald-300',
    ),
    array(
        'label' => lang('declined'),
        'value' => (int) $proposal_statuses['declined'],
        'color' => 'bg-rose-500',
        'text' => 'text-rose-600 dark:text-rose-300',
    ),
);
?>

<div class="space-y-6">
    <?php
    $selected_client_label = '';
    if (!empty($client_details)) {
        $selected_client_label = !empty($client_details->name) ? $client_details->name : '';
    }
    $is_portfolio_mode = !empty($report_mode) && $report_mode === 'portfolio';
    ?>
    <?= form_open(base_url('admin/report/client_report'), array('id' => 'client-report-form', 'class' => 'rounded-3xl border border-border bg-card p-6 shadow-sm')) ?>
    <input type="hidden" name="report_mode" id="client-report-mode" value="<?= $is_portfolio_mode ? 'portfolio' : 'client' ?>">
    <div class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div class="w-full lg:max-w-md">
            <?= form_lookup_group(
                'client_id',
                lang('client'),
                $client_id ?? '',
                $selected_client_label,
                false,
                array(),
                '',
                array(
                    'type' => 'client',
                    'min_length' => 0,
                    'limit' => 12,
                    'onchange' => 'clientReportAutoSubmit',
                    'placeholder' => lang('search') . ' ' . lang('client'),
                )
            ); ?>
        </div>
        <div class="flex items-center justify-end gap-2">
            <button type="button" id="load-portfolio-summary" class="inline-flex items-center gap-2 rounded-xl bg-primary px-4 py-3 text-sm font-semibold text-primary-foreground hover:bg-primary/90">
                <i data-lucide="chart-column-big" class="h-4 w-4"></i>
                Load Portfolio Summary
            </button>
        </div>
    </div>
    </form>

    <section class="rounded-3xl border border-border bg-card shadow-sm">
        <div class="border-b border-border px-6 py-5">
            <div class="inline-flex items-center gap-2 rounded-full border border-primary/20 bg-primary/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.24em] text-primary">
                <i data-lucide="users" class="h-3.5 w-3.5"></i>
                <?= lang('client') . ' ' . lang('report') ?>
            </div>
            <h2 class="mt-3 text-2xl font-semibold text-foreground"><?= lang('client') . ' ' . lang('report') ?></h2>
            <p class="mt-1 text-sm text-muted-foreground">
                <?= $is_portfolio_mode
                    ? 'Portfolio-wide client summary loaded on demand for a controlled full overview.'
                    : (!empty($selected_client_label)
                    ? 'Commercial health and service delivery visibility for ' . html_escape($selected_client_label) . '.'
                    : 'Select a client from lookup to load a fast focused report without scanning the full portfolio.'); ?>
            </p>
        </div>
        <?php if (!empty($report_ready)): ?>
            <div class="grid grid-cols-1 gap-4 p-6 md:grid-cols-2 xl:grid-cols-4">
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('client') ?></p>
                    <p class="mt-3 text-2xl font-bold text-foreground"><?= $is_portfolio_mode ? (int) $total_client_count : 1 ?></p>
                    <p class="mt-2 text-sm text-muted-foreground"><?= $is_portfolio_mode ? 'Active portfolio summary' : html_escape($selected_client_label) ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('paid_amount') ?></p>
                    <p class="mt-3 text-2xl font-bold text-emerald-600 dark:text-emerald-300"><?= display_money($client_payments, $currency->symbol) ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('due_amount') ?></p>
                    <p class="mt-3 text-2xl font-bold text-rose-600 dark:text-rose-300"><?= display_money($client_outstanding, $currency->symbol) ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-5">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('estimates') . ' ' . lang('amount') ?></p>
                    <p class="mt-3 text-2xl font-bold text-sky-600 dark:text-sky-300"><?= display_money($total_estimate, $currency->symbol) ?></p>
                </div>
            </div>
        <?php else: ?>
            <div class="px-6 py-10">
                <div class="rounded-2xl border border-dashed border-border bg-background/50 p-8 text-center">
                    <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                        <i data-lucide="search" class="h-6 w-6"></i>
                    </div>
                    <h3 class="mt-4 text-lg font-semibold text-foreground"><?= lang('select') . ' ' . lang('client') ?></h3>
                    <p class="mt-2 text-sm text-muted-foreground">
                        Use the lookup above to load one client report at a time, or click `Load Portfolio Summary` when you need the full aggregate. This keeps the page fast even with <?= (int) $total_client_count ?> clients in the system.
                    </p>
                </div>
            </div>
        <?php endif; ?>
    </section>

    <?php if (!empty($report_ready)): ?>
        <section class="rounded-3xl border border-border bg-card p-6 shadow-sm">
            <div class="mb-4">
                <h3 class="text-lg font-semibold text-foreground">Client Activity Snapshot</h3>
                <p class="text-sm text-muted-foreground">Quick volume overview across sales, delivery, and support.</p>
            </div>
            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-5">
                <div class="rounded-2xl border border-border bg-background/70 p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('invoices') ?></p>
                    <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['invoices'] ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('estimates') ?></p>
                    <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['estimates'] ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('proposals') ?></p>
                    <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['proposals'] ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('project') ?></p>
                    <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['projects'] ?></p>
                </div>
                <div class="rounded-2xl border border-border bg-background/70 p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('tickets') ?></p>
                    <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['tickets'] ?></p>
                </div>
            </div>
        </section>

        <section class="grid grid-cols-1 gap-6 xl:grid-cols-2">
            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= lang('client') . ' ' . lang('payment') . ' ' . lang('status') ?></h3>
                    <p class="text-sm text-muted-foreground">Commercial mix across invoiced, paid, due, and estimate value.</p>
                </div>
                <div class="space-y-4">
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <?php foreach ($commercial_segments as $segment):
                            $share = $commercial_total > 0 ? round(($segment['value'] / $commercial_total) * 100, 1) : 0;
                            ?>
                            <div class="rounded-2xl border border-border bg-background/70 p-4">
                                <div class="flex items-start justify-between gap-3">
                                    <div>
                                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= $segment['label'] ?></p>
                                        <p class="mt-2 text-lg font-bold <?= $segment['text'] ?>">
                                            <?= $segment['format'] === 'money' ? display_money($segment['value'], $currency->symbol) : (int) $segment['value'] ?>
                                        </p>
                                    </div>
                                    <span class="mt-1 inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                </div>
                                <p class="mt-2 text-xs text-muted-foreground"><?= $share ?>% of commercial total</p>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= lang('client') . ' ' . lang('project') . ' ' . lang('report') ?></h3>
                    <p class="text-sm text-muted-foreground">Client-facing project status distribution.</p>
                </div>
                <div class="space-y-3">
                    <?php foreach ($project_segments as $segment):
                        $width = $project_total > 0 ? max(round(($segment['value'] / $project_total) * 100, 2), ($segment['value'] > 0 ? 3 : 0)) : 0;
                        $share = $project_total > 0 ? round(($segment['value'] / $project_total) * 100, 1) : 0;
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <div class="mb-2 flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2">
                                    <span class="inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                    <p class="text-sm font-semibold text-foreground"><?= $segment['label'] ?></p>
                                </div>
                                <p class="text-sm font-semibold <?= $segment['text'] ?>"><?= (int) $segment['value'] ?> <span class="text-muted-foreground">(<?= $share ?>%)</span></p>
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-muted">
                                <progress class="report-meter report-meter-<?= str_replace(array('bg-', '-500'), '', $segment['color']) ?>" max="100" value="<?= $width ?>"></progress>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>

        <section class="grid grid-cols-1 gap-6 xl:grid-cols-3">
            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground">Invoice Status Report</h3>
                    <p class="text-sm text-muted-foreground">Billing position across paid, due, partial, overdue, and non-final invoices.</p>
                </div>
                <div class="space-y-3">
                    <?php foreach ($invoice_segments as $segment):
                        $width = $invoice_total > 0 ? max(round(($segment['value'] / $invoice_total) * 100, 2), ($segment['value'] > 0 ? 3 : 0)) : 0;
                        $share = $invoice_total > 0 ? round(($segment['value'] / $invoice_total) * 100, 1) : 0;
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <div class="mb-2 flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2">
                                    <span class="inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                    <p class="text-sm font-semibold text-foreground"><?= $segment['label'] ?></p>
                                </div>
                                <p class="text-sm font-semibold <?= $segment['text'] ?>"><?= (int) $segment['value'] ?> <span class="text-muted-foreground">(<?= $share ?>%)</span></p>
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-muted">
                                <progress class="report-meter report-meter-<?= str_replace(array('bg-', '-500'), '', $segment['color']) ?>" max="100" value="<?= $width ?>"></progress>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground">Estimate Status Report</h3>
                    <p class="text-sm text-muted-foreground">Quote readiness and approval progress for this client scope.</p>
                </div>
                <div class="space-y-3">
                    <?php foreach ($estimate_segments as $segment):
                        $width = $estimate_total > 0 ? max(round(($segment['value'] / $estimate_total) * 100, 2), ($segment['value'] > 0 ? 3 : 0)) : 0;
                        $share = $estimate_total > 0 ? round(($segment['value'] / $estimate_total) * 100, 1) : 0;
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <div class="mb-2 flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2">
                                    <span class="inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                    <p class="text-sm font-semibold text-foreground"><?= $segment['label'] ?></p>
                                </div>
                                <p class="text-sm font-semibold <?= $segment['text'] ?>"><?= (int) $segment['value'] ?> <span class="text-muted-foreground">(<?= $share ?>%)</span></p>
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-muted">
                                <progress class="report-meter report-meter-<?= str_replace(array('bg-', '-500'), '', $segment['color']) ?>" max="100" value="<?= $width ?>"></progress>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground">Proposal Status Report</h3>
                    <p class="text-sm text-muted-foreground">Sales pipeline visibility from draft through acceptance or decline.</p>
                </div>
                <div class="space-y-3">
                    <?php foreach ($proposal_segments as $segment):
                        $width = $proposal_total > 0 ? max(round(($segment['value'] / $proposal_total) * 100, 2), ($segment['value'] > 0 ? 3 : 0)) : 0;
                        $share = $proposal_total > 0 ? round(($segment['value'] / $proposal_total) * 100, 1) : 0;
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <div class="mb-2 flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2">
                                    <span class="inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                    <p class="text-sm font-semibold text-foreground"><?= $segment['label'] ?></p>
                                </div>
                                <p class="text-sm font-semibold <?= $segment['text'] ?>"><?= (int) $segment['value'] ?> <span class="text-muted-foreground">(<?= $share ?>%)</span></p>
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-muted">
                                <progress class="report-meter report-meter-<?= str_replace(array('bg-', '-500'), '', $segment['color']) ?>" max="100" value="<?= $width ?>"></progress>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>

        <section class="grid grid-cols-1 gap-6 xl:grid-cols-2">
            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= lang('client') . ' ' . lang('tickets') . ' ' . lang('report') ?></h3>
                    <p class="text-sm text-muted-foreground">Support workload across answered, open, in progress, and closed tickets.</p>
                </div>
                <div class="space-y-3">
                    <?php foreach ($ticket_segments as $segment):
                        $width = $ticket_total > 0 ? max(round(($segment['value'] / $ticket_total) * 100, 2), ($segment['value'] > 0 ? 3 : 0)) : 0;
                        $share = $ticket_total > 0 ? round(($segment['value'] / $ticket_total) * 100, 1) : 0;
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <div class="mb-2 flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2">
                                    <span class="inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                    <p class="text-sm font-semibold text-foreground"><?= $segment['label'] ?></p>
                                </div>
                                <p class="text-sm font-semibold <?= $segment['text'] ?>"><?= (int) $segment['value'] ?> <span class="text-muted-foreground">(<?= $share ?>%)</span></p>
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-muted">
                                <progress class="report-meter report-meter-<?= str_replace(array('bg-', '-500'), '', $segment['color']) ?>" max="100" value="<?= $width ?>"></progress>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="rounded-3xl border border-border bg-card p-6 shadow-sm">
                <div class="mb-4">
                    <h3 class="text-lg font-semibold text-foreground">Client Operations Report</h3>
                    <p class="text-sm text-muted-foreground">Side-by-side service and delivery totals for quick operational review.</p>
                </div>
                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="rounded-2xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('tickets') ?></p>
                        <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['tickets'] ?></p>
                        <p class="mt-2 text-xs text-muted-foreground">Answered + open + in progress + closed workload.</p>
                    </div>
                    <div class="rounded-2xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('project') ?></p>
                        <p class="mt-2 text-2xl font-bold text-foreground"><?= (int) $activity_counts['projects'] ?></p>
                        <p class="mt-2 text-xs text-muted-foreground">All active and completed delivery initiatives.</p>
                    </div>
                    <div class="rounded-2xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('open') . ' ' . lang('tickets') ?></p>
                        <p class="mt-2 text-2xl font-bold text-amber-600 dark:text-amber-300"><?= (int) $ticket_statuses['open'] + (int) $ticket_statuses['in_progress'] ?></p>
                        <p class="mt-2 text-xs text-muted-foreground">Tickets that still need action from the team.</p>
                    </div>
                    <div class="rounded-2xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('completed') . ' ' . lang('project') ?></p>
                        <p class="mt-2 text-2xl font-bold text-emerald-600 dark:text-emerald-300"><?= (int) $project_statuses['completed'] ?></p>
                        <p class="mt-2 text-xs text-muted-foreground">Projects that have reached final delivery.</p>
                    </div>
                </div>
                <div class="mt-4 space-y-3">
                    <?php
                    $ops_total = max(1, (int) $activity_counts['tickets'] + (int) $activity_counts['projects']);
                    $ops_segments = array(
                        array(
                            'label' => lang('tickets'),
                            'value' => (int) $activity_counts['tickets'],
                            'color' => 'bg-blue-500',
                            'text' => 'text-blue-600 dark:text-blue-300',
                        ),
                        array(
                            'label' => lang('project'),
                            'value' => (int) $activity_counts['projects'],
                            'color' => 'bg-emerald-500',
                            'text' => 'text-emerald-600 dark:text-emerald-300',
                        ),
                    );
                    foreach ($ops_segments as $segment):
                        $width = round(($segment['value'] / $ops_total) * 100, 2);
                        $share = round(($segment['value'] / $ops_total) * 100, 1);
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-4">
                            <div class="mb-2 flex items-center justify-between gap-3">
                                <div class="flex items-center gap-2">
                                    <span class="inline-flex h-3.5 w-3.5 rounded-full <?= $segment['color'] ?>"></span>
                                    <p class="text-sm font-semibold text-foreground"><?= $segment['label'] ?></p>
                                </div>
                                <p class="text-sm font-semibold <?= $segment['text'] ?>"><?= (int) $segment['value'] ?> <span class="text-muted-foreground">(<?= $share ?>%)</span></p>
                            </div>
                            <div class="h-3 overflow-hidden rounded-full bg-muted">
                                <progress class="report-meter report-meter-<?= str_replace(array('bg-', '-500'), '', $segment['color']) ?>" max="100" value="<?= $width ?>"></progress>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
    <?php endif; ?>
</div>

<div id="client-report-preloader" class="fixed inset-0 z-[70] hidden items-center justify-center bg-slate-950/30 backdrop-blur-sm">
    <div class="rounded-2xl border border-border bg-card px-6 py-5 shadow-2xl">
        <div class="flex items-center gap-3">
            <div class="h-5 w-5 animate-spin rounded-full border-2 border-primary/30 border-t-primary"></div>
            <div>
                <p class="text-sm font-semibold text-foreground">Loading report...</p>
                <p class="text-xs text-muted-foreground">Preparing the latest client summary.</p>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        var form = document.getElementById('client-report-form');
        var modeInput = document.getElementById('client-report-mode');
        var preloader = document.getElementById('client-report-preloader');
        var clientLookupWrap = form ? form.querySelector('[data-lookup][data-lookup-type="client"]') : null;
        var clientLookupHidden = clientLookupWrap ? clientLookupWrap.querySelector('[data-lookup-hidden]') : null;
        var clientLookupInput = clientLookupWrap ? clientLookupWrap.querySelector('[data-lookup-input]') : null;
        var lastClientId = clientLookupHidden ? clientLookupHidden.value : '';

        function showClientReportPreloader() {
            if (preloader) {
                preloader.classList.remove('hidden');
                preloader.classList.add('flex');
            }
        }

        window.clientReportAutoSubmit = function (id) {
            if (!form || !id) return;
            if (modeInput) {
                modeInput.value = 'client';
            }
            showClientReportPreloader();
            form.submit();
        };

        if (clientLookupHidden) {
            clientLookupHidden.addEventListener('change', function () {
                if (!this.value || this.value === lastClientId) return;
                lastClientId = this.value;
                window.clientReportAutoSubmit(this.value);
            });
        }

        if (clientLookupInput) {
            clientLookupInput.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    event.preventDefault();
                }
            });
        }

        var portfolioButton = document.getElementById('load-portfolio-summary');
        if (portfolioButton) {
            portfolioButton.addEventListener('click', function () {
                if (!form) return;
                if (modeInput) {
                    modeInput.value = 'portfolio';
                }
                showClientReportPreloader();
                form.submit();
            });
        }

        if (form) {
            form.addEventListener('submit', function () {
                showClientReportPreloader();
            });
        }

    });
</script>
