<style>
    /*
     * The Sales Order actions are rendered manually inside
     * the card's top row.
     *
     * Keep the Filament actions registered because the custom
     * buttons use mountTableAction() to execute them.
     *
     * .fi-ta-record-actions doesn't exist in this Filament version —
     * the actions column actually renders as .fi-ta-actions (and its
     * wrapping .fi-ta-actions-cell). Covering all of these so this
     * keeps working regardless of version.
     */
    .fi-ta-record-actions,
    .fi-ta-actions,
    .fi-ta-actions-cell {
        display: none !important;
    }
</style>

@php
    /** @var \App\Models\Sales\SalesOrder $record */
    $record = $getRecord();

    $total = max((float) $record->net_total, 0);
    $paid = max((float) $record->advance_paid, 0);
    $balance = max((float) $record->balance, 0);

    $paymentPercent = $total > 0
        ? min(100, max(0, ($paid / $total) * 100))
        : 0;

    $statusCode = $record->status?->code;

    $statusSteps = [
        'confirmed',
        'in_production',
        'ready',
        'invoiced',
    ];

    $currentStep = match ($statusCode) {
        'confirmed' => 0,
        'in_production' => 1,
        'ready' => 2,
        'invoiced' => 3,
        default => null,
    };

    // Ties the left rail's accent to where the order actually is, instead of
    // a flat gray that barely registers against a white card in light mode.
    $railColor = match (true) {
        $currentStep === 3 => 'bg-success-500',
        $currentStep === 2 => 'bg-primary-500',
        $currentStep === 1 => 'bg-warning-500',
        $currentStep === 0 => 'bg-gray-400 dark:bg-gray-500',
        default => 'bg-gray-300 dark:bg-gray-600',
    };

    $deadlineDays = $record->daysToDeadline();

    $deadlineText = match (true) {
        $deadlineDays === null => 'No deadline',
        $deadlineDays < 0 => abs($deadlineDays) . ' day(s) overdue',
        $deadlineDays === 0 => 'Due today',
        $deadlineDays === 1 => 'Due tomorrow',
        default => 'In ' . $deadlineDays . ' days',
    };

    // Look the status column up by name rather than a numeric array index —
    // ->components([...]) order is easy to reshuffle later, and an index
    // lookup silently renders the wrong column (or errors) the moment it does.
    $statusColumn = collect($getComponents())->first(
        fn ($component) => method_exists($component, 'getName') && $component->getName() === 'status_id'
    );

    // Where "WhatsApp" sends this order, per Master Control → tenant → Sales
    // Orders. Null (no destination configured, or one that isn't a usable
    // number/link) hides the button rather than offering one that goes nowhere.
    $salesOrderService = app(\App\Services\SalesOrderService::class);
    $whatsappLink = $salesOrderService->whatsappLink($record);
    $whatsappIsGroup = $whatsappLink !== null && app(\App\Services\AppSettings::class)->salesOrderWhatsappIsGroup();
    // Only built for the group case — a one-to-one link already carries it.
    $whatsappMessage = $whatsappIsGroup ? $salesOrderService->whatsappMessage($record) : null;
@endphp

<div
    class="
        group
        relative
        overflow-hidden
        rounded-xl
        border
        border-gray-200
        bg-white
        shadow-sm
        ring-1
        ring-gray-950/[0.02]
        transition
        duration-200
        hover:shadow-md
        hover:ring-gray-950/[0.04]
        dark:border-white/10
        dark:bg-gray-900
        dark:ring-0
        dark:hover:ring-0
    "
>
    {{-- Status-coded left rail --}}
    <div class="absolute inset-y-0 left-0 w-1 {{ $railColor }}"></div>

    <div class="p-5 pl-6">

        {{-- ========================================================= --}}
        {{-- TOP ROW                                                   --}}
        {{-- ========================================================= --}}

        <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">

            {{-- LEFT --}}
            <div class="min-w-0 flex-1">

                <div class="flex flex-wrap items-center gap-2">

                    <div class="text-sm font-semibold tracking-tight text-primary-600 dark:text-primary-400">
                        {{ $record->order_number }}
                    </div>

                    {{-- Status --}}
                    @if ($statusColumn)
                        <div class="min-w-[130px]">
                            {{ $statusColumn
                                ->record($record)
                                ->recordKey($getRecordKey())
                                ->rowLoop($getRowLoop())
                                ->renderInLayout()
                            }}
                        </div>
                    @endif

                </div>

                {{-- Customer --}}
                <div class="mt-2 text-lg font-semibold text-gray-950 dark:text-white">
                    {{ $record->customer?->business_name ?? 'Walk-in customer' }}
                </div>

                @if ($record->customer?->phone)
                    <div class="mt-0.5 text-sm text-gray-500 dark:text-gray-400">
                        {{ $record->customer->phone }}
                    </div>
                @endif

                {{-- Meta --}}
                <div class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-gray-500 dark:text-gray-400">

                    <span class="inline-flex items-center gap-1.5">
                        <x-heroicon-o-calendar class="h-4 w-4" />
                        {{ $record->order_date?->format('d M Y') }}
                    </span>

                    @if ($record->branch)
                        <span class="inline-flex items-center gap-1.5">
                            <x-heroicon-o-building-storefront class="h-4 w-4" />
                            {{ $record->branch->name }}
                        </span>
                    @endif

                    @if ($record->creator)
                        <span class="inline-flex items-center gap-1.5">
                            <x-heroicon-o-user class="h-4 w-4" />
                            {{ $record->creator->name }}
                        </span>
                    @endif

                    <span class="inline-flex items-center gap-1.5">
                        <x-heroicon-o-cube class="h-4 w-4" />
                        {{ $record->items_count ?? $record->items()->count() }} lines
                    </span>

                    @if (($record->custom_items_count ?? $record->customItems()->count()) > 0)
                        <span class="inline-flex items-center gap-1.5">
                            <x-heroicon-o-sparkles class="h-4 w-4" />
                            {{ $record->custom_items_count ?? $record->customItems()->count() }} custom
                        </span>
                    @endif

                </div>

            </div>


            {{-- ========================================================= --}}
            {{-- TOP-RIGHT ACTIONS                                         --}}
            {{-- ========================================================= --}}

            <div class="flex shrink-0 flex-wrap items-center justify-end gap-2">

                {{-- View --}}
                @if (\App\Filament\Resources\SalesOrderResource::canView($record))
                    <a
                        href="{{ \App\Filament\Resources\SalesOrderResource\Pages\ViewSalesOrder::getUrl(['record' => $record]) }}"
                        class="
                            inline-flex items-center gap-2
                            rounded-lg
                            bg-gray-600
                            px-4 py-2.5
                            text-sm font-semibold
                            text-white
                            shadow-sm
                            transition
                            hover:bg-gray-500
                        "
                    >
                        <x-heroicon-o-eye class="h-5 w-5" />
                        View
                    </a>
                @endif


                {{-- Edit --}}
                @if (\App\Filament\Resources\SalesOrderResource::canEdit($record))
                    <a
                        href="{{ \App\Filament\Resources\SalesOrderResource\Pages\EditSalesOrder::getUrl(['record' => $record]) }}"
                        class="
                            inline-flex items-center gap-2
                            rounded-lg
                            bg-primary-600
                            px-4 py-2.5
                            text-sm font-semibold
                            text-white
                            shadow-sm
                            transition
                            hover:bg-primary-500
                        "
                    >
                        <x-heroicon-o-pencil-square class="h-5 w-5" />
                        Edit
                    </a>
                @endif


                {{-- Add Payment — offered on a converted order too, but never on
                     a cancelled one: the same gate addPaymentAction() and
                     SalesOrderService::recordPayment() apply. --}}
                @if (
                    ! $record->isCancelled()
                    && (float) $record->balance > 0.001
                    && \App\Filament\Support\Perm::can('isms_sales_orders', 'edit')
                    && \App\Filament\Resources\SalesOrderResource::ownsOrViewAll($record)
                )
                    <button
                        type="button"
                        wire:click="mountTableAction('addPayment', '{{ $getRecordKey() }}')"
                        class="
                            inline-flex items-center gap-2
                            rounded-lg
                            bg-primary-600
                            px-4 py-2.5
                            text-sm font-semibold
                            text-white
                            shadow-sm
                            transition
                            hover:bg-primary-500
                        "
                    >
                        <x-heroicon-o-banknotes class="h-5 w-5" />
                        Add payment
                    </button>
                @endif


                {{-- Invoice --}}
                @if (
                    $record->isOpen()
                    && \App\Filament\Support\Perm::can('isms_sales_orders', 'invoice')
                    && \App\Filament\Resources\SalesOrderResource::ownsOrViewAll($record)
                )
                    <button
                        type="button"
                        wire:click="mountTableAction('convertToInvoice', '{{ $getRecordKey() }}')"
                        class="
                            inline-flex items-center gap-2
                            rounded-lg
                            bg-success-600
                            px-4 py-2.5
                            text-sm font-semibold
                            text-white
                            shadow-sm
                            transition
                            hover:bg-success-500
                        "
                    >
                        <x-heroicon-o-document-text class="h-5 w-5" />
                        Invoice
                    </button>
                @endif


                {{-- Cancel --}}
                @if (
                    $record->isOpen()
                    && \App\Filament\Support\Perm::can('isms_sales_orders', 'cancel')
                    && \App\Filament\Resources\SalesOrderResource::ownsOrViewAll($record)
                )
                    <button
                        type="button"
                        wire:click="mountTableAction('cancel', '{{ $getRecordKey() }}')"
                        class="
                            inline-flex items-center gap-2
                            rounded-lg
                            bg-danger-600
                            px-4 py-2.5
                            text-sm font-semibold
                            text-white
                            shadow-sm
                            transition
                            hover:bg-danger-500
                        "
                    >
                        <x-heroicon-o-x-circle class="h-5 w-5" />
                        Cancel
                    </button>
                @endif


                {{-- WhatsApp --}}
                @if ($whatsappLink !== null)
                    {{--
                        Two shapes, and the difference is WhatsApp's, not ours:

                        - A one-to-one chat (wa.me/<number>) takes ?text=, so
                          the whole order arrives pre-filled and the sender only
                          has to hit send. A plain link is all that needs.

                        - A group invite (chat.whatsapp.com/…) accepts no
                          message parameter at all — there is no way to pre-fill
                          a group message from a link. So the order text is
                          copied to the clipboard first and the group is opened
                          for pasting, which is the closest WhatsApp allows.
                    --}}
                    <a
                        href="{{ $whatsappLink }}"
                        target="_blank"
                        rel="noopener"
                        @if ($whatsappIsGroup)
                            x-data="{
                                message: @js($whatsappMessage),
                                async copyThenOpen() {
                                    try {
                                        await navigator.clipboard.writeText(this.message);
                                        new FilamentNotification()
                                            .title('Order copied')
                                            .body('Paste it into the group — WhatsApp cannot pre-fill a group message.')
                                            .success()
                                            .send();
                                    } catch (e) {
                                        // Clipboard blocked (insecure origin, or
                                        // permission denied): the group still
                                        // opens, so say what did not happen
                                        // rather than failing silently.
                                        new FilamentNotification()
                                            .title('Could not copy the order')
                                            .body('The group is opening — copy the order details across by hand.')
                                            .warning()
                                            .send();
                                    }
                                },
                            }"
                            x-on:click="copyThenOpen()"
                        @endif
                        class="
                            inline-flex items-center gap-2
                            rounded-lg
                            bg-success-600
                            px-4 py-2.5
                            text-sm font-semibold
                            text-white
                            shadow-sm
                            transition
                            hover:bg-success-500
                        "
                    >
                        <x-heroicon-o-chat-bubble-left-right class="h-5 w-5" />
                        WhatsApp
                    </a>
                @endif

            </div>


            {{-- RIGHT FINANCIAL AREA --}}
            <div class="shrink-0 lg:min-w-[220px] lg:text-right">

                <div class="text-xl font-bold tracking-tight text-gray-950 dark:text-white">
                    {{ number_format($total, 2) }}
                </div>

                <div class="mt-0.5 text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">
                    Order value
                </div>

                <div class="mt-3 text-sm font-semibold text-success-600 dark:text-success-400">
                    {{ number_format($paid, 2) }}
                </div>

                <div class="text-xs text-gray-500 dark:text-gray-400">
                    Advance paid
                </div>

                @if ($balance > 0.001)
                    <div class="mt-2 text-sm font-semibold text-danger-600 dark:text-danger-400">
                        {{ number_format($balance, 2) }}
                    </div>

                    <div class="text-xs text-gray-500 dark:text-gray-400">
                        Outstanding
                    </div>
                @else
                    <div class="mt-2 text-sm font-semibold text-success-600 dark:text-success-400">
                        Fully paid
                    </div>
                @endif

            </div>

        </div>


        {{-- ========================================================= --}}
        {{-- DELIVERY / DEADLINE                                       --}}
        {{-- ========================================================= --}}

        <div
            class="
                mt-5
                flex
                flex-col
                gap-2
                rounded-lg
                border
                border-gray-200
                bg-gray-50
                px-4
                py-3
                dark:border-white/10
                dark:bg-white/[0.03]
                sm:flex-row
                sm:items-center
                sm:justify-between
            "
        >

            <div class="flex items-center gap-2">

                @if ($deadlineDays !== null && $deadlineDays <= 0)
                    <x-heroicon-o-exclamation-triangle
                        class="h-4 w-4 text-danger-500"
                    />
                @else
                    <x-heroicon-o-truck
                        class="h-4 w-4 text-gray-500 dark:text-gray-400"
                    />
                @endif

                <span class="text-sm font-medium text-gray-700 dark:text-gray-200">
                    Delivery
                </span>

                @if ($record->deadline_date)
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                        {{ $record->deadline_date->format('d M Y') }}
                    </span>
                @else
                    <span class="text-sm text-gray-500 dark:text-gray-400">
                        No deadline
                    </span>
                @endif

            </div>

            <div
                class="
                    text-sm
                    font-semibold
                    {{ $deadlineDays !== null && $deadlineDays < 0
                        ? 'text-danger-600 dark:text-danger-400'
                        : ($deadlineDays !== null && $deadlineDays <= 3
                            ? 'text-warning-600 dark:text-warning-400'
                            : 'text-gray-600 dark:text-gray-300') }}
                "
            >
                {{ $deadlineText }}
            </div>

        </div>


        {{-- ========================================================= --}}
        {{-- PAYMENT PROGRESS                                          --}}
        {{-- ========================================================= --}}

        <div class="mt-5">

            <div class="mb-2 flex items-center justify-between text-xs">

                <span class="font-medium text-gray-600 dark:text-gray-300">
                    Payment progress
                </span>

                <span class="font-semibold text-gray-700 dark:text-gray-200">
                    {{ number_format($paymentPercent, 0) }}%
                </span>

            </div>

            <div
                class="
                    h-2
                    overflow-hidden
                    rounded-full
                    bg-gray-200
                    dark:bg-white/10
                "
            >
                <div
                    class="
                        h-full
                        rounded-full
                        bg-success-500
                        transition-all
                        duration-500
                    "
                    style="width: {{ $paymentPercent }}%"
                ></div>
            </div>

            <div class="mt-2 flex justify-between text-xs text-gray-500 dark:text-gray-400">

                <span>
                    Paid {{ number_format($paid, 2) }}
                </span>

                <span>
                    {{ $balance > 0.001
                        ? 'Due ' . number_format($balance, 2)
                        : 'Paid in full' }}
                </span>

            </div>

        </div>


        {{-- ========================================================= --}}
        {{-- STATUS WORKFLOW (Confirmed → Invoiced only)               --}}
        {{-- ========================================================= --}}

        @if ($currentStep !== null)

            <div class="mt-5 hidden md:block">

                <div class="flex items-center">

                    {{-- Confirmed --}}
                    <div class="flex items-center gap-2 shrink-0">

                        <div
                            class="
                                flex h-7 w-7 items-center justify-center
                                rounded-full
                                border border-success-500
                                bg-success-500
                                text-xs font-semibold text-white
                            "
                        >
                            ✓
                        </div>

                        <span class="text-xs font-medium text-gray-200">
                            Confirmed
                        </span>

                    </div>


                    {{-- Connector --}}
                    <div
                        class="
                            mx-4
                            h-px
                            flex-1
                            {{ $currentStep === 3
                                ? 'bg-success-500'
                                : 'bg-gray-600 dark:bg-gray-700' }}
                        "
                    ></div>


                    {{-- Invoiced --}}
                    <div class="flex items-center gap-2 shrink-0">

                        <div
                            class="
                                flex h-7 w-7 items-center justify-center
                                rounded-full
                                border
                                text-xs font-semibold
                                {{ $currentStep === 3
                                    ? 'border-success-500 bg-success-500 text-white'
                                    : 'border-gray-600 bg-gray-800 text-gray-500' }}
                            "
                        >
                            @if ($currentStep === 3)
                                ✓
                            @else
                                2
                            @endif
                        </div>

                        <span
                            class="
                                text-xs font-medium
                                {{ $currentStep === 3
                                    ? 'text-gray-200'
                                    : 'text-gray-500 dark:text-gray-400' }}
                            "
                        >
                            Invoiced
                        </span>

                    </div>

                </div>

            </div>

        @endif


        {{-- ========================================================= --}}
        {{-- INVOICE                                                   --}}
        {{-- ========================================================= --}}

        @if ($record->invoice)
            <div class="mt-4 flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                <x-heroicon-o-document-text class="h-4 w-4" />
                Invoice:
                <span class="font-medium text-gray-700 dark:text-gray-200">
                    {{ $record->invoice->invoice_number }}
                </span>
            </div>
        @endif

    </div>
</div>