// =============================================================================
// MyTruck Bridge — v2.0 (no extension dependency for caristes)
// =============================================================================
// Runs on the cariste's MyTruck page. When the cariste opens "/new-folder",
// it fetches the current truck for their dock directly from the MyTruck API
// (which is fed every 30s by the bureau extension's background worker).
//
// The cariste no longer depends on the bureau's tab being open/active.
// =============================================================================

console.log("[XDock+] MyTruck Bridge v2.0 chargé");

function setReactField(testId, value) {
  const el = document.querySelector(`[data-testid="${testId}"]`);
  if (!el) {
    console.warn("[XDock+] Champ introuvable :", testId);
    return;
  }
  const proto = el instanceof HTMLSelectElement
    ? HTMLSelectElement.prototype
    : HTMLInputElement.prototype;
  const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
  if (setter) setter.call(el, value || "");
  else el.value = value || "";
  el.dispatchEvent(new Event("input", { bubbles: true }));
  el.dispatchEvent(new Event("change", { bubbles: true }));
}

// Read the JWT token MyTruck stores in localStorage to call the protected API
function getAuthToken() {
  return (
    localStorage.getItem("token") ||
    localStorage.getItem("auth_token") ||
    localStorage.getItem("jwt") ||
    ""
  );
}

async function autoFillOnNewFolder() {
  if (!location.pathname.includes("/new-folder")) return;

  // Small delay so React has time to render the inputs
  await new Promise((r) => setTimeout(r, 800));

  const token = getAuthToken();
  if (!token) {
    console.warn("[XDock+] No JWT in localStorage — cariste pas connecté ?");
    return;
  }

  try {
    const r = await fetch("/api/gp/xdock/current-task/me", {
      headers: { Authorization: `Bearer ${token}` },
      credentials: "same-origin",
    });

    if (!r.ok) {
      console.warn("[XDock+] /me HTTP", r.status);
      return;
    }
    const json = await r.json();
    if (!json?.ok || !json?.found) {
      console.log("[XDock+] Pas de camion en cours pour ce cariste");
      return;
    }
    const d = json.data || {};
    console.log("[XDock+] Camion reçu :", d);

    setReactField("plate-input",        d.tracteur);
    setReactField("remorque-input",     d.remorque);
    setReactField("numero-em-sm-input", d.tour_number);
    setReactField("type-em-sm-input",   d.tour_type);
  } catch (e) {
    console.warn("[XDock+] fetch /me failed:", e);
  }
}

// Trigger on initial load + on every SPA route change (MyTruck is React/SPA)
autoFillOnNewFolder();

let lastPath = location.pathname;
setInterval(() => {
  if (location.pathname !== lastPath) {
    lastPath = location.pathname;
    autoFillOnNewFolder();
  }
}, 500);

console.log("[XDock+] MyTruck Bridge prêt");
