@include('components.profile-overview-styles')
@php
    $dealClosed = in_array((int) $deal->stage_id, [9, 10], true);
    $dealWon = (int) $deal->stage_id === 9;
    $dealStageName = $stages->firstWhere('id', $deal->stage_id)?->name ?: 'No status';
    $dealValue = (float) ($deal->grand_total ?: $deal->estimate_amount ?: 0);
    $dealActivityProgress = $reporting['activity_count'] > 0 ? (int) round($reporting['completed_activities'] / $reporting['activity_count'] * 100) : 0;
    $dealLastActivity = $activities->filter(fn ($activity) => ($activity->start_date ? \Carbon\Carbon::parse($activity->start_date.' '.($activity->start_time ?: '00:00:00')) : $activity->created_at)->lte(now()))->first();
    $dealNextActivity = $activities->filter(fn ($activity) => ($activity->start_date ? \Carbon\Carbon::parse($activity->start_date.' '.($activity->start_time ?: '00:00:00')) : $activity->created_at)->gt(now()) && !in_array($activity->lifecycle_status, ['completed', 'cancelled'], true))->sortBy('start_date')->first();
    $dealActivityDate = fn ($activity) => !$activity ? null : ($activity->start_date ? \Carbon\Carbon::parse($activity->start_date.' '.($activity->start_time ?: '00:00:00')) : $activity->created_at);
@endphp
@once
    <style>
        .deal-pro-overview .arrow-steps .step.done span:before { opacity: 1; }
        .deal-pro-overview .arrow-steps .step.deal-won { color: #fff; background: #198754; }
        .deal-pro-overview .arrow-steps .step.deal-won:after { border-left-color: #198754; }
        .deal-pro-overview .arrow-steps .step.deal-lost { color: #fff; background: #dc3545; }
        .deal-pro-overview .arrow-steps .step.deal-lost:after { border-left-color: #dc3545; }
        .deal-pro-overview .arrow-steps .step.deal-terminal-muted { color: #94a3b8; background: #f1f5f9; }
        .deal-pro-overview .arrow-steps .step.deal-terminal-muted:after { border-left-color: #f1f5f9; }
        .deal-pro-overview .deal-terminal-state { display: block; font-size: 9px; font-weight: 700; text-transform: uppercase; }
    </style>
@endonce

<div class="pro-overview deal-pro-overview" data-testid="deal-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">Deal Overview</h5><p class="text-muted mb-0">Pipeline health, commercial value, activity, and related records.</p></div>
        <div class="d-flex gap-2">
            <a href="{{ route('related-activity.index', ['deals', $deal->id]) }}" class="btn btn-sm btn-outline-primary"><i class="feather-activity me-1"></i>Activity Timeline</a>
            @if (!$dealClosed)
                @can('update_deals')<a href="{{ route('deals.edit', ['id' => $deal->id]) }}" class="btn btn-sm btn-primary"><i class="feather-edit-3 me-1"></i>Edit Deal</a>@endcan
            @endif
        </div>
    </div>

    <div class="pro-stage-scroll mb-3"><div class="arrow-steps clearfix">
        @foreach ($stages as $dealStage)
            @php
                $dealStageId = (int) $dealStage->id;
                $selectedTerminal = $dealClosed && $dealStageId === (int) $deal->stage_id;
                $completedPath = $dealClosed ? $dealStageId <= 8 || $selectedTerminal : $dealStageId <= (int) $deal->stage_id;
            @endphp
            <div @class(['step', 'current' => $completedPath, 'done' => $dealClosed && $completedPath, 'deal-won' => $dealWon && $selectedTerminal, 'deal-lost' => $dealClosed && !$dealWon && $selectedTerminal, 'deal-terminal-muted' => $dealClosed && in_array($dealStageId, [9, 10], true) && !$selectedTerminal]) data-stage-id="{{ $dealStageId }}">
                <span>{{ $dealStage->name }}@if($selectedTerminal)<small class="deal-terminal-state">Completed</small>@endif</span>
            </div>
        @endforeach
    </div></div>

    <div class="row g-3 mb-4">
        @foreach ([
            ['icon'=>'feather-dollar-sign','tone'=>'primary','value'=>$deal->currency_name.' '.number_format($dealValue, 2),'label'=>'Deal Value','hint'=>'Current commercial value'],
            ['icon'=>'feather-percent','tone'=>'warning','value'=>(int) ($deal->close_probability ?? 0).'%','label'=>'Win Probability','hint'=>'Forecast confidence'],
            ['icon'=>'feather-trending-up','tone'=>'success','value'=>$deal->currency_name.' '.number_format((float) $reporting['forecast_value'], 2),'label'=>'Forecast Value','hint'=>'Weighted projection'],
            ['icon'=>'feather-activity','tone'=>'info','value'=>$dealActivityProgress.'%','label'=>'Activity Completion','hint'=>$reporting['completed_activities'].' of '.$reporting['activity_count'].' completed'],
        ] 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-briefcase"></i></span><div><h6 class="fw-bold mb-0">Deal Information</h6><small class="text-muted">Pipeline and ownership</small></div></div><div class="pro-panel-body">
            <div class="pro-detail"><span class="pro-label">Deal Status</span><span class="pro-value"><span class="badge {{ $dealWon ? 'bg-success' : ($dealClosed ? 'bg-danger' : 'bg-primary') }}">{{ $dealStageName }}{{ $dealClosed ? ' · Completed' : '' }}</span></span></div>
            @foreach ([['Owner', $deal->assignedUser?->name ?: 'Not assigned'], ['Priority', $deal->priority?->name ?: 'Not set'], ['Deal Type', ucfirst($deal->deal_type ?: 'Not set')], ['Created', $deal->create_date?->format('d M Y, h:i A') ?: 'Not provided'], ['Expected Close', $deal->closing_date?->format('d M Y') ?: 'Not provided'], ['Days Open', $reporting['days_open'] !== null ? $reporting['days_open'].' days' : 'Not available']] 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-users"></i></span><div><h6 class="fw-bold mb-0">Relationships & Billing</h6><small class="text-muted">Customer and payment context</small></div></div><div class="pro-panel-body">
            @foreach ([['Contact', $deal->contact ? trim($deal->contact->first_name.' '.$deal->contact->last_name) : 'Not linked'], ['Account', $deal->accounts->first()?->account_name ?: 'Not linked'], ['Products', $reporting['product_count'].' line item(s)'], ['Documents', $tradeDocuments->count().' document(s)'], ['Billing Frequency', $deal->billingFrequency?->name ?: 'Not set'], ['Payment Status', ucwords(str_replace('_', ' ', $deal->payment_status ?: 'not set'))], ['Paid Total', $deal->currency_name.' '.number_format((float) $reporting['paid_total'], 2)]] 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">
        <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">Latest and upcoming Deal engagement</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>{{ $dealLastActivity?->title ?: 'No activity yet' }}</strong>@if($dealActivityDate($dealLastActivity))<small class="text-muted d-block">{{ $dealActivityDate($dealLastActivity)->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>{{ $dealNextActivity?->title ?: 'Nothing scheduled' }}</strong>@if($dealActivityDate($dealNextActivity))<small class="text-muted d-block">{{ $dealActivityDate($dealNextActivity)->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-bar-chart-2"></i></span><div><h6 class="fw-bold mb-0">Delivery Snapshot</h6><small class="text-muted">Post-sale readiness</small></div></div><div class="pro-panel-body">
            <div class="pro-detail"><span class="pro-label">Projects</span><span class="pro-value">{{ $projects->count() }}</span></div>
            <div class="pro-detail"><span class="pro-label">Cases</span><span class="pro-value">{{ $cases->count() }}</span></div>
            <div class="pro-detail"><span class="pro-label">Delivery Status</span><span class="pro-value">{{ ucwords(str_replace('_', ' ', $deal->delivery_status ?: 'Not set')) }}</span></div>
            <div class="pro-detail"><span class="pro-label">Competitors</span><span class="pro-value">{{ $competitors->count() }}</span></div>
        </div></section></div>
    </div>
</div>
