@include('components.profile-overview-styles')
@php
    $accountPipelineValue = $deals->sum(fn ($deal) => (float) ($deal->grand_total ?: $deal->estimate_amount ?: 0));
    $accountCompletedActivities = $activities->filter(fn ($activity) => in_array(strtolower((string) ($activity->lifecycle_status ?: $activity->status)), ['completed', 'done'], true))->count();
    $accountEmail = $account->contactEmails->first()?->email;
    $accountPhone = $account->contactPhones->first()?->phone;
    $accountLanguages = $account->contactLanguages->pluck('language.name')->filter()->join(', ');
    $accountActivityDate = fn ($activity) => !$activity ? null : ($activity->start_date ? \Carbon\Carbon::parse($activity->start_date.' '.($activity->start_time ?: '00:00:00')) : $activity->created_at);
    $accountLastActivity = $activities->filter(fn ($activity) => $accountActivityDate($activity)?->lte(now()))->first();
    $accountNextActivity = $activities->filter(fn ($activity) => $accountActivityDate($activity)?->gt(now()) && !in_array($activity->lifecycle_status, ['completed', 'cancelled'], true))->sortBy(fn ($activity) => $accountActivityDate($activity))->first();
    $accountContactMethods = collect($account->contact_method ?: [])->filter()->map(fn ($method) => ucwords((string) $method))->join(', ');
@endphp

<div class="pro-overview" data-testid="account-profile-overview">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
        <div><h5 class="fw-bold mb-1">Account Overview</h5><p class="text-muted mb-0">Commercial performance, relationships, and Account details.</p></div>
        <div class="d-flex gap-2">
            <a href="{{ route('related-activity.index', ['accounts', $account->id]) }}" class="btn btn-sm btn-outline-primary"><i class="feather-activity me-1"></i>Activity Timeline</a>
            @can('update_accounts')<a href="{{ route('account.edit', ['id' => $account->id]) }}" class="btn btn-sm btn-primary"><i class="feather-edit-3 me-1"></i>Edit Account</a>@endcan
        </div>
    </div>

    <div class="row g-3 mb-4">
        @foreach ([
            ['icon'=>'feather-users','tone'=>'primary','value'=>$account->contacts->count(),'label'=>'Contacts','hint'=>'Linked people'],
            ['icon'=>'feather-target','tone'=>'warning','value'=>$leads->count(),'label'=>'Leads','hint'=>'Related Leads'],
            ['icon'=>'feather-briefcase','tone'=>'success','value'=>$deals->count(),'label'=>'Deals','hint'=>'Sales opportunities'],
            ['icon'=>'feather-dollar-sign','tone'=>'info','value'=>number_format($accountPipelineValue, 2),'label'=>'Pipeline Value','hint'=>'Closed Won: '.number_format((float) $closedDealValue, 2)],
        ] as $metric)
            <div class="col-sm-6 col-xl-3"><div class="pro-metric"><div class="d-flex align-items-center justify-content-between mb-3"><span class="pro-icon bg-soft-{{ $metric['tone'] }} text-{{ $metric['tone'] }}"><i class="{{ $metric['icon'] }}"></i></span><strong class="fs-6 text-end">{{ $metric['value'] }}</strong></div><div class="fw-semibold">{{ $metric['label'] }}</div><small class="text-muted">{{ $metric['hint'] }}</small></div></div>
        @endforeach
    </div>

    <div class="row g-4 mb-4">
        <div class="col-xl-6"><section class="pro-panel"><div class="pro-panel-header"><span class="pro-icon bg-soft-primary text-primary"><i class="feather-home"></i></span><div><h6 class="fw-bold mb-0">Account Information</h6><small class="text-muted">Identity and business classification</small></div></div><div class="pro-panel-body">
            @foreach ([['Account Name', $account->account_name ?: 'Not provided'], ['Account Number', $account->account_number ?: 'Not provided'], ['Primary Contact', $account->primaryContact ? trim($account->primaryContact->first_name.' '.$account->primaryContact->last_name) : 'Not assigned'], ['Owner', $account->assignedUser?->name ?: 'Not assigned'], ['Type', ucfirst($account->account_type ?: 'Not set')], ['Ownership', ucfirst($account->ownership ?: 'Not set')], ['Status', ucfirst($account->status ?: 'active')], ['Rating', $account->rating ? $account->rating.'/5' : 'Not rated']] as [$label, $value])
                <div class="pro-detail"><span class="pro-label">{{ $label }}</span><span class="pro-value">{{ $value }}</span></div>
            @endforeach
        </div></section></div>
        <div class="col-xl-6"><section class="pro-panel"><div class="pro-panel-header"><span class="pro-icon bg-soft-success text-success"><i class="feather-phone"></i></span><div><h6 class="fw-bold mb-0">Contact & Commercial</h6><small class="text-muted">Communication and financial terms</small></div></div><div class="pro-panel-body">
            @foreach ([['Email', $accountEmail ?: 'Not provided'], ['Phone', $accountPhone ?: 'Not provided'], ['Website', $account->website ?: 'Not provided'], ['Languages', $accountLanguages ?: 'Not provided'], ['Contact Method', $accountContactMethods ?: 'Not selected'], ['Annual Revenue', number_format((float) ($account->total_revenue ?? 0), 2)], ['Credit Limit', number_format((float) ($account->credit_limit ?? 0), 2)], ['Payment Terms', $account->payment_terms ?: 'Not set']] as [$label, $value])
                <div class="pro-detail"><span class="pro-label">{{ $label }}</span><span class="pro-value">{{ $value }}</span></div>
            @endforeach
        </div></section></div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-xl-7"><section class="pro-panel"><div class="pro-panel-header"><span class="pro-icon bg-soft-warning text-warning"><i class="feather-clock"></i></span><div><h6 class="fw-bold mb-0">Activity Snapshot</h6><small class="text-muted">{{ $accountCompletedActivities }} of {{ $activities->count() }} activities completed</small></div></div><div class="pro-panel-body py-3"><div class="row g-3">
            <div class="col-md-6"><div class="pro-snapshot"><i class="feather-check-circle"></i><small class="text-muted d-block">Last interaction</small><strong>{{ $accountLastActivity?->title ?: 'No activity yet' }}</strong>@if($accountActivityDate($accountLastActivity))<small class="text-muted d-block">{{ $accountActivityDate($accountLastActivity)->format('d M Y, h:i A') }}</small>@endif</div></div>
            <div class="col-md-6"><div class="pro-snapshot"><i class="feather-calendar"></i><small class="text-muted d-block">Next interaction</small><strong>{{ $accountNextActivity?->title ?: 'Nothing scheduled' }}</strong>@if($accountActivityDate($accountNextActivity))<small class="text-muted d-block">{{ $accountActivityDate($accountNextActivity)->format('d M Y, h:i A') }}</small>@endif</div></div>
        </div></div></section></div>
        <div class="col-xl-5"><section class="pro-panel"><div class="pro-panel-header"><span class="pro-icon bg-soft-info text-info"><i class="feather-map-pin"></i></span><div><h6 class="fw-bold mb-0">Billing Address</h6><small class="text-muted">Primary Account location</small></div></div><div class="pro-panel-body">
            <div class="pro-detail"><span class="pro-label">Address</span><span class="pro-value">{{ collect([$account->billing_address_1, $account->billing_address_2])->filter()->join(', ') ?: 'Not provided' }}</span></div>
            <div class="pro-detail"><span class="pro-label">City / Province</span><span class="pro-value">{{ collect([$account->billing_city, $account->billing_province])->filter()->join(', ') ?: 'Not provided' }}</span></div>
            <div class="pro-detail"><span class="pro-label">Country</span><span class="pro-value">{{ $account->billingCountry?->name ?: 'Not provided' }}</span></div>
            <div class="pro-detail"><span class="pro-label">Zip Code</span><span class="pro-value">{{ $account->billing_zip_code ?: 'Not provided' }}</span></div>
            <div class="pro-detail"><span class="pro-label">Parent Account</span><span class="pro-value">{{ $account->parentAccount?->account_name ?: 'None' }}</span></div>
        </div></section></div>
    </div>

    <div class="row g-4">
        <div class="col-xl-6"><section class="pro-panel"><div class="pro-panel-header"><span class="pro-icon bg-soft-primary text-primary"><i class="feather-target"></i></span><div><h6 class="fw-bold mb-0">Recent Leads</h6><small class="text-muted">Latest related Lead profiles</small></div></div><div class="pro-panel-body">
            @forelse($leads->take(4) as $lead)<a class="pro-record-link" href="{{ route('leads.view', ['id'=>$lead->id]) }}"><span><strong class="d-block">{{ $lead->topic ?: trim($lead->first_name.' '.$lead->last_name) }}</strong><small class="text-muted">{{ $lead->assignedUser?->name ?: 'Not assigned' }}</small></span><i class="feather-arrow-right"></i></a>@empty<div class="text-muted py-4 text-center">No related Leads.</div>@endforelse
        </div></section></div>
        <div class="col-xl-6"><section class="pro-panel"><div class="pro-panel-header"><span class="pro-icon bg-soft-success text-success"><i class="feather-briefcase"></i></span><div><h6 class="fw-bold mb-0">Recent Deals</h6><small class="text-muted">Latest Account opportunities</small></div></div><div class="pro-panel-body">
            @forelse($deals->take(4) as $deal)<a class="pro-record-link" href="{{ route('deals.view', ['id'=>$deal->id]) }}"><span><strong class="d-block">{{ $deal->name }}</strong><small class="text-muted">{{ $deal->currency_name }} {{ number_format((float) ($deal->grand_total ?: $deal->estimate_amount), 2) }}</small></span><i class="feather-arrow-right"></i></a>@empty<div class="text-muted py-4 text-center">No related Deals.</div>@endforelse
        </div></section></div>
    </div>
</div>
