// VERA Vault — Content Script
// Bridges communication between webpage (VERA Widget) and extension (Service Worker)
console.log("🛡️ VERA content script active on:", window.location.href);

// Announce extension presence to the page
window.postMessage({ source: "VERA_EXTENSION", type: "EXTENSION_READY" }, "*");

// Listen for messages from the webpage
window.addEventListener("message", (event) => {
  // Only accept messages from the same window
  if (event.source !== window) return;
  // Only accept messages from VERA widget
  if (!event.data || event.data.source !== "VERA_WIDGET") return;

  console.log("[VERA Content] Webpage → Extension:", event.data.type);

  // Forward to service worker
  chrome.runtime.sendMessage(event.data, (response) => {
    if (chrome.runtime.lastError) {
      console.error("[VERA Content] Extension error:", chrome.runtime.lastError.message);
      window.postMessage(
        {
          source: "VERA_EXTENSION",
          type: "ERROR",
          error: "Extension service worker not available. Try reloading the page.",
        },
        "*"
      );
      return;
    }

    console.log("[VERA Content] Extension → Webpage:", response?.type);

    // Send notification requests to the background service worker
    // (Notifications are displayed natively by Chrome, not injected into the page)
    if (response?.type === "CREDENTIAL_STORED") {
      chrome.runtime.sendMessage({
        source: "VERA_CONTENT",
        type: "SHOW_NOTIFICATION",
        title: "✅ Secure Credential Stored",
        message: "Your purchase receipt was successfully secured in your VERA Vault.",
      });
    } else if (response?.type === "PROOF_GENERATED") {
      chrome.runtime.sendMessage({
        source: "VERA_CONTENT",
        type: "SHOW_NOTIFICATION",
        title: "🔏 Verified Credential Created",
        message: "Your review has been cryptographically verified. Your identity remains fully protected.",
      });
    } else if (response?.type === "PROOF_ERROR" || response?.type === "STORE_ERROR") {
      chrome.runtime.sendMessage({
        source: "VERA_CONTENT",
        type: "SHOW_NOTIFICATION",
        title: "⚠️ VERA Vault Error",
        message: response.error || "An error occurred with your VERA Vault.",
        isError: true,
      });
    }

    window.postMessage({ source: "VERA_EXTENSION", ...response }, "*");
  });
});
