<!DOCTYPE html>
<html lang="ro">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Editor Publicație</title>
  <!-- EasyMDE CSS -->
  <link rel="stylesheet" href="https://unpkg.com/easymde/dist/easymde.min.css">
  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      background-color: #f3f4f6;
      padding: 30px 10px;
      font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
    }
    .editor-card {
      max-width: 900px;
      margin: 0 auto;
      background: white;
      padding: 35px;
      border-radius: 16px;
      box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
      border: 1px solid #e5e7eb;
    }
    .editor-toolbar {
      border: 1px solid #d1d5db !important;
      border-radius: 8px 8px 0 0 !important;
      background-color: #f9fafb;
    }
    .CodeMirror {
      border: 1px solid #d1d5db !important;
      border-radius: 0 0 8px 8px !important;
      min-height: 400px;
      font-size: 15px;
    }
    .form-control:focus {
      border-color: #3b82f6;
      box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.15);
    }
  </style>
</head>
<body>

  <div class="editor-card">
    <div class="d-flex align-items-center mb-4">
      <svg class="text-primary me-2" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
        <path d="M12 20h9"></path>
        <path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z"></path>
      </svg>
      <h2 class="m-0 fw-bold text-dark" id="editor-title-label">Adaugă Articol Nou</h2>
    </div>

    <div class="mb-4">
      <label for="title" class="form-label fw-bold text-secondary">Titlu Articol</label>
      <input type="text" class="form-control form-control-lg border-2" id="title" placeholder="Introduceți un titlu captivant...">
    </div>

    <div class="mb-4">
      <label for="content" class="form-label fw-bold text-secondary">Conținut Publicație</label>
      <textarea id="content"></textarea>
    </div>

    <div class="d-flex justify-content-end gap-3">
      <button class="btn btn-light border btn-lg px-4" onclick="window.close()">Renunță</button>
      <button class="btn btn-primary btn-lg px-5" id="save-btn" onclick="saveArticle()">Salvează</button>
    </div>

    <div class="alert mt-4 d-none" id="status-alert" role="alert"></div>
  </div>

  <!-- EasyMDE JS -->
  <script src="https://unpkg.com/easymde/dist/easymde.min.js"></script>
  <script>
    // Inițializare editor Markdown
    const easyMDE = new EasyMDE({ 
        element: document.getElementById('content'),
        spellChecker: false,
        placeholder: "Scrieți conținutul publicației folosind formatarea din bara de sus...",
        autosave: {
            enabled: true,
            uniqueId: "article_editor_autosave_temp",
            delay: 2000,
        },
        toolbar: [
            "bold", "italic", "strikethrough", "|", 
            "heading-1", "heading-2", "heading-3", "|", 
            "quote", "unordered-list", "ordered-list", "|", 
            "link", "image", "table", "horizontal-rule", "|", 
            "preview", "side-by-side", "fullscreen", "|", 
            "guide"
        ]
    });

    // Preluare parametri din șablonul Jinja
    const articleId = "{{ article_id }}";
    const token = "{{ token }}";

    // Dacă avem ID de articol, înseamnă că suntem în modul editare
    if (articleId && articleId !== "None") {
        document.getElementById('editor-title-label').innerText = "Editează Articolul";
        
        // Încarcă datele articolului de pe server
        fetch(`/articles/${articleId}`, {
            headers: { 'Authorization': `Bearer ${token}` }
        })
        .then(res => {
            if (!res.ok) throw new Error("Nu s-au putut încărca datele articolului.");
            return res.json();
        })
        .then(data => {
            if (data.title) document.getElementById('title').value = data.title;
            if (data.content) easyMDE.value(data.content);
        })
        .catch(err => {
            showStatus(err.message, "danger");
        });
    }

    function showStatus(message, type) {
        const alertDiv = document.getElementById('status-alert');
        alertDiv.className = `alert alert-${type} mt-4`;
        alertDiv.innerText = message;
        alertDiv.classList.remove('d-none');
    }

    function saveArticle() {
        const title = document.getElementById('title').value.trim();
        const content = easyMDE.value().trim();
        
        if (!title || !content) {
            showStatus("Titlul și conținutul sunt obligatorii!", "danger");
            return;
        }

        const payload = { title, content };
        const url = (articleId && articleId !== "None") ? `/articles/update/${articleId}` : '/articles/add';
        const method = (articleId && articleId !== "None") ? 'PUT' : 'POST';

        const saveBtn = document.getElementById('save-btn');
        saveBtn.disabled = true;

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(payload)
        })
        .then(async res => {
            const data = await res.json();
            if (res.status === 200 || res.status === 201) {
                showStatus("Publicația a fost salvată cu succes! Această fereastră se va închide...", "success");
                // Șterge salvările automate temporare
                easyMDE.clearAutosavedValue();
                setTimeout(() => {
                    window.close();
                }, 1500);
            } else {
                throw new Error(data.error || "A apărut o eroare la salvare.");
            }
        })
        .catch(err => {
            showStatus(err.message, "danger");
            saveBtn.disabled = false;
        });
    }
  </script>
</body>
</html>
