{% extends "admin/base.html" %}

{% block extrastyle %}
  {{ block.super }}
  <style>
    #admin-chat-toggle {
      position: fixed;
      right: 20px;
      bottom: 20px;
      z-index: 9999;
      width: 48px;
      height: 48px;
      border-radius: 24px;
      border: none;
      background: #0c4b33;
      color: #fff;
      cursor: pointer;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
      font-size: 22px;
      line-height: 1;
    }
    #admin-chat-panel {
      position: fixed;
      right: 20px;
      bottom: 80px;
      z-index: 9999;
      width: 280px;
      background: #fff;
      border: 1px solid #d8dde3;
      border-radius: 8px;
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
      padding: 12px;
      display: none;
    }
    #admin-chat-messages {
      height: 220px;
      overflow-y: auto;
      padding: 8px;
      border: 1px solid #e3e7ec;
      border-radius: 6px;
      background: #f7f9fb;
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      gap: 6px;
    }
    .admin-chat-message {
      max-width: 85%;
      padding: 6px 8px;
      border-radius: 10px;
      font-size: 13px;
      line-height: 1.3;
      word-break: break-word;
    }
    .admin-chat-message.user {
      align-self: flex-end;
      background: #0c4b33;
      color: #fff;
    }
    .admin-chat-message.assistant {
      align-self: flex-start;
      background: #fff;
      border: 1px solid #d8dde3;
      color: #111;
    }
    .admin-chat-loading {
      display: inline-block;
      width: 12px;
      height: 12px;
      border: 2px solid #c7cdd4;
      border-top-color: #0c4b33;
      border-radius: 50%;
      animation: admin-chat-spin 0.8s linear infinite;
      vertical-align: middle;
    }
    @keyframes admin-chat-spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    #admin-chat-panel form {
      display: flex;
      gap: 8px;
    }
    #admin-chat-actions {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 8px;
    }
    #admin-chat-clear {
      background: #f7f9fb;
      border: 1px solid #e3e7ec;
      border-radius: 4px;
      color: #5a6673;
      font-size: 12px;
      cursor: pointer;
      padding: 4px 8px;
      display: flex;
      align-items: center;
      gap: 4px;
      transition: all 0.2s ease;
    }
    #admin-chat-clear:hover {
      background: #eef2f5;
      border-color: #c7cdd4;
      color: #0c4b33;
    }
    #admin-chat-clear:active {
      background: #e3e7ec;
    }
    #admin-chat-clear span:first-child {
      font-size: 14px;
    }
    #admin-chat-input {
      flex: 1;
      padding: 6px 8px;
      border: 1px solid #c7cdd4;
      border-radius: 4px;
    }
    #admin-chat-send {
      padding: 6px 10px;
      border-radius: 4px;
      border: none;
      background: #0c4b33;
      color: #fff;
      cursor: pointer;
    }
  </style>
{% endblock %}

{% block footer %}
  {{ block.super }}
  <div id="admin-chat-panel" aria-hidden="true">
    <div id="admin-chat-messages" aria-live="polite" aria-atomic="false"></div>
    <div id="admin-chat-actions">
      <button id="admin-chat-clear" type="button" title="Clear chat history">
        <span>🗑️</span>
        <span>Clear</span>
      </button>
    </div>
    <form id="admin-chat-form">
      <input id="admin-chat-input" type="text" placeholder="Type a message..." autocomplete="off" />
      <button id="admin-chat-send" type="submit">Send</button>
    </form>
  </div>
  <button id="admin-chat-toggle" type="button" aria-controls="admin-chat-panel" aria-expanded="false">
    💬
  </button>
  <script>
    (function () {
      function getCookie(name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length === 2) {
          return parts.pop().split(";").shift();
        }
        return "";
      }

      var panel = document.getElementById("admin-chat-panel");
      var toggle = document.getElementById("admin-chat-toggle");
      var form = document.getElementById("admin-chat-form");
      var input = document.getElementById("admin-chat-input");
      var messagesContainer = document.getElementById("admin-chat-messages");
      var clearButton = document.getElementById("admin-chat-clear");
      var storageKey = "admin_chat_messages";
      var messagesState = [];

      function renderMessages(messages) {
        messagesContainer.innerHTML = "";
        messages.forEach(function (item) {
          appendMessageElement(item);
        });
        messagesState = messages.slice();
        saveMessages(messagesState);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
      }

      function appendMessageElement(item) {
        var messageEl = document.createElement("div");
        messageEl.className = "admin-chat-message " + item.role;
        messageEl.textContent = item.content;
        messagesContainer.appendChild(messageEl);
        return messageEl;
      }

      function saveMessages(messages) {
        try {
          localStorage.setItem(storageKey, JSON.stringify(messages));
        } catch (error) {
          console.error("Admin chat storage error:", error);
        }
      }

      function loadMessages() {
        try {
          var raw = localStorage.getItem(storageKey);
          if (!raw) {
            return [];
          }
          var parsed = JSON.parse(raw);
          return Array.isArray(parsed) ? parsed : [];
        } catch (error) {
          console.error("Admin chat storage error:", error);
          return [];
        }
      }

      function hydrateHistory() {
        fetch("{% url 'django_ai_admin_chat:admin-chat-history' %}", {
          method: "GET",
          headers: {
            "Accept": "application/json"
          }
        })
          .then(function (response) {
            if (!response.ok) {
              throw new Error("History fetch failed");
            }
            return response.json();
          })
          .then(function (data) {
            var history = (data && data.messages) || [];
            if (history.length > 0) {
              renderMessages(history);
              return;
            }
            var cached = loadMessages();
            if (cached.length > 0) {
              renderMessages(cached);
            }
          })
          .catch(function () {
            var cached = loadMessages();
            if (cached.length > 0) {
              renderMessages(cached);
            }
          });
      }

      toggle.addEventListener("click", function () {
        var isOpen = panel.style.display === "block";
        panel.style.display = isOpen ? "none" : "block";
        toggle.setAttribute("aria-expanded", String(!isOpen));
        panel.setAttribute("aria-hidden", String(isOpen));
        if (!isOpen) {
          input.focus();
        }
      });

      form.addEventListener("submit", function (event) {
        event.preventDefault();
        var message = input.value.trim();
        if (!message) {
          return;
        }
        input.value = "";

        var userMessage = { role: "user", content: message };
        messagesState.push(userMessage);
        appendMessageElement(userMessage);

        var assistantMessage = { role: "assistant", content: "" };
        messagesState.push(assistantMessage);
        var assistantElement = appendMessageElement(assistantMessage);
        var loadingSpinner = document.createElement("span");
        loadingSpinner.className = "admin-chat-loading";
        loadingSpinner.setAttribute("aria-label", "Loading");
        assistantElement.appendChild(loadingSpinner);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;

        var streamUrl = "{% url 'django_ai_admin_chat:admin-chat-stream' %}";
        var source = new EventSource(
          streamUrl + "?message=" + encodeURIComponent(message)
        );
        source.onmessage = function (event) {
          var payload = {};
          try {
            payload = JSON.parse(event.data || "{}");
          } catch (error) {
            console.error("Admin chat stream parse error:", error);
          }
          if (payload.error) {
            if (loadingSpinner.parentNode) {
              loadingSpinner.remove();
            }
            assistantElement.textContent = payload.error;
            assistantMessage.content = payload.error;
            saveMessages(messagesState);
            source.close();
            return;
          }
          if (payload.done) {
            if (loadingSpinner.parentNode) {
              loadingSpinner.remove();
            }
            saveMessages(messagesState);
            source.close();
            return;
          }
          if (payload.chunk) {
            if (loadingSpinner.parentNode) {
              loadingSpinner.remove();
            }
            assistantMessage.content += payload.chunk;
            assistantElement.textContent = assistantMessage.content;
            saveMessages(messagesState);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
          }
        };
        source.onerror = function (error) {
          console.error("Admin chat stream error:", error);
          if (loadingSpinner.parentNode) {
            loadingSpinner.remove();
          }
          source.close();
        };
      });

      clearButton.addEventListener("click", function () {
        fetch("{% url 'django_ai_admin_chat:admin-chat-clear' %}", {
          method: "POST",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-CSRFToken": getCookie("csrftoken")
          }
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (data) {
            renderMessages(data.messages || []);
          })
          .catch(function (error) {
            console.error("Admin chat clear error:", error);
          });
        saveMessages([]);
      });

      hydrateHistory();
    })();
  </script>
{% endblock %}
