<x-app-layout>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                Floorplan: {{ $floorplan->name }}
            </h2>
            <a class="underline" href="{{ route('admin.floorplans.index') }}">Back</a>
        </div>
    </x-slot>

    <div class="py-6 max-w-7xl mx-auto sm:px-6 lg:px-8">
        @if (session('status'))
            <div class="mb-4 p-3 bg-green-50 border border-green-200 rounded">
                {{ session('status') }}
            </div>
        @endif

        <div class="bg-white shadow sm:rounded-lg p-6 mb-6">
            <h3 class="text-lg font-semibold mb-3">Add table</h3>
            <form method="POST" action="{{ route('admin.floorplans.tables.create', $floorplan) }}" class="grid grid-cols-1 md:grid-cols-4 gap-3 items-end">
                @csrf
                <div>
                    <label class="block text-sm mb-1">Label</label>
                    <input name="label" class="w-full border rounded p-2" placeholder="T1" required>
                </div>
                <div>
                    <label class="block text-sm mb-1">Shape</label>
                    <select name="shape" class="w-full border rounded p-2">
                        <option value="rect_lg">Rectangle Large</option>
                        <option value="rect_sm">Rectangle Small</option>
                        <option value="sq_lg">Square Large</option>
                        <option value="sq_sm">Square Small</option>
                        <option value="circle_lg">Circle Large</option>
                        <option value="circle_sm">Circle Small</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm mb-1">Seats</label>
                    <input name="seats" type="number" min="1" max="30" value="4" class="w-full border rounded p-2" required>
                </div>
                <div>
                    <button class="px-4 py-2 rounded bg-black text-white w-full">Create</button>
                </div>
            </form>
        </div>

        <div class="bg-white shadow sm:rounded-lg p-6">
            <h3 class="text-lg font-semibold mb-4">Editor (drag + select tables)</h3>

            {{-- Assign selected tables to reservation --}}
            <div class="mb-4 p-4 border rounded-lg">
                <div class="flex flex-col md:flex-row md:items-end gap-3">
                    <div class="flex-1">
                        <label class="block text-sm mb-1">Assign selected tables to reservation (today)</label>
                        <select id="resSelect" class="w-full border rounded p-2">
                            <option value="">-- choose reservation --</option>
                            @foreach(\App\Models\Reservation::whereDate('date', now()->toDateString())->orderBy('expected_arrival_time')->orderBy('id')->get() as $r)
                                <option value="{{ $r->id }}">
                                    #{{ $r->id }} — {{ $r->guest_name }} ({{ $r->expected_arrival_time ?? '--:--' }}, {{ $r->people_count }}p)
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="flex items-end gap-3">
                        <div class="text-sm text-gray-700">
                            Selected: <span id="selCount">0</span>
                        </div>

                        <form id="assignForm" method="POST" action="">
                            @csrf
                            <input type="hidden" name="floorplan_id" value="{{ $floorplan->id }}">
                            <input type="hidden" name="table_ids" id="tableIdsInput" value="">
                            <button type="submit" class="px-4 py-2 rounded bg-black text-white">
                                Assign
                            </button>
                        </form>

                        <button type="button" id="lockBtn" class="px-4 py-2 rounded border">
                            Lock move
                        </button>

                        <button type="button" id="seatedBtn" class="px-4 py-2 rounded border">
                            Настанени
                        </button>
                    </div>
                </div>

                <div class="text-xs text-gray-500 mt-2">
                    Tip: Click tables to select/deselect. Drag still works. Assign saves the selected set to the chosen reservation.
                    Lock move = DO NOT MOVE / НЕ СЕ МЕСТИ (only creator or SuperAdmin can re-assign tables).
                    Настанени = marks reservation as seated (tables turn green).
                </div>
            </div>

            {{-- ✅ Waiter grouping --}}
            <div class="mb-4 p-4 border rounded-lg">
                <div class="flex flex-col md:flex-row md:items-end gap-3">
                    <div class="flex-1">
                        <label class="block text-sm mb-1">Waiter/team name (optional)</label>
                        <input id="waiterTeam" class="w-full border rounded p-2" placeholder="Red team / Luka / Dexter">
                    </div>
                    <div style="width:180px;">
                        <label class="block text-sm mb-1">Color</label>
                        <input id="waiterColor" type="color" class="w-full border rounded p-2" value="#ff0000">
                    </div>
                    <div>
                        <button type="button" id="applyWaiterBtn" class="px-4 py-2 rounded bg-black text-white">
                            Apply to selected tables
                        </button>
                    </div>
                </div>
                <div class="text-xs text-gray-500 mt-2">
                    Select tables, choose a color, and apply. Tables with waiter color get a colored ring.
                </div>
            </div>

            <div id="canvas" style="overflow:auto; border:1px solid #ddd; border-radius:12px; padding:10px;">
                <div id="stage" style="position:relative; display:inline-block;">
                    <img id="fpimg"
                         src="{{ asset('storage/'.$floorplan->image_path) }}"
                         alt="floorplan"
                         style="display:block; max-width:none;">

                    <!-- Glow lines under the tables -->
                    <svg id="linksSvg" style="position:absolute; left:0; top:0; pointer-events:none;"></svg>

                    <!-- Tables layer -->
                    <div id="overlay" style="position:absolute; left:0; top:0;"></div>
                </div>
            </div>

            <p class="text-sm text-gray-600 mt-3">
                Drag tables to position them (auto-save on drop).
            </p>
        </div>
    </div>

    <script>
        const tables = @json($tables);
        const reservationGroups = @json($reservationGroups ?? []);
        const csrf = @json(csrf_token());

        const img = document.getElementById('fpimg');
        const overlay = document.getElementById('overlay');
        const linksSvg = document.getElementById('linksSvg');

        const selected = new Set();
        const selCountEl = document.getElementById('selCount');
        const tableIdsInput = document.getElementById('tableIdsInput');
        const resSelect = document.getElementById('resSelect');
        const assignForm = document.getElementById('assignForm');
        const lockBtn = document.getElementById('lockBtn');
        const seatedBtn = document.getElementById('seatedBtn');

        // ✅ waiter UI
        const waiterTeam = document.getElementById('waiterTeam');
        const waiterColor = document.getElementById('waiterColor');
        const applyWaiterBtn = document.getElementById('applyWaiterBtn');

        function syncLayersToImage() {
            const w = img.clientWidth;
            const h = img.clientHeight;

            overlay.style.width = w + 'px';
            overlay.style.height = h + 'px';

            linksSvg.setAttribute('width', w);
            linksSvg.setAttribute('height', h);
            linksSvg.style.width = w + 'px';
            linksSvg.style.height = h + 'px';
        }

        function applyShape(el, shape) {
            const s = (shape || '');
            el.style.borderRadius = s.startsWith('circle') ? '9999px' : '10px';
        }

        function updateSelectedUi() {
            selCountEl.textContent = String(selected.size);
            tableIdsInput.value = Array.from(selected).join(',');
        }

        function colorForReservation(id) {
            const hue = (Number(id) * 47) % 360;
            return `hsl(${hue} 90% 60%)`;
        }

        function getTableCenter(t) {
            const x = parseInt(t.x ?? 20, 10);
            const y = parseInt(t.y ?? 20, 10);
            const w = parseInt(t.w ?? 60, 10);
            const h = parseInt(t.h ?? 60, 10);
            return { cx: x + (w / 2), cy: y + (h / 2) };
        }

        function findReservationForTable(tableId) {
            const tid = Number(tableId);
            return reservationGroups.find(g => Array.isArray(g.table_ids) && g.table_ids.map(Number).includes(tid)) || null;
        }

        function getSelectedReservation() {
            const rid = resSelect.value;
            if (!rid) return null;
            return reservationGroups.find(g => String(g.id) === String(rid)) || null;
        }

        function refreshActionButtons() {
            const r = getSelectedReservation();
            if (!r) {
                lockBtn.disabled = true;
                lockBtn.textContent = 'Lock move';

                seatedBtn.disabled = true;
                seatedBtn.textContent = 'Настанени';
                return;
            }

            lockBtn.disabled = false;
            lockBtn.textContent = r.locked_move ? 'Unlock move' : 'Lock move';

            seatedBtn.disabled = false;
            seatedBtn.textContent = r.is_seated ? 'Валидна' : 'Настанени';
        }

        function ensureSvgDefs() {
            if (linksSvg.querySelector('defs')) return;

            const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');

            const filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');
            filter.setAttribute('id', 'glow');
            filter.innerHTML = `
                <feGaussianBlur stdDeviation="3" result="coloredBlur"></feGaussianBlur>
                <feMerge>
                    <feMergeNode in="coloredBlur"></feMergeNode>
                    <feMergeNode in="SourceGraphic"></feMergeNode>
                </feMerge>
            `;
            defs.appendChild(filter);
            linksSvg.appendChild(defs);
        }

        function drawReservationLinks() {
            ensureSvgDefs();

            Array.from(linksSvg.children).forEach(ch => {
                if (ch.tagName.toLowerCase() !== 'defs') ch.remove();
            });

            const tById = new Map(tables.map(t => [Number(t.id), t]));

            reservationGroups.forEach(g => {
                const ids = (g.table_ids || []).map(Number).filter(id => tById.has(id));
                if (ids.length < 2) return;

                const base = tById.get(ids[0]);
                const baseC = getTableCenter(base);
                const stroke = colorForReservation(g.id);

                for (let i = 1; i < ids.length; i++) {
                    const t = tById.get(ids[i]);
                    const c = getTableCenter(t);

                    const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                    line.setAttribute('x1', baseC.cx);
                    line.setAttribute('y1', baseC.cy);
                    line.setAttribute('x2', c.cx);
                    line.setAttribute('y2', c.cy);
                    line.setAttribute('stroke', stroke);
                    line.setAttribute('stroke-width', '5');
                    line.setAttribute('stroke-linecap', 'round');
                    line.setAttribute('opacity', '0.9');
                    line.setAttribute('filter', 'url(#glow)');
                    linksSvg.appendChild(line);
                }
            });
        }

        function makeNode(t) {
            const el = document.createElement('div');
            el.dataset.id = t.id;

            const x = parseInt(t.x ?? 20, 10);
            const y = parseInt(t.y ?? 20, 10);
            const w = parseInt(t.w ?? 60, 10);
            const h = parseInt(t.h ?? 60, 10);
            const r = parseInt(t.rotation ?? 0, 10);

            el.style.position = 'absolute';
            el.style.left = x + 'px';
            el.style.top  = y + 'px';
            el.style.width  = w + 'px';
            el.style.height = h + 'px';
            el.style.transform = `rotate(${r}deg)`;

            // seated green
            const res = findReservationForTable(t.id);
            if (res && res.is_seated) {
                el.style.background = 'rgba(16,185,129,0.85)';
            } else {
                el.style.background = 'rgba(0,0,0,0.75)';
            }

            el.style.color = 'white';
            el.style.display = 'flex';
            el.style.alignItems = 'center';
            el.style.justifyContent = 'center';
            el.style.fontSize = '12px';
            el.style.userSelect = 'none';
            el.style.cursor = 'grab';
            el.style.border = '2px solid rgba(255,255,255,0.35)';

            // default shadow
            el.style.boxShadow = '0 6px 18px rgba(0,0,0,0.18)';

            // ✅ waiter ring (if set)
            if (t.waiter_color) {
                el.style.boxShadow = `0 0 0 4px ${t.waiter_color}, 0 6px 18px rgba(0,0,0,0.18)`;
            }

            applyShape(el, t.shape);

            if (res) {
                const time = res.expected_arrival_time || '--:--';
                const name = (res.guest_name || '').trim();
                const people = res.people_count ?? '';
                const lock = res.locked_move ? ' 🔒' : '';
                const adv = (res.advance_amount && Number(res.advance_amount) > 0) ? ' 💰' : '';

                el.innerHTML = `
                    <div style="text-align:center; line-height:1.05; padding:2px;">
                        <div style="font-weight:700;">${(t.label || ('T'+t.id))}${lock}${adv}</div>
                        <div style="font-size:11px; opacity:.95;">${time} • ${people}p</div>
                        <div style="font-size:11px; opacity:.9; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:${Math.max(40, w-6)}px;">
                            ${name}
                        </div>
                    </div>
                `;
            } else {
                el.textContent = t.label || ('T' + t.id);
            }

            if (selected.has(Number(t.id))) {
                el.style.outline = '3px solid rgba(255,255,255,0.9)';
                el.style.outlineOffset = '1px';
            }

            // Click to select/deselect (without breaking drag)
            let downX = 0, downY = 0;
            el.addEventListener('mousedown', (e) => {
                downX = e.clientX;
                downY = e.clientY;
            });

            el.addEventListener('click', (e) => {
                const moved = Math.abs(e.clientX - downX) + Math.abs(e.clientY - downY);
                if (moved > 6) return;

                e.stopPropagation();

                const id = Number(t.id);
                if (selected.has(id)) {
                    selected.delete(id);
                    el.style.outline = 'none';
                } else {
                    selected.add(id);
                    el.style.outline = '3px solid rgba(255,255,255,0.9)';
                    el.style.outlineOffset = '1px';
                }
                updateSelectedUi();
            });

            return el;
        }

        async function savePos(id, x, y) {
            const res = await fetch(`/admin/tables/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ x, y }),
            });

            if (!res.ok) {
                console.error(await res.text());
                alert('Save failed. Check laravel.log');
            }
        }

        function attachDrag(el, tRef) {
            let dragging = false;
            let startX=0, startY=0, origX=0, origY=0;

            el.addEventListener('mousedown', (e) => {
                dragging = true;
                el.style.cursor = 'grabbing';
                startX = e.clientX;
                startY = e.clientY;
                origX = parseInt(el.style.left, 10) || 0;
                origY = parseInt(el.style.top, 10) || 0;
                e.preventDefault();
            });

            window.addEventListener('mousemove', (e) => {
                if (!dragging) return;

                const nx = (origX + (e.clientX - startX));
                const ny = (origY + (e.clientY - startY));

                el.style.left = nx + 'px';
                el.style.top  = ny + 'px';

                tRef.x = nx;
                tRef.y = ny;

                drawReservationLinks();
            });

            window.addEventListener('mouseup', async () => {
                if (!dragging) return;
                dragging = false;
                el.style.cursor = 'grab';

                const id = el.dataset.id;
                const x = parseInt(el.style.left, 10) || 0;
                const y = parseInt(el.style.top, 10) || 0;

                await savePos(id, x, y);
                drawReservationLinks();
            });
        }

        function render() {
            overlay.innerHTML = '';
            syncLayersToImage();

            tables.forEach(t => {
                const el = makeNode(t);
                overlay.appendChild(el);
                attachDrag(el, t);
            });

            drawReservationLinks();
        }

        resSelect.addEventListener('change', () => {
            const rid = resSelect.value;
            assignForm.action = rid ? `/admin/reservations/${rid}/sync-tables` : '';
            refreshActionButtons();
        });

        lockBtn.addEventListener('click', async () => {
            const r = getSelectedReservation();
            if (!r) return;

            const newLock = !r.locked_move;

            const res = await fetch(`/reservations/${r.id}/toggle-lock-move`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json',
                },
                body: JSON.stringify({ locked_move: newLock }),
            });

            if (!res.ok) {
                alert('Lock toggle failed (maybe not allowed).');
                return;
            }

            r.locked_move = newLock;
            refreshActionButtons();
            render();
        });

        seatedBtn.addEventListener('click', async () => {
            const r = getSelectedReservation();
            if (!r) {
                alert('Choose a reservation first.');
                return;
            }

            const res = await fetch(`/reservations/${r.id}/toggle-seated`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json',
                },
            });

            if (!res.ok) {
                alert('Seated toggle failed (maybe not allowed).');
                return;
            }

            const data = await res.json();
            r.is_seated = !!data.is_seated;
            r.seated_at = data.seated_at ?? null;

            refreshActionButtons();
            render();
        });

        // ✅ Apply waiter color/team to selected tables
        applyWaiterBtn.addEventListener('click', async () => {
            if (selected.size === 0) {
                alert('Select at least 1 table first.');
                return;
            }

            const body = new URLSearchParams();
            body.set('_token', csrf);
            body.set('table_ids', Array.from(selected).join(','));
            body.set('waiter_team', waiterTeam.value || '');
            body.set('waiter_color', waiterColor.value || '');

            const res = await fetch(`/admin/floorplans/{{ $floorplan->id }}/tables/assign-waiter`, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: body.toString(),
            });

            if (!res.ok) {
                const t = await res.text();
                console.error(t);
                alert('Failed to assign waiter group. Check laravel.log');
                return;
            }

            window.location.reload();
        });

        assignForm.addEventListener('submit', (e) => {
            if (!resSelect.value) {
                e.preventDefault();
                alert('Choose a reservation first.');
                return;
            }
            if (selected.size === 0) {
                e.preventDefault();
                alert('Select at least 1 table.');
                return;
            }
        });

        img.addEventListener('load', render);
        if (img.complete) render();

        window.addEventListener('resize', () => {
            syncLayersToImage();
            drawReservationLinks();
        });

        refreshActionButtons();
    </script>
</x-app-layout>
