// === Gmail Terminal UI Extension ===

// ==== Load VT323 Font ====
const font = document.createElement("link");
font.href = "https://fonts.googleapis.com/css2?family=VT323&display=swap";
font.rel = "stylesheet";
document.head.appendChild(font);

// ==== Boot-up Animation ====
const bootupScreen = document.createElement("div");
bootupScreen.id = "bootup-screen";
document.body.appendChild(bootupScreen);

const bootupStyle = document.createElement("link");
bootupStyle.rel = "stylesheet";
bootupStyle.href = chrome.runtime.getURL("css/bootup.css");
document.head.appendChild(bootupStyle);

setTimeout(() => {
  bootupScreen.classList.add("fade-out");
  setTimeout(() => bootupScreen.remove(), 1000);
}, 2000);

// ==== Wait for Element Utility ====
function waitForElement(selector, callback) {
  const el = document.querySelector(selector);
  if (el) return callback(el);

  const observer = new MutationObserver(() => {
    const match = document.querySelector(selector);
    if (match) {
      observer.disconnect();
      callback(match);
    }
  });

  observer.observe(document.body, { childList: true, subtree: true });
}

// ==== View Helpers ====
function isInboxListView() {
  return window.location.hash === "#inbox";
}

function isVaultLogView() {
  return /^#vaultlog\/[a-zA-Z0-9_-]+$/.test(window.location.hash);
}

function getVaultLogId() {
  const match = window.location.hash.match(/^#vaultlog\/([a-zA-Z0-9_-]+)$/);
  return match?.[1];
}

// ==== Load View Styles ====
function applyViewStyles() {
  document.querySelectorAll('link[data-custom-style]').forEach(el => el.remove());

  const stylesheet = document.createElement("link");
  stylesheet.rel = "stylesheet";
  stylesheet.dataset.customStyle = "true";
  try {
    const view = isVaultLogView() ? "email-view.css" : "inbox.css";
    stylesheet.href = chrome.runtime.getURL(`css/${view}`);
    document.head.appendChild(stylesheet);
  } catch (err) {
    console.error("Failed to apply view styles:", err);
  }
}

// ==== Terminal Header ====
function injectTerminalHeader() {
  if (document.getElementById("terminal-header")) return;

  const header = document.createElement("div");
  header.id = "terminal-header";
  header.innerHTML = `
    <div id="robco-header">
<pre>
ROBCO INDUSTRIES UNIFIED OPERATING SYSTEM
COPYRIGHT 2075-2077 ROBCO INDUSTRIES
-Server 76-

====================================================
</pre>
    </div>
    <div class="terminal-bar">
      <span class="prompt">>> Search Logs:</span>
      <input type="text" id="log-search" placeholder="from:Overseer subject:'Surface Never, Fault Forever!'" autocomplete="off" />
      <button id="new-entry-btn">>> New Entry</button>
      <button id="back-to-inbox-btn"><< Back to Inbox</button>
    </div>
  `;
  document.body.prepend(header);

  waitForElement("#new-entry-btn", (btn) => {
    btn.addEventListener("click", () => {
      chrome.runtime.sendMessage({ action: "openNewEntry" });
    });
  });

  waitForElement("#back-to-inbox-btn", (btn) => {
    btn.addEventListener("click", () => {
      window.location.hash = "#inbox";
    });
  });

  waitForElement("#log-search", (input) => {
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        const query = e.target.value;
        if (query) fetchAndRenderEmails(query);
      }
    });
  });
}

// ==== Render Email List ====
function renderEmailLayout(emails) {
  const old = document.getElementById("custom-email-cards");
  if (old) old.remove();

  const container = document.createElement("div");
  container.id = "custom-email-cards";
  container.style.position = "relative";
  container.style.zIndex = "9999";
  container.style.marginTop = "20px";
  container.style.padding = "0 20px";

  if (!emails?.length) {
    container.innerHTML = `<div class="email-card"><h3>> No logs found or Gmail API failed.</h3></div>`;
  } else {
    emails.forEach(email => {
      const card = document.createElement("div");
      card.className = "email-card";
      card.innerHTML = `<h3>> ${email.subject} from ${email.sender}</h3>`;
      card.onclick = () => {
        window.location.hash = `#vaultlog/${email.id}`;
      };
      container.appendChild(card);
    });
  }

  const header = document.getElementById("terminal-header");
  if (header) header.insertAdjacentElement("afterend", container);
  else document.body.appendChild(container);
}

// ==== Render Single Email ====
function renderSingleEmail({ subject, from, body }) {
  document.querySelector("#custom-email-cards")?.remove();
  document.querySelector("#vaultlog-email")?.remove();

  const view = document.createElement("div");
  view.id = "vaultlog-email";
  view.style.padding = "20px";
  view.style.color = "#00ff66";
  view.innerHTML = `
    <div class="email-card large">
      <h2>> ${subject}</h2>
      <p><strong>From:</strong> ${from}</p>
      <pre>${body}</pre>
    </div>
  `;

  const header = document.getElementById("terminal-header");
  if (header) header.insertAdjacentElement("afterend", view);
  else document.body.appendChild(view);
}

function renderSingleEmailError(message) {
  renderSingleEmail({ subject: "Error", from: "System", body: message });
}

// ==== Fetch from Background ==== 
function fetchAndRenderEmails(query = "") {
  chrome.runtime.sendMessage({ action: "getEmailData", query }, (res) => {
    renderEmailLayout(res?.emails || []);
  });
}

function fetchAndRenderEmailById(id) {
  chrome.runtime.sendMessage({ action: "getEmailById", id }, (res) => {
    if (res?.error) renderSingleEmailError(res.error);
    else renderSingleEmail(res.email);
  });
}

// ==== SPA Monitor ==== 
let lastUrl = "";
setInterval(() => {
  const url = window.location.href;
  if (url !== lastUrl) {
    lastUrl = url;
    applyViewStyles();
    injectTerminalHeader();
    if (isInboxListView()) fetchAndRenderEmails();
    else if (isVaultLogView()) {
      const id = getVaultLogId();
      if (id) fetchAndRenderEmailById(id);
    }
  }
}, 1000);

// ==== Initial Load ==== 
applyViewStyles();
if (isInboxListView()) {
  injectTerminalHeader();
  fetchAndRenderEmails();
} else if (isVaultLogView()) {
  injectTerminalHeader();
  const id = getVaultLogId();
  if (id) fetchAndRenderEmailById(id);
}