let selectedMonday;

Object.defineProperty(window, "selectedMonday", {
  set(value) {
    console.trace("TRACE: selectedMonday changed to:", value.toISOString().split("T")[0]);
    this._selectedMonday = value;
  },
  get() {
    return this._selectedMonday;
  }
});

const byId = (id) => document.getElementById(id);
const uid = () => Math.random().toString(36).slice(2);

let state = { users: [] }; // fetched from PHP
let expandedUsers = new Set(); // Track which user sections are expanded

const countryTimezones = {
  "Nigeria": "Africa/Lagos",
  "Romania": "Europe/Bucharest",
  "USA": "America/New_York", // you can adjust to preferred US timezone
  "UK": "Europe/London",
  "India": "Asia/Kolkata",
  "Thailand": "Asia/Bangkok",
  "Egypt": "Africa/Cairo",
  "UAE": "Asia/Dubai",
    "Australia": "Australia/Sydney" // ✅ Added Australia
};

const usersContainer = byId("usersContainer");
const userRowTpl = byId("userRowTpl");
const accountItemTpl = byId("accountItemTpl");
const searchBox = byId("searchBox");

const dayNames = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

// --- Load state from PHP ---
async function loadStateFromServer() {
  const res = await fetch("backend.php?action=load");
  state = await res.json();
  render();
}

// --- Save state to PHP ---
async function saveStateToServer() {
  await fetch("backend.php?action=save", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(state)
  });
}

// --- Render UI ---
async function render(filter = "") {
  usersContainer.innerHTML = "";
  const q = filter.trim().toLowerCase();

  // ✅ Fetch results ONCE from backend.php
const resultsMap = state.results || {};

  state.users.forEach((user) => {
    const userNameMatch = user.name.toLowerCase().includes(q);
    const accountsMatch = user.accounts.some((a) => a.name.toLowerCase().includes(q));
    if (q && !(userNameMatch || accountsMatch)) return;

    const node = userRowTpl.content.cloneNode(true);
    const row = node.querySelector("div.border");
    const nameEl = row.querySelector(".userName");
    const countEl = row.querySelector(".accountsCount");
    const accountsWrap = row.querySelector(".accounts");
    const ul = accountsWrap.querySelector("ul");

nameEl.textContent = user.name;
countEl.textContent = `(${user.accounts.length} accounts)`;

// --- Create Country Selector for User ---
const countrySelect = document.createElement("select");
countrySelect.className = "rounded-lg border border-gray-300 px-2 py-1 text-sm ml-2";
countrySelect.innerHTML = `
  <option value="Nigeria">Nigeria</option>
  <option value="Romania">Romania</option>
  <option value="USA">USA</option>
  <option value="UK">UK</option>
  <option value="India">India</option>
  <option value="Thailand">Thailand</option>
  <option value="Egypt">Egypt</option>
  <option value="UAE">UAE</option>
    <option value="Australia">Australia</option> <!-- ✅ Add this line -->
`;

// Default to Nigeria if country not set
countrySelect.value = user.country || "Nigeria";

// Save when changed
countrySelect.addEventListener("change", async (e) => {
  user.country = e.target.value;
  await saveStateToServer();

  // ✅ Automatically refresh yellow/grey statuses for this user
  await updateYellowDays(user);

  console.log(`Country changed to ${user.country} for user ${user.name}. Status refreshed.`);
});

// --- Wrap Country Selector and Refresh Button ---
const wrapper = document.createElement("div");
wrapper.style.display = "flex";
wrapper.style.alignItems = "center";
wrapper.style.gap = "8px";

// Create refresh button
const refreshBtn = document.createElement("button");
refreshBtn.innerHTML = "⟳"; // refresh symbol
refreshBtn.title = "Refresh days";
refreshBtn.className = "px-2 py-0 border rounded text-gray-600 hover:bg-gray-200";

// When clicked, only refresh this user's yellow/grey statuses
refreshBtn.addEventListener("click", async () => {
  await updateYellowDays(user); // Pass only this user
  console.log(`Manual refresh done for ${user.name}`);
});

// Add both to wrapper
wrapper.appendChild(countrySelect);
wrapper.appendChild(refreshBtn);

// Place wrapper after account count
countEl.after(wrapper);


    // --- Toggle expand/collapse via arrow button ---
    const toggleBtn = row.querySelector(".toggleBtn");
    toggleBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      accountsWrap.classList.toggle("hidden");

      if (accountsWrap.classList.contains("hidden")) {
        expandedUsers.delete(user.name); // collapsed
      } else {
        expandedUsers.add(user.name); // expanded
      }
      toggleBtn.textContent = accountsWrap.classList.contains("hidden") ? "▸" : "▾";
    });

    // Restore expanded state
    if (expandedUsers.has(user.name)) {
      accountsWrap.classList.remove("hidden");
      toggleBtn.textContent = "▾";
    } else {
      accountsWrap.classList.add("hidden");
      toggleBtn.textContent = "▸";
    }

    // --- Add Account ---
    const accountInput = row.querySelector(".accountInput");
row.querySelector(".addAccountBtn").addEventListener("click", async () => {
  let accountName = accountInput.value.trim();
  if (!accountName) {
    accountName = prompt("New account name:");
    if (!accountName) return;
  }

  // Prevent duplicate account names under same user
  if (user.accounts.some(a => a.name.toLowerCase() === accountName.toLowerCase())) {
    alert("Account already exists for this user.");
    return;
  }

  // --- STEP 1: Get currently selected week ---
  console.log("DEBUG Selected Monday when adding account:", selectedMonday.toISOString().split("T")[0]); // <-- Add here

  const weekFolderName = "week-" + formatDate(selectedMonday).replace(" ", "-").toLowerCase();
  const weekKey = selectedMonday.toISOString().split("T")[0];

  // --- STEP 2: Ensure correct folder structure exists on the server ---
  try {
    const resp = await fetch("backend.php?action=checkAndCreateFolders", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        user: user.name,
        weekFolder: weekFolderName,
        account: accountName,
        day: "Monday" // placeholder to ensure all weekdays are generated
      })
    });
    const data = await resp.json();
    if (!data.success) {
      alert(`❌ Failed to create folder structure: ${data.error}`);
      return;
    }
    console.log(`📂 Verified folder structure for ${user.name}/${weekFolderName}/${accountName}`);
  } catch (err) {
    console.error("❌ Error creating folder structure:", err);
    alert("Server error when creating folders. Check console for details.");
    return;
  }

  // --- STEP 3: Prepare 7 days for the selected week ---
  const timezone = countryTimezones[user.country] || "UTC";
  const nowUtc = new Date();

  const nowInCountry = new Date(
    new Intl.DateTimeFormat("en-US", {
      timeZone: timezone,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false
    }).format(nowUtc)
  );

  const daysInit = {};
  for (let i = 1; i <= 7; i++) {
    const dayDate = new Date(selectedMonday);
    dayDate.setDate(selectedMonday.getDate() + (i - 1));

    const dayStartInCountry = new Date(
      new Intl.DateTimeFormat("en-US", {
        timeZone: timezone,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false
      }).format(new Date(`${dayDate.toISOString().split("T")[0]}T00:00:00Z`))
    );

    const status = nowInCountry < dayStartInCountry ? "yellow" : "grey";
    daysInit[i] = { status, date: dayDate.toISOString().split("T")[0] };
  }

  // --- STEP 4: Save to stored.txt ---
  user.accounts.push({
    id: uid(),
    name: accountName,
    weeks: { [weekKey]: daysInit }
  });

  await saveStateToServer();

  // Immediately run yellow/grey verification
  await updateYellowDays(user);

  render(searchBox.value);

  // Keep user section expanded
  if (expandedUsers.has(user.name)) {
    accountsWrap.classList.remove("hidden");
    toggleBtn.textContent = "▾";
  }

  console.log(`✅ Account "${accountName}" added under week "${weekFolderName}"`);
});


    // --- Rename User ---
row.querySelector(".renameUserBtn").addEventListener("click", async (e) => {
  e.stopPropagation(); // ✅ Now e is defined
  const newName = prompt("Rename user:", user.name);
  if (!newName || newName.trim() === user.name) return;
  if (state.users.some((u) => u !== user && u.name.toLowerCase() === newName.toLowerCase())) {
    alert("Another user already has that name.");
    return;
  }
  user.name = newName.trim();
  await saveStateToServer();
  render(q);
});

    // --- Delete User ---
row.querySelector(".deleteUserBtn").addEventListener("click", async (e) => {
  e.stopPropagation(); // ✅ Now e is defined
  if (!confirm(`Delete user "${user.name}" and ALL its accounts?`)) return;
  state.users = state.users.filter((u) => u !== user);
  await saveStateToServer();
  render(q);
});

    // --- Render Accounts for this User ---
    user.accounts.forEach((account) => {
      if (q && !user.name.toLowerCase().includes(q) && !account.name.toLowerCase().includes(q)) return;

      const item = accountItemTpl.content.cloneNode(true);
// --- Account Name
item.querySelector(".accountName").textContent = account.name;


      const dayBoxes = item.querySelectorAll(".day-box");
      const weekKey = selectedMonday.toISOString().split("T")[0];
      
       // === Account Edit Button ===
  item.querySelector(".renameAccountBtn").addEventListener("click", async (e) => {
    e.stopPropagation(); // Prevent conflict with day-box clicks
    const newName = prompt("Rename account:", account.name);
    if (!newName || newName.trim() === account.name) return;

    // Check if another account already has this name
    if (user.accounts.some((a) => a !== account && a.name.toLowerCase() === newName.toLowerCase())) {
      alert("Another account already has that name.");
      return;
    }

    account.name = newName.trim();
    await saveStateToServer();
    render(q);
  });

  // === Account Delete Button ===
  item.querySelector(".deleteAccountBtn").addEventListener("click", async (e) => {
    e.stopPropagation(); // Prevent conflict with day-box clicks
    if (!confirm(`Delete account "${account.name}"?`)) return;

    // Remove account from the list
    user.accounts = user.accounts.filter((a) => a !== account);
    await saveStateToServer();
    render(q);
  });

      
        // Auto-fill missing days for existing accounts
if (!account.weeks) account.weeks = {};
if (!account.weeks[weekKey]) {
  console.warn(`Week ${weekKey} does not exist for account ${account.name}. Skipping creation.`);
    account.weeks[weekKey] = {};
}

  for (let i = 1; i <= 7; i++) {
    if (!account.weeks[weekKey][i]) {
      const dayDate = new Date(selectedMonday);
      dayDate.setDate(selectedMonday.getDate() + (i - 1));
      const formattedDate = dayDate.toISOString().split("T")[0];

      account.weeks[weekKey][i] = { status: "grey", date: formattedDate };
    }
  }


      dayBoxes.forEach((box) => {
        const dayIndex = parseInt(box.dataset.day);

        // ✅ Use resultsMap instead of stored.txt
// ✅ Use resultsMap instead of stored.txt
// ✅ Use resultsMap instead of stored.txt
const weekResults = resultsMap?.[user.name]?.[account.name]?.[weekKey];

if (weekResults && weekResults[dayIndex]) {
  // --- Case: this day has analysis results
  const resultObj = weekResults[dayIndex];

  if (typeof resultObj === "object") {
    const savedDate = new Date(resultObj.date);
    const shortDay = savedDate.toLocaleDateString("en-US", { weekday: "short" }); // Wed
    const dayNum = savedDate.getDate(); // 17
    box.setAttribute("data-tooltip", `${shortDay} ${dayNum}: ${resultObj.result}`);
  } else {
    box.setAttribute("data-tooltip", resultObj);
  }
} else {
  // --- Case: no results yet -> check status
  const currentDayData = account.weeks?.[weekKey]?.[dayIndex];
  if (currentDayData) {
    const savedDate = new Date(currentDayData.date);
    const shortDay = savedDate.toLocaleDateString("en-US", { weekday: "short" });
    const dayNum = savedDate.getDate();

    if (currentDayData.status === "grey") {
      box.setAttribute("data-tooltip", `${shortDay} ${dayNum}: not analysed`);
    } else if (currentDayData.status === "yellow") {
      box.setAttribute("data-tooltip", `${shortDay} ${dayNum}: Day not started`);
    } else {
      box.removeAttribute("data-tooltip");
    }
  } else {
    box.removeAttribute("data-tooltip");
  }
}




        // Keep green color
if (account.weeks && account.weeks[weekKey] && account.weeks[weekKey][dayIndex]) {
  const status = account.weeks[weekKey][dayIndex].status;

  if (account.weeks && account.weeks[weekKey] && account.weeks[weekKey][dayIndex]) {
    const status = account.weeks[weekKey][dayIndex].status;


const dateObj = new Date(account.weeks[weekKey][dayIndex].date);

const formattedDate = dateObj.toLocaleDateString("en-US", { weekday: "short" }) + " " + dateObj.getDate();




if (status === "green") {
  box.classList.add("bg-green-500");

  // ✅ Try to get actual result from state.results
  const dayResult = resultsMap?.[user.name]?.[account.name]?.[weekKey]?.[dayIndex];

  if (dayResult && dayResult.result) {
    // Example: "5 from 8 were posted"
    box.setAttribute("data-tooltip", `${formattedDate}: ${dayResult.result}`);
  } else {
    // Fallback if no result found
    box.setAttribute("data-tooltip", `${formattedDate}: All captions posted`);
  }
} else if (status === "red") {
  box.classList.add("bg-red-500");
  box.classList.remove("hover:bg-gray-300");
  box.setAttribute("data-tooltip", `${formattedDate}: Missing captions`);
} else if (status === "orange") {
  box.classList.add("bg-orange-400");
  box.classList.remove("hover:bg-gray-300");
  box.setAttribute("data-tooltip", `${formattedDate}: captions_log.txt missing`);
} else if (status === "grey") {
  // Grey boxes should keep hover effect
  box.classList.add("bg-gray-300", "hover:bg-gray-300", "transition-none", "pointer-events-auto");
  box.setAttribute("data-tooltip", `${formattedDate}: Not analysed`);
} else if (status === "yellow") {
  // Yellow boxes must NEVER have hover:bg-gray-300
  box.classList.add("bg-yellow-400");
  box.classList.remove("hover:bg-gray-300", "bg-gray-300");
  box.style.backgroundColor = ""; // Ensure no inline override
  box.setAttribute("data-tooltip", `${formattedDate}: Day not started`);
}



  }

}

        // On click
box.addEventListener("click", (e) => {
  e.stopPropagation();

  const clickedDate = new Date(selectedMonday);
  clickedDate.setDate(clickedDate.getDate() + (dayIndex - 1));

  const weekKey = selectedMonday.toISOString().split("T")[0];
  const dayData = account.weeks?.[weekKey]?.[dayIndex];

  // ✅ Check if this day is marked as yellow
  if (dayData?.status === "yellow") {
    const dayName = dayNames[dayIndex - 1];
    alert(`❌ Cannot scrape for ${dayName} (${dayData.date}).\nThe day has NOT started yet in ${user.country}.`);
    console.warn(`Blocked scraping attempt: Day ${dayData.date} is yellow for ${user.country}`);
    return; // Stop further execution
  }

  // ✅ If not yellow, proceed normally
  checkCaptionsForDay(user.name, account.name, dayIndex, clickedDate);
});

      });

      ul.appendChild(item);
    });

    usersContainer.appendChild(node);
  });
}

function updateDayBoxUI(userName, accountName, dayIndex, colorClass, tooltipText) {
  document.querySelectorAll(`.day-box[data-day="${dayIndex}"]`).forEach((box) => {
    const accEl = box.closest(".account-item");
    const usrEl = box.closest(".user-card");
    if (!accEl || !usrEl) return;

    // Make sure it's the correct account and user
    if (accEl.querySelector(".accountName")?.textContent !== accountName) return;
    if (usrEl.querySelector(".userName")?.textContent !== userName) return;

    // 🧹 Remove ALL old colors and inline styles
box.classList.remove(
  "bg-green-500",
  "bg-red-500",
  "bg-orange-400",
  "bg-gray-300",
  "bg-yellow-400",
  "hover:bg-gray-300"
);

    box.style.backgroundColor = ""; // remove inline grey/yellow overrides

    // 🆕 Apply the new color
    if (colorClass) {
      box.classList.add(colorClass);
    }

    // ✏️ Update tooltip
    if (tooltipText) {
      box.setAttribute("data-tooltip", tooltipText);
    } else {
      box.removeAttribute("data-tooltip");
    }
  });
}

// --- Add New User ---
byId("addUserBtn").addEventListener("click", async () => {
  const input = byId("userName");
  const name = input.value.trim();
  if (!name) return alert("Please enter a user name.");

  // Prevent duplicate usernames
  if (state.users.some((u) => u.name.toLowerCase() === name.toLowerCase())) {
    return alert("User already exists.");
  }

  // Get the currently selected week
  const weekFolderName = "week-" + formatDate(selectedMonday).replace(" ", "-").toLowerCase();

  // --- Step 1: Create user object in state
  const newUser = { id: uid(), name, country: "Nigeria", accounts: [] };
  state.users.push(newUser);

  // --- Step 2: Save state to store.txt
  await saveStateToServer();

  // --- Step 3: Create week folder on the server
  try {
    const resp = await fetch("backend.php?action=createWeekFolder", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        user: newUser.name,
        weekFolder: weekFolderName
      })
    });
    const data = await resp.json();
    console.log(`📂 Week folder created for new user "${newUser.name}":`, data);
  } catch (err) {
    console.error(`❌ Failed to create week folder for user ${newUser.name}`, err);
  }

  // --- Step 4: Clear input and re-render
  input.value = "";
  render(searchBox.value);
});

// --- Search ---
searchBox.addEventListener("input", (e) => render(e.target.value));

// --- Initial Load ---
loadStateFromServer();

// Run immediately once on load
updateYellowDays();

// Then run every 10 minutes
setInterval(updateYellowDays, 10 * 60 * 1000);

// --- Week Selector Logic ---
const weekBtn = document.getElementById("weekSelectorBtn");
const weekPicker = document.getElementById("weekPicker");

function formatDate(date) {
  return date.toLocaleDateString("en-US", { 
    day: "numeric", 
    month: "short", 
    timeZone: "UTC"   // ✅ Force UTC to avoid timezone shifting
  });
}

function getCurrentMonday() {
  const now = new Date();

  // Get current UTC date
  const utcYear = now.getUTCFullYear();
  const utcMonth = now.getUTCMonth();
  const utcDate = now.getUTCDate();

  const todayUTC = new Date(Date.UTC(utcYear, utcMonth, utcDate));

  const day = todayUTC.getUTCDay(); // 0 = Sunday, 1 = Monday
  const mondayOffset = (day + 6) % 7; // Make Monday the start
  todayUTC.setUTCDate(todayUTC.getUTCDate() - mondayOffset);

  return todayUTC;
}

console.log("TEST Monday:", getCurrentMonday().toISOString().split("T")[0]);

selectedMonday = getCurrentMonday(); // no 'let'!
function updateWeekButtonText(date) {
  weekBtn.textContent = `Week ${formatDate(date)}`;
}
updateWeekButtonText(selectedMonday);

weekBtn.addEventListener("click", () => weekPicker.showPicker());

// --- Create week folder for each user ---
async function createWeekFolders(weekKey) {
  const weekFolderName = "week-" + formatDate(selectedMonday).replace(" ", "-").toLowerCase();

  for (const user of state.users) {
    try {
      await fetch("backend.php?action=createWeekFolder", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          user: user.name,
          weekFolder: weekFolderName
        })
      });
      console.log(`📂 Week folder created for user ${user.name}: ${weekFolderName}`);
    } catch (err) {
      console.error("Failed to create week folder for", user.name, err);
    }
  }
}

weekPicker.addEventListener("change", async (e) => {
  // Parse the input YYYY-MM-DD yourself and build a UTC date
  const [y, m, d] = e.target.value.split("-").map(Number);
  const pickedUTC = new Date(Date.UTC(y, m - 1, d)); // midnight UTC

  // Compute Monday in UTC
  const day = pickedUTC.getUTCDay();            // 0=Sun, 1=Mon, ... 6=Sat
  const mondayOffset = (day + 6) % 7;           // days to subtract to reach Monday
  pickedUTC.setUTCDate(pickedUTC.getUTCDate() - mondayOffset);

  // This is your canonical Monday
  selectedMonday = pickedUTC;

  console.log("DEBUG - Picker raw date:", e.target.value);
  console.log("DEBUG - Calculated Monday (UTC):", selectedMonday.toISOString().split("T")[0]);

  console.log(`📆 Switched to week starting ${selectedMonday.toISOString().split("T")[0]}`);
  updateWeekButtonText(selectedMonday);

  // --- STEP 1: Update only yellow/grey statuses (NO folder creation, NO stored.txt ghost weeks)
  const weekKey = selectedMonday.toISOString().split("T")[0];

  state.users.forEach(user => {
    const timezone = countryTimezones[user.country] || "UTC";
    const nowUtc = new Date();

    const nowInCountry = new Date(
      new Intl.DateTimeFormat("en-US", {
        timeZone: timezone,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false
      }).format(nowUtc)
    );
    

    user.accounts.forEach(account => {
      if (!account.weeks) account.weeks = {};

if (!account.weeks[weekKey]) {
  // ✅ Only create an empty week if it truly doesn't exist
  console.log(`⚠️ Week ${weekKey} not found for account "${account.name}". Creating a NEW week...`);
  account.weeks[weekKey] = {};
} else {
  console.log(`📂 Week ${weekKey} already exists for account "${account.name}". Loading saved data.`);
}


      console.log(`🔄 Updating yellow/grey statuses for week ${weekKey}, account "${account.name}"`);

for (let i = 1; i <= 7; i++) {
  const dayDateUTC = new Date(selectedMonday);      // clone UTC Monday
  dayDateUTC.setUTCDate(dayDateUTC.getUTCDate() + (i - 1)); // add i-1 days in UTC

  const dayStartInCountry = new Date(
    new Intl.DateTimeFormat("en-US", {
      timeZone: timezone,
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false
    }).format(new Date(`${dayDateUTC.toISOString().split("T")[0]}T00:00:00Z`))
  );

  const status = nowInCountry < dayStartInCountry ? "yellow" : "grey";

  if (!account.weeks[weekKey][i]) {
    // ✅ Create day if it doesn't exist
    account.weeks[weekKey][i] = { status, date: dayDateUTC.toISOString().split("T")[0] };
  } else if (account.weeks[weekKey][i].status === "yellow") {
    // ✅ Only update yellow dynamically
    account.weeks[weekKey][i].status = status;
  }
}

    });
  });

  await saveStateToServer();
  console.log("💾 Week data saved to stored.txt (only yellow/grey updated)");

  await updateYellowDays();
  console.log("🔄 Yellow/Grey verification done for new week");

  render(searchBox.value);
});

window.addEventListener("load", () => {
  selectedMonday = getCurrentMonday();
  console.log("DEBUG Initial Selected Monday:", selectedMonday.toISOString().split("T")[0]);
  updateWeekButtonText(selectedMonday);
});

async function updateYellowDays(targetUser = null) {
  const nowUTC = new Date();
  let hasChanges = false;

  const usersToCheck = targetUser ? [targetUser] : state.users;

  usersToCheck.forEach(user => {
    const tz = countryTimezones[user.country] || "UTC";

    // Correct “now” in the user’s country (for logging) + local date (for logic)
    const localNowVerbose = formatLocalDateTimeVerbose(nowUTC, tz);
    const localTodayYMD = getLocalYMD(nowUTC, tz);

    console.log(`\n🌍 ${user.name} — ${user.country} (${tz})`);
    console.log(`   Local now: ${localNowVerbose}`);
    console.log(`   Local today (Y-M-D): ${localTodayYMD}`);

    user.accounts.forEach(account => {
      const weekKey = selectedMonday.toISOString().split("T")[0];
      if (!account.weeks || !account.weeks[weekKey]) return;

      for (let i = 1; i <= 7; i++) {
        const dayData = account.weeks[weekKey][i];
        if (!dayData) continue;

        const shortDay = new Date(dayData.date).toLocaleDateString("en-US", { weekday: "short" });
        const relation = dayData.date > localTodayYMD ? "FUTURE → YELLOW" : "TODAY/PAST → GREY";
        console.log(`   ${shortDay} (${dayData.date}) vs ${localTodayYMD}: ${relation}`);

        // ✅ Yellow if the scheduled date is strictly in the future (in that country)
        if (dayData.date > localTodayYMD) {
          if (dayData.status !== "yellow") {
            dayData.status = "yellow";
            hasChanges = true;
          }
        } else {
if (dayData.status === "yellow") {
  if (dayData.date <= localTodayYMD) {
    // ✅ Only update yellow → grey when the day actually starts
    dayData.status = "grey";
    hasChanges = true;
  }
}
        }

        // Visual refresh animation for this box
        const boxSelector = `.account-item .day-box[data-day="${i}"]`;
        document.querySelectorAll(boxSelector).forEach(box => {
          const accEl = box.closest(".account-item");
          if (
            accEl.querySelector(".accountName").textContent === account.name &&
            accEl.closest(".user-card").querySelector(".userName").textContent === user.name
          ) {
            box.classList.add("refresh-animate");
            setTimeout(() => box.classList.remove("refresh-animate"), 800);
          }
        });
      }
    });
  });

  if (hasChanges) {
    await saveStateToServer();
    render(searchBox.value);
    console.log("✅ Yellow/grey statuses updated based on country local date.");
  }
}

function getLocalYMD(dateUTC, tz) {
  const parts = new Intl.DateTimeFormat("en-CA", {
    timeZone: tz,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).formatToParts(dateUTC);
  const val = (t) => parts.find(p => p.type === t).value;
  return `${val("year")}-${val("month")}-${val("day")}`; // e.g. 2025-09-21
}

function formatLocalDateTimeVerbose(dateUTC, tz) {
  return new Intl.DateTimeFormat("en-GB", {
    timeZone: tz,
    dateStyle: "full",
    timeStyle: "long"
  }).format(dateUTC);
}

// --- Check Captions for Day ---
async function checkCaptionsForDay(userName, accountName, dayIndex, clickedDate) {
      let dayStatus = null;  // ✅ Declare here at the start
  const dayName = dayNames[dayIndex - 1];
  const dateString = clickedDate.toISOString().split("T")[0];
  const currentWeekFolder = `week-${selectedMonday.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric"
  }).replace(" ", "-").toLowerCase()}`; // e.g., week-sep-15

  // 1. --- Ensure folder structure exists ---
// 1. --- Ensure folder structure exists ---
const checkFolderUrl = `backend.php?action=checkAndCreateFolders`;
try {
  const resp = await fetch(checkFolderUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      user: userName,
      weekFolder: currentWeekFolder,
      account: accountName,
      day: dayName
    })
  });
  const folderResult = await resp.json();

  if (folderResult.success) {
    console.log(`📂 Folder verified for ${userName}/${currentWeekFolder}/${accountName}`);

    // ✅ Only now update stored.txt because folders truly exist
    const currentUserObj = state.users.find(u => u.name === userName);
    if (currentUserObj) {
      const currentAccountObj = currentUserObj.accounts.find(a => a.name === accountName);
      if (currentAccountObj) {
        const weekKey = selectedMonday.toISOString().split("T")[0];
        if (!currentAccountObj.weeks[weekKey]) {
          currentAccountObj.weeks[weekKey] = {};
        }
      }
    }
    await saveStateToServer();

  } else {
    alert(`❌ Folder check failed: ${folderResult.error}`);
    return; // Stop execution
  }
} catch (err) {
  alert("❌ Failed to verify folder structure.");
  console.error(err);
  return;
}


// 2. --- Check if captions_log.txt exists ---
// 2. --- Check if captions_log.txt exists (silent, no red 404 errors) ---
const captionsLogPath = `users/${userName}/${currentWeekFolder}/${accountName}/${dayName}/captions_log.txt`;

try {
  const logResp = await fetch(`${captionsLogPath}?t=${Date.now()}`, {
    method: "HEAD",
    cache: "no-store"
  });

  if (!logResp.ok) {
    // ✅ File missing → mark as ORANGE but no console error
    console.warn(`⚠️ captions_log.txt does NOT exist at ${captionsLogPath}`);
    
    const weekKey = selectedMonday.toISOString().split("T")[0];
    const u = state.users.find(u => u.name === userName);
    if (u) {
      const a = u.accounts.find(a => a.name === accountName);
      if (a) {
        if (!a.weeks) a.weeks = {};
        if (!a.weeks[weekKey]) a.weeks[weekKey] = {};
        a.weeks[weekKey][dayIndex] = {
          status: "orange",
          date: clickedDate.toISOString().split("T")[0]
        };
      }
    }

    await saveStateToServer();

    const shortDay = dayName.slice(0, 3);
    const tip = `${shortDay} ${clickedDate.getDate()}: captions_log.txt missing`;
    updateDayBoxUI(userName, accountName, dayIndex, "bg-orange-400", tip);

    return; // ⛔ Stop here if missing
  }

} catch (err) {
  // ✅ Catch prevents red errors if server is unreachable
  console.warn("HEAD request failed silently:", err);
  return;
}



  // 3. --- Now read captions_log.txt content ---
  let captionsLog = [];
  try {
    const logResp = await fetch(`${captionsLogPath}?t=${Date.now()}`, { cache: "no-store" });
    const logText = await logResp.text();
    captionsLog = logText.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
  } catch (err) {
    alert(`❌ Cannot read captions_log.txt for ${dayName}`);
    console.error(err);
    return;
  }

  if (captionsLog.length === 0) {
    alert(`No captions found in captions_log.txt for ${dayName}`);
    return;
  }

  console.log("Captions from captions_log.txt:", captionsLog);

  // 4. --- Scraper API call ---
  const country = state.users.find(u => u.name === userName)?.country || "Nigeria";
  const apiUrl = `https://stephieluv.com/manager/scraped/index.php?folder=${encodeURIComponent(
    accountName
  )}&start=${dateString}&end=${dateString}&country=${encodeURIComponent(country)}`;

  let apiRespJson;
  try {
    const apiResp = await fetch(apiUrl);
    apiRespJson = await apiResp.json();
    if (!apiResp.ok || apiRespJson.error) {
      throw new Error(apiRespJson.error || "Unknown error from scraper API");
    }
  } catch (error) {
    alert("❌ Failed to scrape posts. Please try again.");
    console.error("Scraper API call failed:", error);
    return;
  }

  console.log("Scraper API finished successfully:", apiRespJson);

// 5. --- Read data.txt from scraper folder ---
const dataPath = `https://stephieluv.com/manager/scraped/${accountName}/data.txt`;
let dataContent = [];

try {
  const dataResp = await fetch(dataPath);
  if (!dataResp.ok) throw new Error("Cannot read data.txt");

  const rawJson = await dataResp.json();

  // ✅ Ensure we're extracting ONLY the posts array
  if (Array.isArray(rawJson.posts)) {
      console.log("RAW JSON FROM data.txt:", rawJson);
    dataContent = rawJson.posts;
  } else {
    console.error("Unexpected data.txt format:", rawJson);
    alert("❌ data.txt does not contain a valid 'posts' array.");
    return;
  }
} catch (err) {
  alert("❌ Failed to read data.txt after scraping.");
  console.error("Error reading data.txt:", err);
  return;
}

// Debugging
console.log("DEBUG dataContent:", dataContent);
console.log("Type:", typeof dataContent, "Is Array:", Array.isArray(dataContent));

// 6. --- Filter posts by clicked date ---
const scrapedCaptions = dataContent
  .filter(post => post.date === dateString)
  .map(post => post.caption.trim());

console.log("Scraped captions for exact date:", scrapedCaptions);

// 7. --- Compare captions ---
let matchedCount = 0;
captionsLog.forEach((logCaption) => {
  if (scrapedCaptions.includes(logCaption)) matchedCount++;
});

// --- Check order consistency ---
// Reverse the scraped captions because they're saved backwards
const reversedScraped = [...scrapedCaptions].reverse();

let orderStatus = "Same order";
for (let i = 0; i < Math.min(captionsLog.length, reversedScraped.length); i++) {
  if (captionsLog[i] !== reversedScraped[i]) {
    orderStatus = "Not same order";
    break;
  }
}

const resultText = `${matchedCount} from ${captionsLog.length} were posted\n(${orderStatus})`;


console.log(resultText);

  const weekKey = selectedMonday.toISOString().split("T")[0];

  // --- Save to stored.txt through backend ---
  await fetch("backend.php?action=saveResult", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      user: userName,
      account: accountName,
      week: weekKey,
      day: dayIndex,
      result: resultText,
      date: dateString
    })
  });

const currentUserObj = state.users.find((u) => u.name === userName);
if (currentUserObj) {
  const currentAccountObj = currentUserObj.accounts.find((a) => a.name === accountName);
  if (currentAccountObj) {
    if (!currentAccountObj.weeks) currentAccountObj.weeks = {};
    if (!currentAccountObj.weeks[weekKey]) currentAccountObj.weeks[weekKey] = {};

    // Determine day status
    if (matchedCount === captionsLog.length) {
      dayStatus = "green"; // ✅ All captions matched
    } else if (matchedCount < captionsLog.length) {
      dayStatus = "red";   // ❌ Missing captions
    } else {
      dayStatus = "grey";  // Fallback
    }

    // ✅ Update local state for this day
    currentAccountObj.weeks[weekKey][dayIndex] = {
      status: dayStatus,
      date: dateString
    };
  }
}

// ✅ Update results map
if (!state.results[userName]) state.results[userName] = {};
if (!state.results[userName][accountName]) state.results[userName][accountName] = {};
if (!state.results[userName][accountName][weekKey]) state.results[userName][accountName][weekKey] = {};

state.results[userName][accountName][weekKey][dayIndex] = {
  date: dateString,
  result: `${matchedCount} from ${captionsLog.length} were posted (${orderStatus})`
};

await saveStateToServer();

// Update UI
const shortDayName = dayName.slice(0, 3);
const dayNum = clickedDate.getDate();
const color =
  dayStatus === "green" ? "bg-green-500" :
  dayStatus === "red"   ? "bg-red-500"   :
  dayStatus === "orange"? "bg-orange-400": null;

updateDayBoxUI(
  userName,
  accountName,
  dayIndex,
  color,
  `${shortDayName} ${dayNum}: ${resultText}`
);
}


