chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.action) {
    case "getEmailData":
      handleEmailQuery(request.query || "", sendResponse);
      return true;

    case "getEmailById":
      getEmailById(request.id, sendResponse);
      return true;

    case "openNewEntry":
      chrome.tabs.create({
        url: chrome.runtime.getURL("new_entry.html")
      });
      return true;

    case "sendEmail":
      sendEmail(request.payload, sendResponse);
      return true;

    case "saveDraft":
      saveDraft(request.payload, sendResponse);
      return true;

    case "loadLastDraft":
      loadLastDraft(sendResponse);
      return true;
  }
});

// ==== Fetch Emails ====
function handleEmailQuery(query, sendResponse) {
  getAuthToken()
    .then(token => {
      const base = "https://gmail.googleapis.com/gmail/v1/users/me/messages";
      const queryString = query
      ? `in:inbox -in:spam -in:sent ${query}`
      : "in:inbox -in:spam -in:sent";
    
    const url = `${base}?maxResults=10&q=${encodeURIComponent(queryString)}`;
    

      return fetch(url, {
        headers: { Authorization: `Bearer ${token}` }
      }).then(res => res.json());
    })
    .then(async data => {
      if (!data.messages?.length) return sendResponse({ emails: [] });

      const token = await getAuthToken();
      const details = await Promise.all(
        data.messages.map(msg =>
          fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${msg.id}`, {
            headers: { Authorization: `Bearer ${token}` }
          })
            .then(r => r.json())
            .then(full => ({
              id: full.id,
              subject: full.payload?.headers?.find(h => h.name === "Subject")?.value || "(No Subject)",
              sender: full.payload?.headers?.find(h => h.name === "From")?.value || "(Unknown Sender)"
            }))
        )
      );

      sendResponse({ emails: details });
    })
    .catch(err => {
      console.error("❌ Gmail query error:", err);
      sendResponse({ error: err.message });
    });
}

// ==== Send Email ====
function sendEmail({ to, subject, body }, sendResponse) {
  getAuthToken()
    .then(token => {
      if (!token) throw new Error("No OAuth token returned");

      console.log("Using OAuth token:", token);

      const message = [
        `Subject: ${subject}`,
        `To: ${to}`,
        "MIME-Version: 1.0",
        "Content-Type: text/plain; charset=utf-8",
        "",
        body
      ].join("\r\n");

      const encodedMessage = btoa(unescape(encodeURIComponent(message)))
        .replace(/\+/g, "-").replace(/\//g, "_");

      return fetch("https://gmail.googleapis.com/gmail/v1/users/me/messages/send", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ raw: encodedMessage })
      });
    })
    .then(async res => {
      const text = await res.text();
      let json;
      try {
        json = JSON.parse(text);
      } catch {
        throw new Error(`Invalid JSON from Gmail API: ${text}`);
      }

      if (!res.ok) throw new Error(json.error?.message || "Gmail API error");

      console.log("Email sent successfully:", json);
      sendResponse({ success: true, messageId: json.id });
    })
    .catch(err => {
      console.error("Failed to send email:", err);
      sendResponse({ error: err.message });
    });

  return true; // keep the message channel alive
}


// ==== Save Draft ====
function saveDraft({ to, subject, body }, sendResponse) {
  getAuthToken()
    .then(token => {
      const message = [
        `To: ${to}`,
        "Content-Type: text/plain; charset=utf-8",
        "MIME-Version: 1.0",
        `Subject: ${subject}`,
        "",
        body
      ].join("\n");

      const encodedMessage = btoa(unescape(encodeURIComponent(message))).replace(/\+/g, "-").replace(/\//g, "_");

      return fetch("https://gmail.googleapis.com/gmail/v1/users/me/drafts", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ message: { raw: encodedMessage } })
      });
    })
    .then(res => res.json())
    .then(data => {
      console.log("✅ Draft saved:", data);
      sendResponse({ success: true, draftId: data.id });
    })
    .catch(err => {
      console.error("❌ Failed to save draft:", err);
      sendResponse({ error: err.message });
    });
}

// ==== Load Last Draft (first from list) ====
function loadLastDraft(sendResponse) {
  getAuthToken()
    .then(token => {
      return fetch("https://gmail.googleapis.com/gmail/v1/users/me/drafts?maxResults=1", {
        headers: { Authorization: `Bearer ${token}` }
      }).then(res => res.json());
    })
    .then(data => {
      const draft = data.drafts?.[0];
      if (!draft) return sendResponse({ error: "No drafts found." });

      getAuthToken().then(token =>
        fetch(`https://gmail.googleapis.com/gmail/v1/users/me/drafts/${draft.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
          .then(res => res.json())
          .then(full => {
            const headers = full.message.payload.headers;
            const subject = headers.find(h => h.name === "Subject")?.value || "";
            const to = headers.find(h => h.name === "To")?.value || "";
            const body = atob(full.message.raw).split("\r\n\r\n").pop();
            sendResponse({ subject, to, body });
          })
      );
    })
    .catch(err => {
      console.error("Failed to load draft:", err);
      sendResponse({ error: err.message });
    });

  return true;
}

// ==== OAuth Helper ====
function getAuthToken() {
  return new Promise((resolve, reject) => {
    chrome.identity.getAuthToken({ interactive: true }, token => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else {
        resolve(token);
      }
    });
  });
}


// ==== Get Email by ID  ====
function getEmailById(id, sendResponse) {
  getAuthToken()
    .then(token =>
      fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${id}`, {
        headers: { Authorization: `Bearer ${token}` }
      }).then(res => res.json())
    )
    .then(data => {
      const headers = data.payload.headers;
      const subject = headers.find(h => h.name === "Subject")?.value || "(No Subject)";
      const from = headers.find(h => h.name === "From")?.value || "(Unknown Sender)";
      const body = getPlainTextFromPayload(data.payload);
      sendResponse({ email: { subject, from, body } });
    })
    .catch(err => {
      console.error(" Failed to load email:", err);
      sendResponse({ error: err.message });
    });
}

function getPlainTextFromPayload(payload) {
  if (payload.parts) {
    const part = payload.parts.find(p => p.mimeType === "text/plain");
    if (part?.body?.data) {
      return atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));
    }
  }
  if (payload.body?.data) {
    return atob(payload.body.data.replace(/-/g, '+').replace(/_/g, '/'));
  }
  return "(No content found)";
}

