<div class="content-wrapper">
<section class="content pt-3">

<?php
use Core\App\Services\Shipping\EcotrackStatusMapper;
use Core\App\Services\Shipping\ShippingStatusPresenter;

$provider = strtolower((string)($shipping['provider'] ?? ''));

if ($provider === 'maystro') {
    $statusCode = isset($shipping['status_code']) ? (int)$shipping['status_code'] : null;
    $meta     = ShippingStatusPresenter::meta($provider, $shipping['status'] ?? null, $statusCode);
    $timeline = ShippingStatusPresenter::timeline($provider, $shipping);
} else {
    $meta = EcotrackStatusMapper::meta($shipping['status'] ?? null);
    $timeline = [
        'type'        => 'steps',
        'steps'       => EcotrackStatusMapper::timelineSteps(),
        'activeIndex' => EcotrackStatusMapper::activeIndex($shipping['status'] ?? null),
    ];
}

$mappedStatus = [
    'label' => __($meta['label_key'], $meta['fallback']),
    'badge' => $meta['badge'],
    'group' => $meta['group'],
];

// For Maystro: get ALL 18 statuses for full display
$allMaystroStatuses = ($provider === 'maystro')
    ? ShippingStatusPresenter::allMaystroStatuses()
    : [];

$currentCode = ($provider === 'maystro')
    ? ShippingStatusPresenter::normalizeMaystroStatus(
        $shipping['status'] ?? null,
        isset($shipping['status_code']) ? (int)$shipping['status_code'] : null
    )
    : null;
?>

<style>
.tracking-status-item { padding: 10px 16px; border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; gap: 12px; }
.tracking-status-item:last-child { border-bottom: none; }
.tracking-status-item .ts-icon { font-size: 18px; width: 28px; text-align: center; }
.tracking-status-item .ts-label { flex: 1; font-size: 14px; }
.tracking-status-item.ts-done .ts-icon { color: #22c55e; }
.tracking-status-item.ts-current .ts-icon { color: #3b82f6; }
.tracking-status-item.ts-current .ts-label { font-weight: 700; color: #1d4ed8; }
.tracking-status-item.ts-current-issue .ts-icon { color: #f59e0b; }
.tracking-status-item.ts-current-issue .ts-label { font-weight: 700; color: #b45309; }
.tracking-status-item.ts-future .ts-icon { color: #d1d5db; }
.tracking-status-item.ts-future .ts-label { color: #9ca3af; }
.tracking-status-item.ts-issue-group { background: #fffbeb; }
.tracking-group-header { padding: 6px 16px; background: #f3f4f6; font-size: 12px; font-weight: 600; color: #6b7280; text-transform: uppercase; letter-spacing: .5px; }
</style>

<div class="container-fluid py-4 pb-5">
    <div class="card shadow-sm">
        <div class="card-body">

            <h4 class="mb-4">
                <i class="bi bi-truck me-2"></i>
                <?= __('tracking.result', 'Shipment Tracking') ?>
                <span class="text-muted">#<?= (int)$order['id'] ?></span>
            </h4>

            <!-- Summary Row -->
            <div class="row mb-4 g-3">
                <div class="col-md-4">
                    <div class="text-muted small mb-1"><?= __('tracking.provider', 'شركة التوصيل') ?></div>
                    <strong><?= strtoupper(htmlspecialchars($shipping['provider'] ?? '-')) ?></strong>
                </div>
                <div class="col-md-4">
                    <div class="text-muted small mb-1"><?= __('tracking.number', 'رقم التتبع') ?></div>
                    <code><?= htmlspecialchars($shipping['tracking'] ?? '-') ?></code>
                </div>
                <div class="col-md-4">
                    <div class="text-muted small mb-1"><?= __('tracking.status', 'الحالة') ?></div>
                    <span class="badge <?= $mappedStatus['badge'] ?> fs-6">
                        <?= htmlspecialchars($mappedStatus['label']) ?>
                    </span>
                </div>
            </div>

            <hr>

            <h5 class="mb-3">
                <i class="bi bi-list-check me-1"></i>
                <?= __('tracking.timeline', 'مراحل التتبع') ?>
            </h5>

            <?php if ($provider === 'maystro' && !empty($allMaystroStatuses)): ?>

                <?php
                // Determine order of statuses reached so far
                // Main progress flow (in order)
                $mainFlow = [
                    'CREATED', 'PICK_UP_REQUESTED', 'IN_PROCESS',
                    'WAITING_TRANSIT', 'IN_TRANSIT_TO_BE_SHIPPED',
                    'READY_TO_SHIP', 'ASSIGNED', 'SHIPPED', 'DELIVERED',
                ];
                $issueStatuses = [
                    'IN_TRANSIT_TO_BE_RETURNED', 'PENDING', 'OUT_OF_STOCK',
                    'ALERTED', 'POSTPONED', 'ABORTED',
                    'READY_TO_RETURN', 'TAKEN_BY_STORE', 'NOT_RECEIVED',
                ];

                $currentIsIssue  = in_array($currentCode, $issueStatuses, true);
                $currentMainIdx  = array_search($currentCode, $mainFlow);

                // For issue status, find which main step it's associated with
                $issueMainStep = [
                    'IN_TRANSIT_TO_BE_RETURNED' => 'SHIPPED',
                    'PENDING'                   => 'IN_PROCESS',
                    'OUT_OF_STOCK'              => 'IN_PROCESS',
                    'ALERTED'                   => 'SHIPPED',
                    'POSTPONED'                 => 'SHIPPED',
                    'ABORTED'                   => 'SHIPPED',
                    'READY_TO_RETURN'           => 'SHIPPED',
                    'TAKEN_BY_STORE'            => 'SHIPPED',
                    'NOT_RECEIVED'              => 'SHIPPED',
                ];

                if ($currentIsIssue) {
                    $associatedMain = $issueMainStep[$currentCode] ?? 'SHIPPED';
                    $currentMainIdx = array_search($associatedMain, $mainFlow);
                    if ($currentMainIdx === false) $currentMainIdx = count($mainFlow) - 2;
                }
                ?>

                <!-- Main Progress Flow -->
                <div class="border rounded mb-3" style="overflow:hidden">
                    <div class="tracking-group-header">
                        <i class="bi bi-arrow-right-circle me-1"></i>
                        <?= __('tracking.main_flow', 'مسار التوصيل') ?>
                    </div>
                    <?php foreach ($mainFlow as $idx => $code):
                        $entry = $allMaystroStatuses[$code] ?? null;
                        if (!$entry) continue;
                        [$ar, $en, $badge, $group, $icon] = $entry;
                        $label = __('shipping.maystro.status.' . strtolower($code), $en);

                        if (!$currentIsIssue && $code === $currentCode) {
                            $cls = 'ts-current';
                            $dot = '▶';
                        } elseif ($currentIsIssue && $idx <= $currentMainIdx) {
                            $cls = 'ts-done';
                            $dot = '✓';
                        } elseif (!$currentIsIssue && $currentMainIdx !== false && $idx < $currentMainIdx) {
                            $cls = 'ts-done';
                            $dot = '✓';
                        } else {
                            $cls = 'ts-future';
                            $dot = '○';
                        }
                    ?>
                    <div class="tracking-status-item <?= $cls ?>">
                        <span class="ts-icon"><i class="bi <?= htmlspecialchars($icon) ?>"></i></span>
                        <span class="ts-label"><?= htmlspecialchars($label) ?></span>
                        <?php if (!$currentIsIssue && $code === $currentCode): ?>
                            <span class="badge bg-primary"><?= __('tracking.current', 'الحالة الحالية') ?></span>
                        <?php elseif ($cls === 'ts-done'): ?>
                            <i class="bi bi-check-circle-fill text-success"></i>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- Issue/Exception Statuses -->
                <div class="border rounded mb-3" style="overflow:hidden">
                    <div class="tracking-group-header" style="background:#fffbeb;color:#92400e">
                        <i class="bi bi-exclamation-triangle me-1"></i>
                        <?= __('tracking.exception_statuses', 'حالات استثنائية') ?>
                    </div>
                    <?php foreach ($issueStatuses as $code):
                        $entry = $allMaystroStatuses[$code] ?? null;
                        if (!$entry) continue;
                        [$ar, $en, $badge, $group, $icon] = $entry;
                        $label = __('shipping.maystro.status.' . strtolower($code), $en);

                        if ($code === $currentCode) {
                            $cls = 'ts-current-issue';
                        } else {
                            $cls = 'ts-future ts-issue-group';
                        }
                    ?>
                    <div class="tracking-status-item <?= $cls ?>">
                        <span class="ts-icon"><i class="bi <?= htmlspecialchars($icon) ?>"></i></span>
                        <span class="ts-label"><?= htmlspecialchars($label) ?></span>
                        <?php if ($code === $currentCode): ?>
                            <span class="badge bg-warning text-dark"><?= __('tracking.current', 'الحالة الحالية') ?></span>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>

            <?php elseif (!empty($timeline['steps'])): ?>

                <!-- Non-Maystro steps -->
                <ul class="list-group list-group-flush">
                    <?php foreach ($timeline['steps'] as $i => $step):
                        $done    = $i <= ($timeline['activeIndex'] ?? -1);
                        $current = $i === ($timeline['activeIndex'] ?? -1);
                    ?>
                    <li class="list-group-item d-flex align-items-center py-2">
                        <i class="bi <?= htmlspecialchars($step['icon'] ?? 'bi-circle') ?> <?= $done ? 'text-success' : 'text-muted' ?> me-3 fs-5"></i>
                        <span class="<?= $current ? 'fw-bold text-primary' : ($done ? '' : 'text-muted') ?>">
                            <?= htmlspecialchars(__($step['label_key'], $step['fallback'])) ?>
                        </span>
                    </li>
                    <?php endforeach; ?>
                </ul>

            <?php else: ?>
                <div class="alert alert-secondary"><?= __('tracking.no_timeline', 'No tracking details available yet') ?></div>
            <?php endif; ?>

            <!-- Lifecycle events (if available) -->
            <?php $events = $timeline['events'] ?? []; ?>
            <?php if (!empty($events)): ?>
            <details class="mt-3">
                <summary class="text-muted small" style="cursor:pointer">
                    <i class="bi bi-clock-history me-1"></i>
                    <?= __('tracking.details', 'تفاصيل الأحداث') ?> (<?= count($events) ?>)
                </summary>
                <ul class="list-group list-group-flush mt-2">
                    <?php foreach ($events as $event):
                        $evGroup = $event['group'] ?? 'in_progress';
                        $evIcon  = $event['icon']  ?? 'bi-circle';
                        $evColor = match($evGroup) {
                            'delivered' => 'text-success',
                            'issues'    => 'text-warning',
                            default     => 'text-primary',
                        };
                    ?>
                    <li class="list-group-item py-2">
                        <div class="d-flex align-items-start gap-3">
                            <i class="bi <?= htmlspecialchars($evIcon) ?> <?= $evColor ?> fs-5 mt-1"></i>
                            <div>
                                <div class="fw-semibold"><?= htmlspecialchars($event['label']) ?></div>
                                <?php if (!empty($event['note'])): ?>
                                    <div class="text-muted small"><?= htmlspecialchars($event['note']) ?></div>
                                <?php endif; ?>
                                <?php if (!empty($event['date'])): ?>
                                    <div class="text-muted small mt-1"><i class="bi bi-clock me-1"></i><?= htmlspecialchars($event['date']) ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </details>
            <?php endif; ?>

            <!-- Actions -->
            <div class="mt-4 d-flex justify-content-between">
                <a href="/admin/shipments" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i>
                    <?= __('actions.back', 'Back') ?>
                </a>
                <?php if (!empty($shipping['tracking'])): ?>
                    <button type="button" class="btn btn-outline-primary"
                            onclick="navigator.clipboard.writeText('<?= htmlspecialchars($shipping['tracking']) ?>')">
                        <i class="bi bi-clipboard"></i>
                        <?= __('actions.copy', 'Copy') ?>
                    </button>
                <?php endif; ?>
            </div>

        </div>
    </div>
</div>

</section>
</div>
