@extends('layouts.app')

@section('title', 'Flowsheet · ' . ($admission->pet->petname ?? 'Patient'))

@section('css')
<style>
.fs-shell { background:#fff; border:1px solid #e5e9f0; border-radius:10px; overflow:hidden; }
.fs-toolbar {
    display:flex; align-items:center; gap:12px; padding:10px 14px;
    background:#f8fafc; border-bottom:1px solid #e5e9f0; flex-wrap:wrap;
}
.fs-toolbar .grow { flex:1; }
.fs-toolbar .legend { display:flex; gap:8px; font-size:11px; color:#475569; align-items:center; }
.fs-toolbar .legend span.dot { display:inline-block; width:12px; height:12px; border-radius:3px; vertical-align:middle; margin-right:3px; }

.fs-wrap { overflow-x:auto; max-height: 72vh; }
table.fs { border-collapse:separate; border-spacing:0; font-size:11px; min-width:100%; }
table.fs th, table.fs td { border-right:1px solid #e5e9f0; border-bottom:1px solid #e5e9f0; padding:5px 4px; text-align:center; vertical-align:middle; white-space:nowrap; }

/* sticky header row */
table.fs thead th {
    position:sticky; top:0; z-index:3; background:#f1f5f9;
    color:#1a3a5c; font-weight:700; font-size:10px; padding:6px 4px;
}
table.fs thead th.day-head { background:#1a3a5c; color:#fff; font-size:11px; padding:5px; }

/* sticky left column */
table.fs th.task-col, table.fs td.task-col {
    position:sticky; left:0; z-index:2; background:#fff;
    text-align:left; min-width:220px; max-width:220px; padding:8px 10px;
    border-right:2px solid #cbd5e1;
}
table.fs thead th.task-col { z-index:4; background:#f1f5f9; }
.task-name { font-weight:700; color:#1a3a5c; }
.task-meta { font-size:10px; color:#64748b; margin-top:1px; }

.slot {
    width:48px; height:32px; display:inline-flex; align-items:center; justify-content:center;
    cursor:pointer; border-radius:3px; font-size:11px; font-weight:700; transition: filter .12s;
}
.slot:hover { filter:brightness(.92); }
.slot.pending { background:#f1f5f9; color:#94a3b8; }
.slot.due     { background:#dbeafe; color:#1e40af; }
.slot.missed  { background:#fee2e2; color:#991b1b; animation: missedPulse 1.4s infinite; }
.slot.done    { background:#dcfce7; color:#15803d; }
.slot.skipped { background:#fef3c7; color:#92400e; }

@keyframes missedPulse {
    0%,100% { background:#fee2e2; }
    50%     { background:#fecaca; }
}

.window-btn { padding:4px 12px; border:1px solid #cbd5e1; background:#fff; border-radius:5px; font-size:11px; font-weight:700; cursor:pointer; }
.window-btn.active { background:#2563eb; color:#fff; border-color:#2563eb; }

.empty-state { text-align:center; padding:36px; color:#94a3b8; font-size:14px; }
</style>
@endsection

@section('content')

<section class="content-header">
    <h1>
        <i class="fa fa-th-large"></i> Flowsheet
        <small>
            <i class="fa fa-paw"></i> {{ optional($admission->pet)->petname ?? '—' }}
            · {{ ucfirst(str_replace('_', ' ', $admission->type ?? '')) }}
            · {{ optional($admission->ward)->name ?? 'Unassigned' }}
        </small>
    </h1>
</section>

<section class="content">

    <div style="margin-bottom: 12px;">
        <a href="{{ route('va.admissions.show', $admission->id) }}" class="btn btn-default btn-sm">
            <i class="fa fa-arrow-left"></i> Back to admission
        </a>
        <a href="{{ route('va.admissions.board') }}" class="btn btn-default btn-sm">
            <i class="fa fa-th"></i> Ward board
        </a>
    </div>

    <div class="fs-shell">
        <div class="fs-toolbar">
            <div>
                <strong>Window:</strong>
                <button type="button" class="window-btn" data-hours="8">8 h</button>
                <button type="button" class="window-btn active" data-hours="24">24 h</button>
                <button type="button" class="window-btn" data-hours="48">48 h</button>
                <button type="button" class="window-btn" data-hours="168">7 d</button>
            </div>

            <div class="grow"></div>

            <div class="legend">
                <span><span class="dot" style="background:#f1f5f9;"></span>Pending</span>
                <span><span class="dot" style="background:#dbeafe;"></span>Due</span>
                <span><span class="dot" style="background:#fee2e2;"></span>Missed</span>
                <span><span class="dot" style="background:#dcfce7;"></span>Done</span>
                <span><span class="dot" style="background:#fef3c7;"></span>Skipped</span>
            </div>

            <button type="button" id="fs-refresh" class="btn btn-default btn-sm">
                <i class="fa fa-sync"></i> Refresh
            </button>
        </div>

        <div class="fs-wrap">
            <div id="fs-content">
                <div class="empty-state"><i class="fa fa-spinner fa-spin"></i> Loading flowsheet…</div>
            </div>
        </div>
    </div>

</section>

@endsection

@section('javascript')
<script>
$(function () {
    'use strict';

    var DATA_URL    = '{{ route('va.admissions.flowsheet-data', $admission->id) }}';
    var LOG_URL     = '{{ route('va.admissions.care-log', $admission->id) }}';
    var MED_ADMIN_BASE = '{{ url('/vet-admission/medication-administrations') }}';
    var TOKEN       = $('meta[name="csrf-token"]').attr('content');
    var windowHours = parseInt('{{ $defaultWindow }}', 10) || 24;

    function pad(n) { return n < 10 ? '0' + n : '' + n; }
    function isoDate(d) { return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()); }

    function load() {
        var now = new Date();
        var from = new Date(now.getTime());
        var to;
        if (windowHours <= 24) {
            from = new Date(now.getFullYear(), now.getMonth(), now.getDate()); // start of today
            to = new Date(from.getTime() + windowHours * 3600 * 1000);
        } else {
            from = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            to = new Date(from.getTime() + windowHours * 3600 * 1000);
        }
        $('#fs-content').html('<div class="empty-state"><i class="fa fa-spinner fa-spin"></i> Loading…</div>');

        $.get(DATA_URL, { from: isoDate(from), to: isoDate(to) })
            .done(function (res) { render(res); })
            .fail(function () {
                $('#fs-content').html('<div class="empty-state" style="color:#b91c1c;">Could not load flowsheet.</div>');
            });
    }

    function render(res) {
        if (!res.rows || !res.rows.length) {
            $('#fs-content').html(
                '<div class="empty-state">' +
                'No active care-plan items. Add some from the admission page (Care Plan tab) to populate the flowsheet.' +
                '</div>'
            );
            return;
        }

        // Build a sorted list of unique (date, slot_index, due_at) keys across all rows
        var colKeys = [];
        var colMeta = {}; // key -> { date, slot_index, due_at }
        res.rows.forEach(function (row) {
            row.slots.forEach(function (s) {
                var key = s.date + '|' + s.slot_index;
                if (!colMeta[key]) {
                    colMeta[key] = { date: s.date, slot_index: s.slot_index, due_at: s.due_at };
                    colKeys.push(key);
                }
            });
        });
        colKeys.sort(function (a, b) {
            return new Date(colMeta[a].due_at) - new Date(colMeta[b].due_at);
        });

        // Group columns by date for the day-banner row
        var dayBands = [];   // [{ date, span, label }]
        var lastDate = null, lastIdx = -1;
        colKeys.forEach(function (k) {
            var d = colMeta[k].date;
            if (d !== lastDate) {
                dayBands.push({ date: d, span: 1, label: formatDay(d) });
                lastDate = d;
                lastIdx++;
            } else {
                dayBands[lastIdx].span++;
            }
        });

        var html = '<table class="fs"><thead>';
        html += '<tr><th class="task-col">Treatment</th>';
        dayBands.forEach(function (b) {
            html += '<th class="day-head" colspan="' + b.span + '">' + b.label + '</th>';
        });
        html += '</tr><tr><th class="task-col">&nbsp;</th>';
        colKeys.forEach(function (k) {
            var dt = new Date(colMeta[k].due_at);
            html += '<th>' + pad(dt.getHours()) + ':' + pad(dt.getMinutes()) + '</th>';
        });
        html += '</tr></thead><tbody>';

        res.rows.forEach(function (row) {
            html += '<tr><td class="task-col">';
            html += '<div class="task-name"><i class="fa ' + (row.task_icon || 'fa-clipboard-check') + '" style="color:' + (row.task_color || '#3b82f6') + ';"></i> ' + escape(row.task_name || 'Task') + '</div>';
            if (row.instructions) {
                html += '<div class="task-meta">' + escape(row.instructions) + '</div>';
            }
            html += '</td>';
            var slotMap = {};
            row.slots.forEach(function (s) { slotMap[s.date + '|' + s.slot_index] = s; });
            colKeys.forEach(function (k) {
                var s = slotMap[k];
                if (!s) { html += '<td>&nbsp;</td>'; return; }
                var label = (s.status === 'done') ? '✓' :
                            (s.status === 'skipped') ? '–' :
                            (s.status === 'missed') ? '!' : '';
                var dataAttrs = ' data-kind="' + (row.kind || 'care_plan') + '"';
                if (row.kind === 'medication') {
                    dataAttrs += ' data-admin="' + s.admin_id + '"';
                    dataAttrs += ' data-med="'   + row.medication_id + '"';
                } else {
                    dataAttrs += ' data-plan="' + row.plan_id + '"';
                    dataAttrs += ' data-date="' + s.date + '"';
                    dataAttrs += ' data-slot="' + s.slot_index + '"';
                }
                html += '<td><div class="slot ' + s.status + '"' + dataAttrs +
                        ' data-status="' + s.status + '" title="' + (s.notes || '') + '">' + label + '</div></td>';
            });
            html += '</tr>';
        });
        html += '</tbody></table>';
        $('#fs-content').html(html);
    }

    function formatDay(d) {
        var dt = new Date(d + 'T00:00:00');
        var today = new Date(); today.setHours(0,0,0,0);
        var diff = Math.round((dt - today) / 86400000);
        var prefix = diff === 0 ? 'Today' : (diff === 1 ? 'Tomorrow' : (diff === -1 ? 'Yesterday' : ''));
        var label = dt.toLocaleDateString(undefined, { weekday:'short', day:'2-digit', month:'short' });
        return prefix ? prefix + ' · ' + label : label;
    }

    function escape(s) {
        return (s || '').toString().replace(/[&<>"']/g, function (c) {
            return { '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c];
        });
    }

    // ── Cell click → cycle done / skipped / undo (care plan OR medication) ──
    $(document).on('click', '.slot', function () {
        var $cell = $(this);
        var current = $cell.data('status');
        var kind = $cell.data('kind') || 'care_plan';

        // Medication cells cycle: pending/due/missed -> given -> missed (refused) -> pending
        // Care-plan cells cycle: pending/due/missed -> done -> skipped -> undo
        var req, url, nextLabel;

        if (kind === 'medication') {
            var nextMed = (current === 'done') ? 'missed' :
                          (current === 'skipped') ? 'pending-skip' :
                          'given';
            if (nextMed === 'pending-skip') {
                // No real "undo" for a recorded med — re-mark as pending visually only;
                // backend keeps the audit row but the cell shows pending until next refresh.
                toastr.info('Medication doses cannot be cleared — fix via the medications tab.');
                return;
            }
            url = MED_ADMIN_BASE + '/' + $cell.data('admin');
            req = { _token: TOKEN, status: nextMed === 'given' ? 'given' : 'missed' };
            nextLabel = nextMed;
        } else {
            var nextCare = (current === 'done') ? 'skipped' :
                           (current === 'skipped') ? 'undo' :
                           'done';
            url = LOG_URL;
            req = {
                _token: TOKEN,
                care_plan_id: $cell.data('plan'),
                slot_index:   $cell.data('slot'),
                care_date:    $cell.data('date'),
                action:       nextCare,
            };
            nextLabel = nextCare;
        }

        $.post(url, req).done(function (res) {
            if (!res.success) return;
            var newStatus = (nextLabel === 'undo') ? 'pending'
                          : (nextLabel === 'given') ? 'done'
                          : (nextLabel === 'missed') ? 'skipped'
                          : nextLabel;
            $cell.removeClass('pending due missed done skipped').addClass(newStatus);
            $cell.data('status', newStatus);
            $cell.text(newStatus === 'done' ? '✓' : newStatus === 'skipped' ? '–' : '');
            toastr.success((kind === 'medication' ? 'Dose ' : 'Slot ') + nextLabel + '.');
        }).fail(function (xhr) {
            var m = xhr.responseJSON && xhr.responseJSON.msg;
            toastr.error(m || 'Could not save.');
        });
    });

    // ── Toolbar ──
    $('.window-btn').on('click', function () {
        $('.window-btn').removeClass('active');
        $(this).addClass('active');
        windowHours = parseInt($(this).data('hours'), 10);
        load();
    });
    $('#fs-refresh').on('click', load);

    // Initial load + auto-refresh every 30 s.
    load();
    setInterval(load, 30000);
});
</script>
@endsection
