{{--
    Polymorphic notes panel for an owner OR a pet profile.
    Required vars: $subjectType ('owner'|'pet'), $subjectId
    Renders an empty container + script; the script fetches and renders the
    notes via AJAX so the panel works the same way on both pages.
--}}
@php
    $vcSubjectType = $subjectType ?? null;
    $vcSubjectId   = $subjectId   ?? null;
    $vcCanWrite    = auth()->user()->can('vet_clinic.manage_appointments')
                  || auth()->user()->can('vet_clinic.manage_subject_notes');
    $vcCanConfidential = auth()->user()->can('vet_clinic.view_confidential_notes');
@endphp

@if($vcSubjectType && $vcSubjectId)
<style>
.vc-notes-card { background:#fff; border:1px solid #e5e7eb; border-radius:10px; padding:14px 16px; margin-top:14px; }
.vc-notes-hd { display:flex; align-items:center; gap:10px; margin-bottom:10px; }
.vc-notes-hd h4 { font-size:13px; font-weight:800; color:#0f172a; margin:0; text-transform:uppercase; letter-spacing:.4px; }
.vc-notes-hd .badge-key { background:#fef3c7; color:#92400e; font-size:9px; font-weight:700; padding:2px 7px; border-radius:10px; text-transform:uppercase; letter-spacing:.4px; }
.vc-notes-empty { text-align:center; color:#94a3b8; padding:18px; font-size:12.5px; }
.vc-note { border:1px solid #e5e7eb; border-radius:8px; padding:10px 12px; margin-bottom:8px; }
.vc-note.is-conf { background:#fff7ed; border-color:#fed7aa; border-left:4px solid #ea580c; }
.vc-note-hd { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; margin-bottom:5px; }
.vc-note-title { font-size:13px; font-weight:800; color:#0f172a; }
.vc-note-conf  { font-size:9px; font-weight:800; text-transform:uppercase; letter-spacing:.5px; color:#9a3412; background:#fed7aa; border-radius:10px; padding:1px 7px; }
.vc-note-body  { font-size:12.5px; color:#1e293b; white-space:pre-wrap; line-height:1.5; }
.vc-note-meta  { font-size:10.5px; color:#94a3b8; margin-top:6px; display:flex; gap:10px; flex-wrap:wrap; }
.vc-note-actions { margin-left:auto; display:flex; gap:4px; }
.vc-notes-form { padding-top:10px; border-top:1px dashed #e5e7eb; margin-top:6px; }
</style>

<div class="vc-notes-card" id="vc_notes_card_{{ $vcSubjectType }}_{{ $vcSubjectId }}">
    <div class="vc-notes-hd">
        <h4><i class="fa fa-sticky-note" style="color:#f59e0b;"></i> {{ ucfirst($vcSubjectType) }} Notes</h4>
        @if($vcCanConfidential)
            <span class="badge-key" title="You may read confidential notes"><i class="fa fa-key"></i> Confidential access</span>
        @endif
    </div>

    <div class="vc-notes-list"><span class="text-muted" style="font-size:12px;"><i class="fa fa-spinner fa-spin"></i> Loading notes…</span></div>

    @if($vcCanWrite)
    <div class="vc-notes-form">
        <input type="text" class="form-control input-sm vc-note-title" placeholder="Title (optional)" maxlength="191" style="margin-bottom:6px;">
        <textarea class="form-control vc-note-body" rows="2" placeholder="Add a note…" maxlength="5000"></textarea>
        <div style="display:flex;align-items:center;margin-top:6px;gap:10px;">
            @if($vcCanConfidential)
            <label style="font-weight:normal;font-size:11.5px;cursor:pointer;color:#9a3412;">
                <input type="checkbox" class="vc-note-conf-chk">
                <i class="fa fa-lock"></i> Mark as confidential — hidden from users without the key
            </label>
            @endif
            <button class="btn btn-sm btn-primary vc-note-save" style="margin-left:auto;">
                <i class="fa fa-plus"></i> Add note
            </button>
        </div>
    </div>
    @endif
</div>

<script>
// Mid-page partial — defer to load so jQuery (page-end) is ready.
window.addEventListener('load', function () {
    var subjectType = @json($vcSubjectType);
    var subjectId   = @json((int) $vcSubjectId);
    var $card = $('#vc_notes_card_' + subjectType + '_' + subjectId);
    var listUrl  = '{{ url('vet-clinic/notes') }}/' + subjectType + '/' + subjectId;
    var token = '{{ csrf_token() }}';

    function render(notes) {
        var $list = $card.find('.vc-notes-list').empty();
        if (!notes.length) {
            $list.html('<div class="vc-notes-empty"><i class="fa fa-feather"></i> No notes yet for this ' + subjectType + '.</div>');
            return;
        }
        notes.forEach(function (n) {
            var $n = $('<div class="vc-note"></div>').toggleClass('is-conf', n.is_confidential).attr('data-id', n.id);
            var hd = '<div class="vc-note-hd">';
            if (n.title) hd += '<span class="vc-note-title">' + $('<i>').text(n.title).html() + '</span>';
            if (n.is_confidential) hd += '<span class="vc-note-conf"><i class="fa fa-lock"></i> Confidential</span>';
            if (n.can_edit) {
                hd += '<span class="vc-note-actions">' +
                      '<button class="btn btn-xs btn-default vc-note-edit"><i class="fa fa-edit"></i></button> ' +
                      '<button class="btn btn-xs btn-danger vc-note-del"><i class="fa fa-trash"></i></button>' +
                      '</span>';
            }
            hd += '</div>';
            $n.append(hd);
            $n.append($('<div class="vc-note-body"></div>').text(n.body));
            $n.append('<div class="vc-note-meta">' +
                '<span><i class="fa fa-user"></i> ' + $('<i>').text(n.created_by || '—').html() + '</span>' +
                '<span><i class="fa fa-clock"></i> ' + (n.created_at || '') + '</span>' +
                (n.updated_at && n.updated_at !== n.created_at
                    ? '<span><i class="fa fa-pen"></i> edited ' + (n.updated_at) + (n.updated_by ? ' by ' + $('<i>').text(n.updated_by).html() : '') + '</span>'
                    : '') +
                '</div>');
            $list.append($n);
            $n.data('note', n);
        });
    }

    function reload() {
        $.get(listUrl).done(function (res) { render(res.notes || []); });
    }

    $card.find('.vc-note-save').on('click', function () {
        var body  = $card.find('.vc-note-body').val().trim();
        if (!body) { toastr.warning('Please enter a note body.'); return; }
        var title = $card.find('.vc-note-title').val().trim();
        var conf  = $card.find('.vc-note-conf-chk').is(':checked');
        var $btn  = $(this).prop('disabled', true);
        $.ajax({
            url: listUrl, method: 'POST',
            data: { _token: token, title: title, body: body, visibility: conf ? 'confidential' : 'normal' },
            success: function (res) {
                if (res.success) {
                    toastr.success(res.msg);
                    $card.find('.vc-note-title, .vc-note-body').val('');
                    $card.find('.vc-note-conf-chk').prop('checked', false);
                    reload();
                }
            },
            error: function (xhr) {
                toastr.error(xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : 'Could not save note.');
            },
            complete: function () { $btn.prop('disabled', false); }
        });
    });

    $card.on('click', '.vc-note-edit', function () {
        var $n = $(this).closest('.vc-note');
        var n  = $n.data('note');
        var newBody  = window.prompt('Edit note body:', n.body);
        if (newBody === null) return;
        $.ajax({
            url: '{{ url('vet-clinic/notes') }}/' + n.id + '/update', method: 'POST',
            data: { _token: token, title: n.title || '', body: newBody, visibility: n.visibility },
            success: function (res) { if (res.success) { toastr.success(res.msg); reload(); } }
        });
    });

    $card.on('click', '.vc-note-del', function () {
        var id = $(this).closest('.vc-note').attr('data-id');
        if (!confirm('Delete this note?')) return;
        $.ajax({
            url: '{{ url('vet-clinic/notes') }}/' + id, method: 'DELETE',
            data: { _token: token },
            success: function (res) { if (res.success) { toastr.success(res.msg); reload(); } }
        });
    });

    reload();
});
</script>
@endif
