// ============ 1. WAIT FOR HTML TO BE READY ============ //
document.addEventListener("DOMContentLoaded", () => {

  // ============ GLOBAL STATE ============ //
  let currentDomain = "";
  let editingIndex = null;
  let currentUserId = null; // Stores the user's unique Google ID (data.sub)

  // ============ AUTHENTICATION SCREENS & ELEMENTS ============ //
  const loginScreen = document.getElementById("loginScreen");
  const mainAppScreen = document.getElementById("mainAppScreen");

  // --- Login Screen ---
  const loginButton = document.getElementById("loginButton");
  const authStatus = document.getElementById("authStatus");

  // --- Main App Screen ---
  const userEmail = document.getElementById("userEmail");
  const logoutButton = document.getElementById("logoutButton");

  // ============ APP ELEMENTS (Your existing) ============ //
  const credNameInput = document.getElementById("credName");
  const usernameInput = document.getElementById("username");
  const passwordInput = document.getElementById("password");
  const credNameError = document.getElementById("credNameError");
  const usernameError = document.getElementById("usernameError");
  const passwordError = document.getElementById("passwordError");
  const saveButton = document.getElementById("saveButton");
  const updateButton = document.getElementById("updateButton");
  const status = document.getElementById("status");
  const credList = document.getElementById("credList");
  const strengthIndicator = document.getElementById("strengthIndicator");
  const strengthLabel = document.getElementById("strengthLabel");
  const searchInput = document.getElementById("searchInput");
  const filterSelect = document.getElementById("filterSelect");
  const categorySelect = document.getElementById("categorySelect");
  const lengthError = document.getElementById("lengthError");
  const uppercaseError = document.getElementById("uppercaseError");
  const numberError = document.getElementById("numberError");
  const specialError = document.getElementById("specialError");
  const usernameInPasswordError = document.getElementById("usernameInPasswordError");
  const toggleTypingPassButton = document.getElementById("toggleTypingPass");

  // ============ 2. ATTACH ALL EVENT LISTENERS ============ //

  // --- Auth Listeners ---
 loginButton.addEventListener("click", () => {
  authStatus.textContent = "";
  chrome.identity.getAuthToken({ interactive: true }, (token) => {
    if (chrome.runtime.lastError || !token) {
      const err = chrome.runtime.lastError;
      const msg = err && err.message ? err.message : "No token returned";
      authStatus.textContent = `Login failed: ${msg}`;
      console.error("chrome.identity.getAuthToken error:", err);
      return;
    }
    handleAuthenticated(token);
  });
});

//settings button listener//
document.getElementById("settingsButton").addEventListener("click", () => {
  window.open("https://fortipass.com.my/pages/profile.html", "_blank");
});

  logoutButton.addEventListener("click", handleLogout);

  // --- App Listeners ---
  toggleTypingPassButton.addEventListener("click", (event) => {
    if (passwordInput.type === "password") {
      passwordInput.type = "text";
      event.target.textContent = "Hide";
    } else {
      passwordInput.type = "password";
      event.target.textContent = "Show";
    }
  });

  [credNameInput, usernameInput, passwordInput].forEach(input => {
    input.addEventListener("input", () => {
      updateStrengthUI(evaluateStrength(passwordInput.value));
      validateInputs();
    });
  });

  searchInput.addEventListener("input", loadCredentials);
  filterSelect.addEventListener("change", loadCredentials);
  saveButton.addEventListener("click", onSaveCredential);
  updateButton.addEventListener("click", onUpdateCredential);


  // ============ 3. AUTHENTICATION & ROUTING LOGIC ============ //

  // 3.1. Main entry point: Check if user is already logged in
  chrome.identity.getAuthToken({ interactive: false }, (token) => {
    console.debug('[Auth Debug] initial getAuthToken (non-interactive) callback, lastError:', chrome.runtime.lastError, 'token:', token);
    if (chrome.runtime.lastError || !token) {
      // Not logged in, show login screen
      console.log("Not logged in.");
      showScreen("login");
    } else {
      // Already logged in, start the auth flow
      console.log("Already logged in.");
      handleAuthenticated(token);
    }
  });

  // 3.2. Central function to handle a logged-in user
  function handleAuthenticated(token) {
  // Create a Google provider with custom parameters
  const provider = new firebase.auth.GoogleAuthProvider();
  provider.setCustomParameters({
    prompt: 'select_account'
  });

  // Build credential from Chrome token
  const credential = firebase.auth.GoogleAuthProvider.credential(null, token);

  // Sign in to Firebase with credential
  fb_auth.signInWithCredential(credential)
    .then((result) => {
      const user = result.user;
      currentUserId = user.uid;
      userEmail.textContent = user.email || "User";
      showScreen("main");
    })
    .catch((error) => {
      console.error("Firebase Auth Error:", error);
      handleLogout();
      authStatus.textContent = "Firebase login failed. Please try again.";
    });
}

  // 3.3. Central function to show the correct screen
  function showScreen(screenName) {
    // Hide all screens first
    loginScreen.style.display = "none";
    mainAppScreen.style.display = "none";

    // Show the requested one
    if (screenName === "login") {
      loginScreen.style.display = "block";
    } else if (screenName === "main") {
      mainAppScreen.style.display = "block";
      // ⭐️ This is the final step! Initialize the vault app.
      initializeAppLogic();
    }
  }

  // 3.4. Logout logic
  function handleLogout() {
  fb_auth.signOut().then(() => {
    console.log("Firebase user signed out.");
  });

  // Clear ALL cached tokens, not just the last one
  chrome.identity.clearAllCachedAuthTokens(() => {
    console.log("All cached tokens cleared.");
    currentUserId = null;
    showScreen("login");
  });
}

  // ============ 4. YOUR EXISTING APP LOGIC (Now secure) ============ //

  // This function is now called *only after* login is complete.
  function initializeAppLogic() {
    console.log("Initializing app for user:", currentUserId);
    
    // Get active tab's domain
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (chrome.runtime.lastError) {
        console.error("Error querying tabs:", chrome.runtime.lastError);
        return;
      }
      try {
        const url = new URL(tabs[0].url);
        currentDomain = url.hostname;
        loadCredentials();
      } catch (e) {
        currentDomain = "(Invalid URL)";
        console.error("Could not parse URL:", e);
      }
    });
    // Note: Listeners are already attached, so this function just loads data.
  }

  // 4.1. Load credentials *for the current user*
// 4.1. Load credentials *for the current user*
  function loadCredentials() {
    if (!currentUserId) return; // Jangan jalan kalau user ID takde

    // Rujukan kepada dokumen pengguna dalam Firestore
    const userCredsRef = fb_db.collection("credentials").doc(currentUserId);

    userCredsRef.get().then((doc) => {
      // Dapatkan 'all' map dari dokumen. Kalau takde, guna objek kosong.
      const all = (doc.exists && doc.data().all) ? doc.data().all : {};
      
      const allCreds = Object.values(all).flat();
      const searchTerm = searchInput.value.toLowerCase();
      const filter = filterSelect.value;
      
      const filteredCreds = allCreds.filter(cred => {
        const matchesSearch = cred.name.toLowerCase().includes(searchTerm) ||
                              cred.username.toLowerCase().includes(searchTerm);
        const matchesFilter = filter === "all" || cred.category === filter;
        return matchesSearch && matchesFilter;
      });

      credList.innerHTML = "";
      
      filteredCreds.forEach((cred, index) => {
        const wrapper = document.createElement("div");
        wrapper.className = "cred-entry";
        const domainForCred = Object.keys(all).find(key => all[key].some(c => c.name === cred.name && c.username === cred.username));
        const credIdentifier = c => c.name === cred.name && c.username === cred.username && c.password === cred.password;

        wrapper.innerHTML = `
          <strong>${cred.name}</strong><br>
          Username: ${cred.username}<br>
          Password: •••••••<br>
          <button data-use-index="${index}" data-domain="${domainForCred}">Use</button>
          <button data-edit-index="${index}" data-domain="${domainForCred}">Edit</button>
          <button data-delete-index="${index}" data-domain="${domainForCred}">Delete</button>
        `;

        // Listener untuk 'use' (tak berubah)
        wrapper.querySelector(`[data-use-index="${index}"]`).addEventListener("click", (e) => {
          useCredential(e.target.dataset.domain, cred.username, cred.password);
        });

        // Listener untuk 'edit' (tak berubah)
        wrapper.querySelector(`[data-edit-index="${index}"]`).addEventListener("click", (e) => {
          const domain = e.target.dataset.domain;
          const siteCreds = all[domain] || [];
          const credIndex = siteCreds.findIndex(credIdentifier);
          
          if (credIndex !== -1) {
            credNameInput.value = cred.name;
            usernameInput.value = cred.username;
            passwordInput.value = cred.password;
            categorySelect.value = cred.category || "all";
            editingIndex = credIndex;
            currentDomain = domain;
            updateStrengthUI(evaluateStrength(passwordInput.value));
            validateInputs();
            saveButton.style.display = "none";
            updateButton.style.display = "block";
          }
        });

        // Listener untuk 'delete' (DIUBAH UNTUK GUNA FIREBASE)
        wrapper.querySelector(`[data-delete-index="${index}"]`).addEventListener("click", (e) => {
          const domain = e.target.dataset.domain;
          const siteCreds = all[domain] || [];
          const credIndex = siteCreds.findIndex(credIdentifier);
          
          if (credIndex !== -1) {
            siteCreds.splice(credIndex, 1); // Buang dari array
            all[domain] = siteCreds; // Kemaskini 'all' map

            // ⭐️ FIREBASE: Update dokumen di server
            userCredsRef.set({ all: all }, { merge: true }) 
              .then(() => {
                loadCredentials(); // Muat semula senarai
              });
          }
        });
        credList.appendChild(wrapper);
      });
    });
  }

  // 4.2. Save new credential *for the current user*
// 4.2. Save new credential *for the current user*
  function onSaveCredential() {
    const name = credNameInput.value.trim();
    const username = usernameInput.value.trim();
    const password = passwordInput.value;

    validateInputs();
    if (saveButton.disabled) {
      status.textContent = "❌ Please fix errors above!";
      status.style.color = "red";
      return;
    }
    
    // Rujukan kepada dokumen pengguna
    const userCredsRef = fb_db.collection("credentials").doc(currentUserId);

    // 1. Dapatkan data sedia ada dulu
    userCredsRef.get().then((doc) => {
      const all = (doc.exists && doc.data().all) ? doc.data().all : {};
      const siteCreds = all[currentDomain] || [];
      const category = categorySelect.value;
      const newEntry = { name, username, password, category };

      siteCreds.unshift(newEntry);
      all[currentDomain] = siteCreds;
      
      // 2. Simpan (atau 'set') data baru. {merge: true} penting!
      userCredsRef.set({ all: all }, { merge: true })
        .then(() => {
          resetForm();
          loadCredentials();
          status.textContent = "✅ Saved!";
          status.style.color = "green";
        })
        .catch(err => {
          status.textContent = "❌ Save failed: " + err.message;
          status.style.color = "red";
        });
    });
  }

  // 4.3. Update existing credential *for the current user*
  function onUpdateCredential() {
    const name = credNameInput.value.trim();
    const username = usernameInput.value.trim();
    const password = passwordInput.value;
    
    validateInputs();
    if (updateButton.disabled) {
      status.textContent = "❌ Please fix errors above!";
      status.style.color = "red";
      return;
    }
    
    // Rujukan kepada dokumen pengguna
    const userCredsRef = fb_db.collection("credentials").doc(currentUserId);
    
    // 1. Dapatkan data sedia ada dulu
    userCredsRef.get().then((doc) => {
      const all = (doc.exists && doc.data().all) ? doc.data().all : {};
      const siteCreds = all[currentDomain] || [];
      const category = categorySelect.value;
      const newEntry = { name, username, password, category };
      
      if (editingIndex !== null) {
        siteCreds[editingIndex] = newEntry;
        editingIndex = null;
        updateButton.style.display = "none";
        saveButton.style.display = "block";
      }
      
      all[currentDomain] = siteCreds;
      
      // 2. Simpan (atau 'set') data yang dah update.
      userCredsRef.set({ all: all }, { merge: true })
        .then(() => {
          resetForm();
          loadCredentials();
          status.textContent = "✅ Updated!";
          status.style.color = "green";
        })
        .catch(err => {
          status.textContent = "❌ Update failed: " + err.message;
          status.style.color = "red";
        });
    });
  }

  // ============ 5. ALL YOUR OTHER HELPER FUNCTIONS (Unchanged) ============ //

  function useCredential(domain, username, password) {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (chrome.runtime.lastError) {
        console.error("Error querying tabs:", chrome.runtime.lastError);
        return;
      }
      const tabId = tabs[0].id;
      if (!tabId) return;

      chrome.scripting.executeScript({
        target: { tabId: tabId },
        func: (username, password) => {
          const userField = document.querySelector("input[type='text'], input[type='email']");
          const passField = document.querySelector("input[type='password']");
          if (userField) userField.value = username;
          if (passField) passField.value = password;
        },
        args: [username, password]
      }, () => {
        if (chrome.runtime.lastError) {
          console.error("Error executing script:", chrome.runtime.lastError);
          status.textContent = "❌ Failed to fill credentials!";
          status.style.color = "red";
        } else {
          status.textContent = "✅ Credentials filled!";
          status.style.color = "green";
        }
      });
    });
  }

  function resetForm() {
    credNameInput.value = "";
    usernameInput.value = "";
    passwordInput.value = "";
    categorySelect.value = "all";
    credNameError.style.display = "none";
    usernameError.style.display = "none";
    passwordError.style.display = "none";
    usernameInPasswordError.style.display = "none";
    saveButton.disabled = true;
    editingIndex = null;
    strengthLabel.textContent = "";
    strengthIndicator.style.backgroundColor = "lightgray";
    status.textContent = "";
    saveButton.style.display = "block";
    updateButton.style.display = "none";
    lengthError.style.display = "none";
    uppercaseError.style.display = "none";
    numberError.style.display = "none";
    specialError.style.display = "none";
  }

  function validateInputs() {
    const name = credNameInput.value.trim();
    const username = usernameInput.value.trim().toLowerCase();
    const password = passwordInput.value;
    const containsUsername = (username && password.toLowerCase().includes(username));
    const strength = evaluateStrength(password);
    const { length, uppercase, number, special } = strength.checks;

    let valid = true;
    if (!name) valid = false;
    if (!username) valid = false;
    if (!password) valid = false;

    credNameError.style.display = name ? "none" : "block";
    usernameError.style.display = username ? "none" : "block";
    passwordError.style.display = password ? "none" : "block";
    
    lengthError.style.display = length ? "none" : "block";
    uppercaseError.style.display = uppercase ? "none" : "block";
    numberError.style.display = number ? "none" : "block";
    specialError.style.display = special ? "none" : "block";

    const passwordValid = length && uppercase && number && special;

    if (containsUsername) {
      usernameInPasswordError.style.display = "block";
      valid = false;
    } else {
      usernameInPasswordError.style.display = "none";
    }

    if (!password) {
      status.textContent = "";
    } else if (containsUsername) {
      status.textContent = "❌ Password cannot contain username";
      status.style.color = "red";
      valid = false;
    } else if (!passwordValid) {
      status.textContent = "❌ Password does not meet requirements!";
      status.style.color = "red";
      valid = false;
    } else {
      status.textContent = "";
    }

    const buttonsEnabled = valid && passwordValid && !containsUsername;
    saveButton.disabled = !buttonsEnabled;
    updateButton.disabled = !buttonsEnabled;
  }

  function evaluateStrength(password) {
    const checks = {
      length: password.length >= 8,
      uppercase: /[A-Z]/.test(password),
      number: /[0-9]/.test(password),
      special: /[!@#$%^&*(),.?":{}|<>]/.test(password)
    };
    let score = 0;
    Object.values(checks).forEach(ok => ok && score++);
    return { score, checks };
  }

  function updateStrengthUI(strength) {
    strengthIndicator.classList.remove("strength-weak-bar", "strength-medium-bar", "strength-strong-bar");
    strengthLabel.classList.remove("strength-weak-text", "strength-medium-text", "strength-strong-text");

    if (passwordInput.value.length === 0) {
        strengthLabel.textContent = "";
        strengthIndicator.style.backgroundColor = "lightgray";
        return;
    }

    let label;
    if (strength.score === 4) {
      strengthIndicator.classList.add("strength-strong-bar");
      strengthLabel.classList.add("strength-strong-text");
      label = "Very Strong (All requirements met)";
    } else if (strength.score >= 2) {
      strengthIndicator.classList.add("strength-medium-bar");
      strengthLabel.classList.add("strength-medium-text");
      label = "Medium";
    } else {
      strengthIndicator.classList.add("strength-weak-bar");
      strengthLabel.classList.add("strength-weak-text");
      label = "Weak";
    }
    strengthLabel.textContent = label;
  }
}); // <-- This closes the DOMContentLoaded wrapper