@php
    $baseQuery = request()->except(['view', 'page']);
    $dealStatusLabels = [
        'open' => __('Open'),
        'won' => __('Won'),
        'lost' => __('Lost'),
    ];
@endphp

<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between gap-4">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">Transactions</h2>
            <a href="{{ route('deals.create', ['pipeline_id' => $activePipeline?->id]) }}" class="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">New deal</a>
        </div>
    </x-slot>

    <div class="pb-12" data-sidepanel-scope>
        <div class="w-full px-6 space-y-6">
            <div class="bg-white border border-gray-200 rounded-xl p-4">
                <div class="mb-4 flex flex-wrap gap-2">
                    @foreach ($viewOptions as $mode => $label)
                        <a
                            href="{{ route('deals.index', array_merge($baseQuery, ['view' => $mode])) }}"
                            class="inline-flex items-center rounded-md px-3 py-1.5 text-sm font-medium {{ $viewMode === $mode ? 'bg-indigo-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' }}"
                        >
                            {{ $label }}
                        </a>
                    @endforeach
                </div>

                <form method="GET" action="{{ route('deals.index') }}" class="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <input type="hidden" name="view" value="{{ $viewMode }}">

                    <div>
                        <label for="pipeline_id" class="block text-xs font-medium text-gray-500 uppercase">Funnel</label>
                        <select
                            id="pipeline_id"
                            name="pipeline_id"
                            onchange="this.form.requestSubmit()"
                            class="mt-1 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                        >
                            @foreach ($pipelines as $pipeline)
                                <option value="{{ $pipeline->id }}" @selected($activePipeline?->id === $pipeline->id)>{{ $pipeline->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="md:col-span-2">
                        <label for="q" class="block text-xs font-medium text-gray-500 uppercase">Search</label>
                        <div class="mt-1 flex gap-2">
                            <input id="q" type="text" name="q" value="{{ $search }}" placeholder="Deal name, company, contact" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                            <a href="{{ route('deals.index', ['view' => $viewMode]) }}" class="inline-flex items-center rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Reset</a>
                        </div>
                    </div>
                </form>
            </div>

            @if ($viewMode === 'kanban')
                @if ($activePipeline)
                    <section
                        id="deal-board"
                        data-pipeline-id="{{ $activePipeline->id }}"
                        data-csrf="{{ csrf_token() }}"
                        data-stage-update-url="{{ route('pipelines.update-stages', $activePipeline) }}"
                        data-can-update-stages="{{ ($canUpdateActivePipeline ?? false) ? '1' : '0' }}"
                    >
                        <h3 class="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-3">Kanban · {{ $activePipeline->name }}</h3>
                        <p class="mb-3 text-xs text-gray-500">Drag and drop cards between stages, changes are saved without rebooting and broadcast to other users in real time.</p>

                        <div class="relative" data-board-scroll-wrap>
                        <div class="overflow-x-auto pb-2" data-board-scroll>
                            <div class="flex min-w-max items-start gap-4" data-board-grid>
                                @foreach ($boardStages as $column)
                                    @php
                                        $stageColor = preg_match('/^#[0-9A-Fa-f]{6}$/', (string) $column['stage']->color)
                                            ? strtoupper((string) $column['stage']->color)
                                            : '#94A3B8';
                                    @endphp
                                    <div
                                        class="w-[320px] shrink-0 self-start rounded-xl border border-gray-200 border-t-4 bg-white p-3 flex flex-col"
                                        data-stage-column="{{ $column['stage']->id }}"
                                        data-stage-color="{{ $stageColor }}"
                                        style="border-top-color: {{ $stageColor }}; background-image: linear-gradient(to bottom, {{ $stageColor }}1F, #FFFFFF 42%);"
                                    >
                                        <div class="mb-3 flex items-start justify-between gap-2">
                                            <div class="min-w-0">
                                                <p class="truncate font-semibold text-gray-900">{{ $column['stage']->name }}</p>
                                                <p class="text-xs text-gray-500"><span data-stage-count>{{ $column['deals']->count() }}</span> transactions · $<span data-stage-amount>{{ number_format((float) $column['amount'], 0, '.', ' ') }}</span></p>
                                            </div>
                                            @if ($canUpdateActivePipeline ?? false)
                                                <div class="flex items-center gap-1">
                                                    <label class="inline-flex h-7 w-7 cursor-pointer items-center justify-center rounded-md border border-gray-200 text-gray-500 hover:bg-gray-50" title="Stage color">
                                                        <x-menu-icon name="fa-solid fa-palette" class="h-3.5 w-3.5" />
                                                        <input
                                                            type="color"
                                                            value="{{ $stageColor }}"
                                                            class="sr-only"
                                                            data-stage-color-picker
                                                        >
                                                    </label>
                                                    <button
                                                        type="button"
                                                        class="inline-flex h-7 w-7 cursor-grab items-center justify-center rounded-md border border-gray-200 text-gray-500 hover:bg-gray-50 active:cursor-grabbing"
                                                        title="Move Stage"
                                                        data-stage-move-handle
                                                        draggable="true"
                                                    >
                                                        <x-menu-icon name="fa-solid fa-grip-vertical" class="h-3.5 w-3.5" />
                                                    </button>
                                                </div>
                                            @endif
                                        </div>

                                        <div class="space-y-2 max-h-96 overflow-auto pr-1" data-stage-list>
                                            @forelse ($column['deals'] as $deal)
                                                <div class="h-auto rounded-lg border border-gray-100 p-3 bg-gray-50 cursor-move" draggable="true" data-deal-card data-deal-id="{{ $deal->id }}" data-stage-id="{{ $deal->stage_id }}" data-status="{{ $deal->status }}" data-amount="{{ (float) $deal->amount }}" data-update-url="{{ route('deals.update-stage', $deal) }}">
                                                    <a href="{{ route('deals.show', $deal) }}" class="text-sm font-medium text-gray-900 hover:text-indigo-600" data-deal-title>{{ $deal->title }}</a>
                                                    <p class="mt-1 text-xs text-gray-500" data-company-name>{{ $deal->company?->name ?? 'Without company' }}</p>
                                                    <p class="text-xs text-gray-600 mt-1 font-semibold">$<span data-amount-display>{{ number_format((float) $deal->amount, 0, '.', ' ') }}</span></p>

                                                    <form method="POST" action="{{ route('deals.update-stage', $deal) }}" class="mt-2" data-stage-form>
                                                        @csrf
                                                        @method('PATCH')
                                                        <select name="stage_id" class="w-full rounded-md border-gray-300 text-xs shadow-sm focus:border-indigo-500 focus:ring-indigo-500" data-stage-select>
                                                            @foreach ($activePipeline->stages as $stage)
                                                                <option value="{{ $stage->id }}" @selected($deal->stage_id === $stage->id)>{{ $stage->name }}</option>
                                                            @endforeach
                                                        </select>
                                                    </form>
                                                </div>
                                            @empty
                                                <p class="text-xs text-gray-500" data-empty>No deals</p>
                                            @endforelse
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                        <div
                            class="pointer-events-none absolute inset-y-0 right-0 w-16 bg-gradient-to-l from-gray-100 via-gray-100/90 to-transparent opacity-0 transition-opacity duration-200"
                            data-board-scroll-fade-right
                        ></div>
                        </div>
                    </section>
                @else
                    <section class="rounded-xl border border-gray-200 bg-white p-6">
                        <p class="text-sm text-gray-600">Create a sales funnel to use Deal Kanban.</p>
                        <a href="{{ route('pipelines.create') }}" class="mt-3 inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-500">Create a funnel</a>
                    </section>
                @endif
            @else
                <section class="bg-white border border-gray-200 rounded-xl overflow-hidden">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Deal</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Company / Contact</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Stage</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Responsible</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Sum</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 bg-white">
                            @forelse ($deals as $deal)
                                <tr class="hover:bg-gray-50">
                                    <td class="px-4 py-3">
                                        <a href="{{ route('deals.show', $deal) }}" class="font-medium text-gray-900 hover:text-indigo-600">{{ $deal->title }}</a>
                                        <div class="text-xs text-gray-500">{{ $deal->pipeline?->name ?? '—' }}</div>
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $deal->company?->name ?? '—' }} / {{ $deal->contact?->full_name ?? '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $deal->stage?->name ?? '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $deal->owner?->name ?? '—' }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">${{ number_format((float) $deal->amount, 0, '.', ' ') }}</td>
                                    <td class="px-4 py-3 text-sm text-gray-700">{{ $dealStatusLabels[$deal->status] ?? $deal->status }}</td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="6" class="px-4 py-8 text-center text-sm text-gray-500">No deals found.</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </section>

                <div>{{ $deals->links() }}</div>
            @endif
        </div>
    </div>

    @if ($viewMode === 'kanban' && $activePipeline)
        <script>
            document.addEventListener('DOMContentLoaded', () => {
                const board = document.getElementById('deal-board');

                if (!board) {
                    return;
                }

                const csrf = board.dataset.csrf;
                const pipelineId = board.dataset.pipelineId;
                const boardGrid = board.querySelector('[data-board-grid]');
                if (!boardGrid) {
                    return;
                }

                const stageUpdateUrl = board.dataset.stageUpdateUrl || '';
                const canManageStages = board.dataset.canUpdateStages === '1';
                let draggingCard = null;
                let draggingStageColumn = null;
                let stageSettingsSaveTimer = null;

                const money = (value) => {
                    const numeric = Number(value || 0);
                    return new Intl.NumberFormat(document.documentElement.lang || 'ru-RU', {
                        maximumFractionDigits: 0,
                    }).format(numeric);
                };

                const getStageColumns = () => Array.from(board.querySelectorAll('[data-stage-column]'));

                const normalizeStageColor = (rawColor) => {
                    const color = String(rawColor || '').trim().toUpperCase();

                    if (!/^#[0-9A-F]{6}$/.test(color)) {
                        return '#94A3B8';
                    }

                    return color;
                };

                const applyColumnColor = (column, rawColor) => {
                    const color = normalizeStageColor(rawColor);
                    column.dataset.stageColor = color;
                    column.style.borderTopColor = color;
                    column.style.backgroundImage = `linear-gradient(to bottom, ${color}1F, #FFFFFF 42%)`;

                    const picker = column.querySelector('[data-stage-color-picker]');
                    if (picker) {
                        picker.value = color;
                    }
                };

                const collectStageSettings = () => {
                    return getStageColumns().map((column, index) => ({
                        id: Number(column.dataset.stageColumn || 0),
                        color: normalizeStageColor(column.dataset.stageColor || '#94A3B8'),
                        sort_order: index,
                    }));
                };

                const persistStageSettings = async () => {
                    if (!canManageStages || !stageUpdateUrl) {
                        return;
                    }

                    try {
                        await fetch(stageUpdateUrl, {
                            method: 'PATCH',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrf,
                                'X-Requested-With': 'XMLHttpRequest',
                            },
                            body: JSON.stringify({ stages: collectStageSettings() }),
                        });
                    } catch (error) {
                        // Keep board interactive even if settings save fails.
                    }
                };

                const queueStageSettingsSave = () => {
                    if (!canManageStages) {
                        return;
                    }

                    if (stageSettingsSaveTimer) {
                        window.clearTimeout(stageSettingsSaveTimer);
                    }

                    stageSettingsSaveTimer = window.setTimeout(() => {
                        persistStageSettings();
                    }, 180);
                };

                const updateStageStats = (column) => {
                    const list = column.querySelector('[data-stage-list]');
                    const cards = list ? Array.from(list.querySelectorAll('[data-deal-card]')) : [];
                    const count = cards.length;
                    const amount = cards.reduce((sum, card) => sum + Number(card.dataset.amount || 0), 0);

                    const countNode = column.querySelector('[data-stage-count]');
                    const amountNode = column.querySelector('[data-stage-amount]');

                    if (countNode) {
                        countNode.textContent = String(count);
                    }

                    if (amountNode) {
                        amountNode.textContent = money(amount);
                    }

                    const emptyNode = list ? list.querySelector('[data-empty]') : null;
                    if (emptyNode) {
                        emptyNode.classList.toggle('hidden', count > 0);
                    }

                    if (count === 0 && list && !emptyNode) {
                        const placeholder = document.createElement('p');
                        placeholder.dataset.empty = '1';
                        placeholder.className = 'text-xs text-gray-500';
                        placeholder.textContent = 'No deals';
                        list.appendChild(placeholder);
                    }
                };

                const updateAllStats = () => {
                    getStageColumns().forEach(updateStageStats);
                };

                const placeCardIntoStage = (card, stageId) => {
                    const targetColumn = board.querySelector(`[data-stage-column="${stageId}"]`);
                    const targetList = targetColumn ? targetColumn.querySelector('[data-stage-list]') : null;

                    if (!targetList) {
                        return;
                    }

                    const existingEmpty = targetList.querySelector('[data-empty]');
                    if (existingEmpty) {
                        existingEmpty.remove();
                    }

                    targetList.prepend(card);
                    card.dataset.stageId = String(stageId);

                    const select = card.querySelector('[data-stage-select]');
                    if (select) {
                        select.value = String(stageId);
                    }

                    updateAllStats();
                };

                const removeCardFromBoard = (card) => {
                    card.remove();
                    updateAllStats();
                };

                const syncCardFromPayload = (payload) => {
                    const card = board.querySelector(`[data-deal-card][data-deal-id="${payload.id}"]`);

                    if (!card) {
                        return;
                    }

                    card.dataset.amount = String(payload.amount ?? 0);
                    card.dataset.status = payload.status;
                    card.dataset.stageId = String(payload.stage_id);

                    const titleNode = card.querySelector('[data-deal-title]');
                    const companyNode = card.querySelector('[data-company-name]');
                    const amountNode = card.querySelector('[data-amount-display]');
                    const selectNode = card.querySelector('[data-stage-select]');

                    if (titleNode && payload.title) {
                        titleNode.textContent = payload.title;
                    }
                    if (companyNode) {
                        companyNode.textContent = payload.company_name || 'Without company';
                    }
                    if (amountNode) {
                        amountNode.textContent = money(payload.amount || 0);
                    }
                    if (selectNode) {
                        selectNode.value = String(payload.stage_id);
                    }

                    if (payload.status !== 'open') {
                        removeCardFromBoard(card);
                        return;
                    }

                    placeCardIntoStage(card, payload.stage_id);
                };

                const updateDealStage = async (card, stageId, previousStageId = card.dataset.stageId) => {
                    const url = card.dataset.updateUrl;

                    try {
                        const response = await fetch(url, {
                            method: 'PATCH',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrf,
                            },
                            body: JSON.stringify({ stage_id: Number(stageId) }),
                        });

                        if (!response.ok) {
                            throw new Error('Stage update failed');
                        }

                        const data = await response.json();
                        if (!data.deal) {
                            throw new Error('Missing deal payload');
                        }

                        syncCardFromPayload(data.deal);
                    } catch (error) {
                        placeCardIntoStage(card, previousStageId);
                    }
                };

                board.querySelectorAll('[data-deal-card]').forEach((card) => {
                    card.addEventListener('dragstart', () => {
                        draggingCard = card;
                        card.classList.add('opacity-60');
                    });

                    card.addEventListener('dragend', () => {
                        card.classList.remove('opacity-60');
                    });

                    const select = card.querySelector('[data-stage-select]');
                    if (select) {
                        select.addEventListener('change', () => {
                            const nextStageId = select.value;
                            const previousStageId = card.dataset.stageId;
                            placeCardIntoStage(card, nextStageId);
                            updateDealStage(card, nextStageId, previousStageId);
                        });
                    }
                });

                getStageColumns().forEach((column) => {
                    column.addEventListener('dragover', (event) => {
                        if (draggingStageColumn) {
                            return;
                        }

                        event.preventDefault();
                        column.classList.add('ring-2', 'ring-indigo-200');
                    });

                    column.addEventListener('dragleave', () => {
                        column.classList.remove('ring-2', 'ring-indigo-200');
                    });

                    column.addEventListener('drop', (event) => {
                        event.preventDefault();
                        column.classList.remove('ring-2', 'ring-indigo-200');

                        if (draggingStageColumn) {
                            return;
                        }

                        if (!draggingCard) {
                            return;
                        }

                        const targetStageId = column.dataset.stageColumn;
                        if (String(draggingCard.dataset.stageId) === String(targetStageId)) {
                            return;
                        }

                        const previousStageId = draggingCard.dataset.stageId;
                        placeCardIntoStage(draggingCard, targetStageId);
                        updateDealStage(draggingCard, targetStageId, previousStageId);
                    });
                });

                if (canManageStages) {
                    getStageColumns().forEach((column) => {
                        applyColumnColor(column, column.dataset.stageColor || '#94A3B8');

                        const picker = column.querySelector('[data-stage-color-picker]');
                        if (picker) {
                            picker.addEventListener('input', () => {
                                applyColumnColor(column, picker.value);
                                queueStageSettingsSave();
                            });
                        }
                    });

                    boardGrid.addEventListener('dragstart', (event) => {
                        const target = event.target instanceof Element
                            ? event.target.closest('[data-stage-move-handle]')
                            : null;
                        if (!target) {
                            return;
                        }

                        const column = target.closest('[data-stage-column]');
                        if (!column) {
                            return;
                        }

                        draggingStageColumn = column;
                        draggingCard = null;
                        column.classList.add('opacity-60');

                        if (event.dataTransfer) {
                            event.dataTransfer.effectAllowed = 'move';
                            event.dataTransfer.setData('text/plain', 'deal-stage-column');
                        }
                    });

                    boardGrid.addEventListener('dragover', (event) => {
                        if (!draggingStageColumn) {
                            return;
                        }

                        const target = event.target instanceof Element
                            ? event.target.closest('[data-stage-column]')
                            : null;

                        if (!target || target === draggingStageColumn) {
                            return;
                        }

                        event.preventDefault();

                        const rect = target.getBoundingClientRect();
                        const shouldInsertAfter = event.clientX > rect.left + rect.width / 2;

                        if (shouldInsertAfter) {
                            boardGrid.insertBefore(draggingStageColumn, target.nextElementSibling);
                        } else {
                            boardGrid.insertBefore(draggingStageColumn, target);
                        }
                    });

                    boardGrid.addEventListener('drop', (event) => {
                        if (!draggingStageColumn) {
                            return;
                        }

                        event.preventDefault();
                    });

                    boardGrid.addEventListener('dragend', () => {
                        if (!draggingStageColumn) {
                            return;
                        }

                        draggingStageColumn.classList.remove('opacity-60');
                        draggingStageColumn = null;
                        queueStageSettingsSave();
                    });
                }

                if (window.Echo && pipelineId) {
                    window.Echo.channel(`pipelines.${pipelineId}`)
                        .listen('.deal.stage-changed', (payload) => {
                            syncCardFromPayload(payload);
                        });
                }

                updateAllStats();
            });
        </script>
    @endif
</x-app-layout>
