<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Notas</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <style>
        body {
            background: linear-gradient(135deg, #f8e9d2 0%, #cfe0f0 100%);
            min-height: 100vh;
        }
        .app-wrap { max-width: 1100px; margin: 0 auto; padding: 2.5rem 1rem 4rem; }
        .app-title {
            text-align: center;
            font-weight: 700;
            color: #2b2b40;
            margin-bottom: 1.75rem;
            letter-spacing: -.5px;
        }
        .create-card {
            background: #fff;
            border-radius: 1rem;
            box-shadow: 0 10px 30px rgba(30, 41, 59, .10);
            padding: 1.5rem;
            margin-bottom: 2.5rem;
        }
        .create-card textarea {
            border: 1px solid #e2e8f0;
            border-radius: .75rem;
            resize: vertical;
            min-height: 90px;
        }
        .create-card textarea:focus {
            box-shadow: 0 0 0 .2rem rgba(99, 102, 241, .15);
            border-color: #a5b4fc;
        }
        .section-title {
            text-align: center;
            font-weight: 600;
            color: #2b2b40;
            margin-bottom: 1.5rem;
        }
        .notes-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
            gap: 1.25rem;
        }
        .note-card {
            background: #fff;
            border-radius: 1rem;
            box-shadow: 0 6px 18px rgba(30, 41, 59, .08);
            padding: 1.15rem 1.25rem;
            display: flex;
            flex-direction: column;
            transition: transform .12s ease, box-shadow .12s ease;
        }
        .note-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 26px rgba(30, 41, 59, .13);
        }
        .note-card-header {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-bottom: .5rem;
        }
        .note-card-header h6 {
            font-weight: 700;
            color: #312e81;
            margin: 0;
        }
        .note-date {
            font-size: .72rem;
            color: #94a3b8;
            white-space: nowrap;
        }
        .note-content {
            color: #475569;
            font-size: .9rem;
            flex-grow: 1;
            margin-bottom: .9rem;
            white-space: pre-wrap;
            word-break: break-word;
        }
        .note-actions .btn { font-size: .78rem; padding: .3rem .7rem; }
        .note-edit-textarea {
            border: 1px solid #c7d2fe;
            border-radius: .5rem;
            font-size: .9rem;
            margin-bottom: .75rem;
            resize: vertical;
            min-height: 80px;
        }
        .empty-state {
            grid-column: 1 / -1;
            text-align: center;
            color: #94a3b8;
            padding: 2.5rem 0;
        }
        .toast-container { z-index: 1080; }
    </style>
</head>
<body>

<div class="app-wrap">
   

    <div class="create-card">
        <label class="form-label fw-semibold" for="newNoteContent">Create New Note</label>
        <textarea class="form-control" id="newNoteContent" placeholder="Escribe tu nota..."></textarea>
        <div class="invalid-feedback d-block text-danger small" id="newNoteError"></div>
        <div class="d-flex justify-content-end gap-2 mt-3">
            <button type="button" class="btn btn-outline-secondary" onclick="cancelNewNote()">Cancel</button>
            <button type="button" class="btn btn-primary" id="addNoteBtn" onclick="addNote()">Add Note</button>
        </div>
    </div>

    <h5 class="section-title">Notes List</h5>

    <div class="notes-grid" id="notesGrid">
        <div class="empty-state">Cargando...</div>
    </div>
</div>

<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="appToast" class="toast align-items-center text-white border-0" role="alert">
        <div class="d-flex">
            <div class="toast-body" id="appToastBody">...</div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
    let notesCache = [];
    let editingId = null;

    function showToast(message, ok = true) {
        const toastEl = document.getElementById('appToast');
        const body = document.getElementById('appToastBody');
        toastEl.classList.remove('bg-success', 'bg-danger');
        toastEl.classList.add(ok ? 'bg-success' : 'bg-danger');
        body.textContent = message;
        new bootstrap.Toast(toastEl, { delay: 3000 }).show();
    }

    async function apiRequest(url, options = {}) {
        options.headers = Object.assign({
            'X-CSRF-TOKEN': csrfToken,
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json',
        }, options.headers || {});

        const res = await fetch(url, options);
        let json = null;
        try { json = await res.json(); } catch (e) {}

        if (!res.ok) {
            const err = new Error((json && json.message) || 'Ocurrió un error.');
            err.status = res.status;
            err.payload = json;
            throw err;
        }
        return json;
    }

    function escapeHtml(str) {
        return String(str ?? '').replace(/[&<>"']/g, s => ({
            '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
        }[s]));
    }

    function formatDate(isoString) {
        if (!isoString) return '';
        const d = new Date(isoString.replace(' ', 'T'));
        if (isNaN(d)) return '';
        return d.toLocaleDateString('es-PE', { day: '2-digit', month: 'short', year: 'numeric' }) +
               ' · ' + d.toLocaleTimeString('es-PE', { hour: '2-digit', minute: '2-digit' });
    }

    // ---- Crear nota ----
    function cancelNewNote() {
        document.getElementById('newNoteContent').value = '';
        document.getElementById('newNoteError').textContent = '';
        document.getElementById('newNoteContent').classList.remove('is-invalid');
    }

    async function addNote() {
        const textarea = document.getElementById('newNoteContent');
        const errEl = document.getElementById('newNoteError');
        const content = textarea.value.trim();
        errEl.textContent = '';
        textarea.classList.remove('is-invalid');

        if (!content) {
            errEl.textContent = 'Escribe algo antes de guardar la nota.';
            textarea.classList.add('is-invalid');
            return;
        }

        const btn = document.getElementById('addNoteBtn');
        btn.disabled = true;
        try {
            const res = await apiRequest(`<?php echo e(url('notes')); ?>`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ content }),
            });
            textarea.value = '';
            showToast(res.message, true);
            loadNotes();
        } catch (e) {
            showToast(e.message, false);
        } finally {
            btn.disabled = false;
        }
    }

    // ---- Editar / Eliminar (inline, sin modal) ----
    function startEdit(id) {
        editingId = id;
        renderNotes(notesCache);
    }

    function cancelEdit() {
        editingId = null;
        renderNotes(notesCache);
    }

    async function saveEdit(id) {
        const textarea = document.getElementById(`edit-textarea-${id}`);
        const content = textarea.value.trim();
        if (!content) {
            textarea.classList.add('is-invalid');
            return;
        }
        try {
            const res = await apiRequest(`<?php echo e(url('notes')); ?>/${id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ content }),
            });
            editingId = null;
            showToast(res.message, true);
            loadNotes();
        } catch (e) {
            showToast(e.message, false);
        }
    }

    async function deleteNote(id) {
        if (!confirm('¿Eliminar esta nota?')) return;
        try {
            const res = await apiRequest(`<?php echo e(url('notes')); ?>/${id}`, { method: 'DELETE' });
            showToast(res.message, true);
            loadNotes();
        } catch (e) {
            showToast(e.message, false);
        }
    }

    // ---- Render ----
    function renderNotes(notes) {
        const grid = document.getElementById('notesGrid');

        if (!notes.length) {
            grid.innerHTML = '<div class="empty-state">Aún no hay notas. ¡Crea la primera!</div>';
            return;
        }

        grid.innerHTML = notes.map((n, i) => {
            const numero = i + 1; // Título automático: Nota 1, Nota 2, ...
            const fecha = formatDate(n.created_at);

            if (editingId === n.id) {
                return `
                    <div class="note-card">
                        <div class="note-card-header">
                            <h6>Nota ${numero}</h6>
                            <span class="note-date">${fecha}</span>
                        </div>
                        <textarea class="form-control note-edit-textarea" id="edit-textarea-${n.id}">${escapeHtml(n.content)}</textarea>
                        <div class="note-actions d-flex gap-2">
                            <button class="btn btn-primary" onclick="saveEdit(${n.id})">Guardar</button>
                            <button class="btn btn-outline-secondary" onclick="cancelEdit()">Cancel</button>
                        </div>
                    </div>
                `;
            }

            return `
                <div class="note-card">
                    <div class="note-card-header">
                        <h6>Nota ${numero}</h6>
                        <span class="note-date">${fecha}</span>
                    </div>
                    <div class="note-content">${escapeHtml(n.content)}</div>
                    <div class="note-actions d-flex gap-2">
                        <button class="btn btn-primary" onclick="startEdit(${n.id})">Edit</button>
                        <button class="btn btn-danger" onclick="deleteNote(${n.id})">Delete</button>
                    </div>
                </div>
            `;
        }).join('');
    }

    async function loadNotes() {
        try {
            const notes = await apiRequest(`<?php echo e(url('notes/data')); ?>`);
            notesCache = notes;
            renderNotes(notes);
        } catch (e) {
            showToast(e.message, false);
        }
    }

    loadNotes();
</script>
</body>
</html>
<?php /**PATH C:\xampp\htdocs\example-app - copia\resources\views/view_nota/nota.blade.php ENDPATH**/ ?>