let latestDraftId = null;

function base64Encode(str) {
  return btoa(unescape(encodeURIComponent(str)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

// 🟢 Load last Fallout draft
function loadLastDraft() {
  chrome.identity.getAuthToken({ interactive: true }, (token) => {
    fetch("https://gmail.googleapis.com/gmail/v1/users/me/drafts", {
      headers: { Authorization: `Bearer ${token}` }
    })
      .then(res => res.json())
      .then(data => {
        const falloutDraft = data.drafts?.find(draft =>
          draft?.message?.payload?.headers?.some(
            header => header.name === "Subject" && header.value.includes("FalloutEntry")
          )
        );

        if (falloutDraft) {
          latestDraftId = falloutDraft.id;

          // Fetch full content
          return fetch(`https://gmail.googleapis.com/gmail/v1/users/me/drafts/${latestDraftId}`, {
            headers: { Authorization: `Bearer ${token}` }
          });
        }
      })
      .then(res => res?.json())
      .then(draftData => {
        const headers = draftData.message.payload.headers.reduce((acc, h) => {
          acc[h.name.toLowerCase()] = h.value;
          return acc;
        }, {});
        const body = atob(draftData.message.payload.body.data.replace(/-/g, '+').replace(/_/g, '/'));

        document.querySelector('[name="to"]').value = headers.to || '';
        document.querySelector('[name="subject"]').value = headers.subject || '';
        document.querySelector('[name="body"]').value = body || '';
      })
      .catch(console.error);
  });
}

// 🟢 Save or update Gmail draft
function saveDraft(to, subject, body) {
  chrome.identity.getAuthToken({ interactive: true }, (token) => {
    const email =
      `To: ${to}\r\n` +
      `Subject: ${subject}\r\n` +
      "Content-Type: text/plain; charset=utf-8\r\n" +
      "\r\n" +
      body;

    const raw = base64Encode(email);

    const draftData = {
      message: {
        raw: raw
      }
    };

    const url = latestDraftId
      ? `https://gmail.googleapis.com/gmail/v1/users/me/drafts/${latestDraftId}`
      : `https://gmail.googleapis.com/gmail/v1/users/me/drafts`;

    fetch(url, {
      method: latestDraftId ? "PUT" : "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify(draftData)
    })
      .then(res => res.json())
      .then(data => {
        latestDraftId = data.id;
      })
      .catch(console.error);
  });
}

// Send email
function sendEmail(to, subject, body) {
  chrome.runtime.sendMessage({
    action: "sendEmail",
    payload: { to, subject, body }
  }, (response) => {
    if (response?.success) {
      alert("Entry sent successfully.");
      latestDraftId = null;
      chrome.tabs.update({ url: "https://mail.google.com/mail/u/0/#inbox" });
    } else {
      console.error("Failed to send email:", response?.error);
      alert("Error sending email.");
    }
  });
}


// 🟢 Hook everything up
document.addEventListener("DOMContentLoaded", () => {
  loadLastDraft();

  const form = document.getElementById("email-form");

  form.addEventListener("input", () => {
    const to = form.to.value;
    const subject = form.subject.value || "FalloutEntry";
    const body = form.body.value;
    if (to || subject || body) {
      saveDraft(to, subject, body);
    }
  });

  form.addEventListener("submit", (e) => {
    e.preventDefault();
    sendEmail(form.to.value, form.subject.value, form.body.value);
  });
});
