@extends('layouts.admin')

@section('title', 'Dashboard')

@section('page-title', 'Dashboard')

@section('breadcrumbs')
    <nav aria-label="Breadcrumb" class="flex">
        <ol class="flex items-center space-x-2 text-sm">
            <li>
                <a class="text-slate-400 transition-colors hover:text-violet-600" href="{{ route('admin.dashboard') }}">
                    <span class="material-symbols-outlined text-[20px]">home</span>
                </a>
            </li>
            <li><span class="text-slate-300">/</span></li>
            <li><span class="font-medium text-violet-600">Overview</span></li>
        </ol>
    </nav>
@endsection

@section('content')
<div class="mx-auto max-w-[1400px] space-y-8 pb-8">
    @include('admin.dashboard.partials.hero-kpi')

    <div class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-between">
        <p class="text-sm text-slate-500">Shortcuts</p>
        <div class="flex flex-wrap gap-3">
            <a href="{{ route('admin.customers.create') }}" class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-800 shadow-sm transition-all hover:border-violet-200 hover:bg-slate-50">
                <span class="material-symbols-outlined text-[20px] text-violet-600">person_add</span>
                Add customer
            </a>
            <a href="{{ route('admin.invoices.create') }}" class="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-violet-600 to-indigo-600 px-4 py-2.5 text-sm font-semibold text-white shadow-lg shadow-violet-500/25 transition-all hover:from-violet-700 hover:to-indigo-700">
                <span class="material-symbols-outlined text-[20px]">add</span>
                New invoice
            </a>
        </div>
    </div>

    @include('admin.dashboard.partials.analytics')

    <div class="grid grid-cols-1 gap-6 xl:grid-cols-12">
        <div class="space-y-6 xl:col-span-8">
            @include('admin.dashboard.partials.recent')
        </div>
        <div class="xl:col-span-4">
            @include('admin.dashboard.partials.sidebar')
        </div>
    </div>
</div>

{{-- Note modal --}}
<div id="note-modal" data-admin-modal class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-900/60 backdrop-blur-sm">
    <div class="mx-4 w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-2xl">
        <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold text-slate-900" id="note-modal-title">Add note</h3>
            <button type="button" id="note-modal-close" class="rounded-lg p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-600">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>
        <form id="note-form">
            <input type="hidden" id="note-id" name="id">
            <div class="space-y-4">
                <div>
                    <label class="mb-1.5 block text-sm font-medium text-slate-700">Title</label>
                    <input type="text" id="note-title" name="title" required class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-slate-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20">
                </div>
                <div>
                    <label class="mb-1.5 block text-sm font-medium text-slate-700">Content</label>
                    <textarea id="note-content" name="content" rows="3" required class="w-full resize-none rounded-xl border border-slate-200 px-4 py-2.5 text-slate-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20"></textarea>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="mb-1.5 block text-sm font-medium text-slate-700">Type</label>
                        <select id="note-type" name="type" class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-slate-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20">
                            <option value="info">General</option>
                            <option value="warning">Payment due</option>
                            <option value="reminder">Reminder</option>
                            <option value="task">Client task</option>
                        </select>
                    </div>
                    <div>
                        <label class="mb-1.5 block text-sm font-medium text-slate-700">Due date</label>
                        <input type="date" id="note-due-date" name="due_date" class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-slate-900 focus:border-violet-500 focus:outline-none focus:ring-2 focus:ring-violet-500/20">
                    </div>
                </div>
                <label class="flex items-center gap-2">
                    <input type="checkbox" id="note-pinned" name="is_pinned" class="rounded border-slate-300 text-violet-600 focus:ring-violet-500">
                    <span class="text-sm text-slate-700">Pin note</span>
                </label>
            </div>
            <div class="mt-6 flex gap-3">
                <button type="button" id="note-cancel" class="flex-1 rounded-xl border border-slate-200 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50">Cancel</button>
                <button type="submit" class="flex-1 rounded-xl bg-violet-600 py-2.5 text-sm font-semibold text-white hover:bg-violet-700">Save</button>
            </div>
        </form>
    </div>
</div>

<div id="delete-note-modal" data-admin-modal class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-900/60 backdrop-blur-sm">
    <div class="mx-4 w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-2xl">
        <div class="flex gap-4">
            <div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-rose-100">
                <span class="material-symbols-outlined text-2xl text-rose-600">warning</span>
            </div>
            <div>
                <h3 class="text-lg font-bold text-slate-900">Delete note</h3>
                <p class="mt-1 text-sm text-slate-600">This cannot be undone.</p>
            </div>
        </div>
        <div class="mt-6 flex gap-3">
            <button type="button" id="delete-note-cancel" class="flex-1 rounded-xl border border-slate-200 py-2.5 text-sm font-semibold text-slate-700 hover:bg-slate-50">Cancel</button>
            <button type="button" id="delete-note-confirm" class="flex-1 rounded-xl bg-rose-600 py-2.5 text-sm font-semibold text-white hover:bg-rose-700">Delete</button>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const clockEl = document.getElementById('dashboard-live-clock');
    function tickClock() {
        if (!clockEl) return;
        const now = new Date();
        const t = now.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
        clockEl.innerHTML = '<span class="material-symbols-outlined text-[20px] text-violet-600" aria-hidden="true">schedule</span><span class="font-medium">' + t + '</span>';
    }
    tickClock();
    setInterval(tickClock, 30000);

    let currentYear = {{ now()->year }};
    let currentMonth = {{ now()->month }};

    function loadCalendar() {
        fetch('{{ route('admin.dashboard.calendar') }}?year=' + currentYear + '&month=' + currentMonth, {
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (!data.success) return;
            var el = document.getElementById('calendar-month-year');
            if (el) el.textContent = data.month;
            var calendarDays = document.getElementById('calendar-days');
            if (!calendarDays) return;
            calendarDays.innerHTML = '';
            data.days.forEach(function (day) {
                var span = document.createElement('span');
                span.className = 'flex min-h-[2.25rem] items-center justify-center rounded-xl text-sm transition-colors ';
                if (!day.isCurrentMonth) span.className += 'text-slate-300';
                else if (day.isToday) span.className += 'bg-violet-600 font-semibold text-white shadow-md shadow-violet-500/30';
                else span.className += 'text-slate-800 hover:bg-slate-100';
                var hasEvent = data.events.some(function (e) { return e.date === day.date; });
                if (hasEvent) {
                    span.className += ' relative font-medium';
                    span.innerHTML = day.day + '<span class="absolute bottom-1 left-1/2 h-1 w-1 -translate-x-1/2 rounded-full bg-rose-500"></span>';
                } else span.textContent = day.day;
                calendarDays.appendChild(span);
            });
        })
        .catch(function (e) { console.error(e); });
    }

    var calPrev = document.getElementById('calendar-prev');
    var calNext = document.getElementById('calendar-next');
    if (calPrev) calPrev.addEventListener('click', function () {
        currentMonth--;
        if (currentMonth < 1) { currentMonth = 12; currentYear--; }
        loadCalendar();
    });
    if (calNext) calNext.addEventListener('click', function () {
        currentMonth++;
        if (currentMonth > 12) { currentMonth = 1; currentYear++; }
        loadCalendar();
    });
    loadCalendar();

    const noteModal = document.getElementById('note-modal');
    const noteForm = document.getElementById('note-form');
    const addNoteBtn = document.getElementById('add-note-btn');

    function openNoteModal(noteId) {
        if (!noteModal || !noteForm) return;
        if (noteId) {
            fetch('{{ route('admin.dashboard.notes') }}?limit=20', { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' } })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                if (!data.success) return;
                var note = data.notes.find(function (n) { return n.id == noteId; });
                if (note) {
                    document.getElementById('note-modal-title').textContent = 'Edit note';
                    document.getElementById('note-id').value = note.id;
                    document.getElementById('note-title').value = note.title;
                    document.getElementById('note-content').value = note.content;
                    document.getElementById('note-type').value = note.type;
                    document.getElementById('note-due-date').value = note.due_date || '';
                    document.getElementById('note-pinned').checked = !!note.is_pinned;
                }
            });
        } else {
            document.getElementById('note-modal-title').textContent = 'Add note';
            noteForm.reset();
            document.getElementById('note-id').value = '';
        }
        noteModal.classList.remove('hidden');
        noteModal.classList.add('flex');
    }
    function closeNoteModal() {
        if (!noteModal || !noteForm) return;
        noteModal.classList.add('hidden');
        noteModal.classList.remove('flex');
        noteForm.reset();
    }

    if (addNoteBtn) addNoteBtn.addEventListener('click', function () { openNoteModal(null); });
    var noteModalClose = document.getElementById('note-modal-close');
    var noteCancel = document.getElementById('note-cancel');
    if (noteModalClose) noteModalClose.addEventListener('click', closeNoteModal);
    if (noteCancel) noteCancel.addEventListener('click', closeNoteModal);

    document.addEventListener('click', function (e) {
        var ed = e.target.closest('.edit-note');
        if (ed && noteModal && noteForm) openNoteModal(ed.dataset.noteId);
    });

    var noteToDelete = null;
    document.addEventListener('click', function (e) {
        var del = e.target.closest('.delete-note');
        if (del) {
            noteToDelete = del.dataset.noteId;
            var dm = document.getElementById('delete-note-modal');
            if (dm) {
                dm.classList.remove('hidden');
                dm.classList.add('flex');
            }
        }
    });

    var deleteNoteConfirm = document.getElementById('delete-note-confirm');
    if (deleteNoteConfirm) deleteNoteConfirm.addEventListener('click', function () {
        if (!noteToDelete) return;
        fetch('{{ route('admin.dashboard.notes.delete', ':id') }}'.replace(':id', noteToDelete), {
            method: 'DELETE',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (data.success) {
                loadNotes();
                var dm = document.getElementById('delete-note-modal');
                if (dm) {
                    dm.classList.add('hidden');
                    dm.classList.remove('flex');
                }
                noteToDelete = null;
            }
        });
    });
    var deleteNoteCancel = document.getElementById('delete-note-cancel');
    if (deleteNoteCancel) deleteNoteCancel.addEventListener('click', function () {
        var dm = document.getElementById('delete-note-modal');
        if (dm) {
            dm.classList.add('hidden');
            dm.classList.remove('flex');
        }
        noteToDelete = null;
    });

    if (noteForm) noteForm.addEventListener('submit', function (e) {
        e.preventDefault();
        var noteId = document.getElementById('note-id').value;
        var url = noteId
            ? '{{ route('admin.dashboard.notes.update', ':id') }}'.replace(':id', noteId)
            : '{{ route('admin.dashboard.notes.store') }}';
        var method = noteId ? 'PUT' : 'POST';
        var data = {
            title: document.getElementById('note-title').value,
            content: document.getElementById('note-content').value,
            type: document.getElementById('note-type').value,
            due_date: document.getElementById('note-due-date').value || null,
            is_pinned: document.getElementById('note-pinned').checked
        };
        fetch(url, {
            method: method,
            headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            body: JSON.stringify(data)
        })
        .then(function (r) { return r.json(); })
        .then(function (d) {
            if (d.success) {
                closeNoteModal();
                loadNotes();
                loadCalendar();
            }
        });
    });

    function noteTypeMeta(type) {
        var map = {
            info: { label: 'Note', ring: 'ring-slate-200/80 bg-slate-50/80' },
            warning: { label: 'Payment due', ring: 'ring-amber-200/80 bg-amber-50/50' },
            reminder: { label: 'Reminder', ring: 'ring-sky-200/80 bg-sky-50/50' },
            task: { label: 'Client task', ring: 'ring-emerald-200/80 bg-emerald-50/50' }
        };
        return map[type] || map.info;
    }

    function loadNotes() {
        fetch('{{ route('admin.dashboard.notes') }}?limit=20', { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' } })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (!data.success) return;
            var container = document.getElementById('notes-container');
            if (!container) return;
            container.innerHTML = '';
            if (data.notes.length === 0) {
                container.innerHTML = '<div class="rounded-xl border border-dashed border-slate-200 bg-slate-50/50 py-10 text-center"><span class="material-symbols-outlined mb-2 text-4xl text-slate-300">note_add</span><p class="text-sm text-slate-500">No notes yet</p><p class="mt-1 text-xs text-slate-400">Capture reminders and follow-ups</p></div>';
                return;
            }
            data.notes.forEach(function (note) {
                var meta = noteTypeMeta(note.type);
                var pin = note.is_pinned ? '<span class="material-symbols-outlined text-[16px] text-amber-500" title="Pinned">push_pin</span>' : '';
                var due = note.due_date
                    ? '<span class="mt-2 inline-flex items-center gap-1 rounded-full bg-white/90 px-2 py-0.5 text-xs font-medium text-violet-700 ring-1 ring-violet-200"><span class="material-symbols-outlined text-[14px]">event</span>' + new Date(note.due_date + 'T12:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) + '</span>'
                    : '';
                var div = document.createElement('div');
                div.className = 'note-item group rounded-xl border border-slate-100 p-3 ring-1 ' + meta.ring + ' transition-all hover:shadow-sm';
                div.dataset.noteId = note.id;
                div.innerHTML = '<div class="flex items-start justify-between gap-2"><div class="min-w-0 flex-1"><div class="mb-1 flex flex-wrap items-center gap-2"><span class="rounded-md bg-white/80 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-slate-600 ring-1 ring-slate-200/80">' + meta.label + '</span>' + pin + '</div><p class="font-semibold text-slate-900">' + escapeHtml(note.title) + '</p><p class="mt-1 line-clamp-2 text-sm text-slate-600">' + escapeHtml(note.content) + '</p>' + due + '</div><div class="flex shrink-0 gap-0.5 opacity-70 transition-opacity group-hover:opacity-100"><button type="button" class="edit-note rounded-lg p-1.5 text-slate-400 hover:bg-white hover:text-violet-600" data-note-id="' + note.id + '"><span class="material-symbols-outlined text-[18px]">edit</span></button><button type="button" class="delete-note rounded-lg p-1.5 text-slate-400 hover:bg-white hover:text-rose-600" data-note-id="' + note.id + '"><span class="material-symbols-outlined text-[18px]">delete</span></button></div></div>';
                container.appendChild(div);
            });
        });
    }

    function escapeHtml(s) {
        if (!s) return '';
        var d = document.createElement('div');
        d.textContent = s;
        return d.innerHTML;
    }

    loadNotes();
});
</script>
@endpush
