



const OVERLAY_ACTION_FUNCTION = "__isecaClientOverlayAction";

const OVERLAY_FIELD_DEFINITIONS = [
  ["clientName", "Klient", true, "text"],
  ["clientAddress", "Adres", true, "text"],
  ["clientPostalCode", "Kod pocztowy", true, "text"],
  ["identityNumber", "PESEL / NIP / REGON", true, "text"],
  ["clientMaidenName", "Nazwisko rodowe", true, "text"],
  ["clientPhone", "Telefon", true, "tel"],
  ["clientEmail", "E-mail", true, "email"],
  ["registration", "Nr rejestracyjny", false, "text"],
  ["vehicleMake", "Marka", true, "text"],
  ["vehicleModel", "Model", true, "text"],
  ["vehicleType", "Rodzaj pojazdu", true, "text"],
  ["vin", "VIN", true, "text"],
  ["firstRegistrationDate", "Pierwsza rejestracja", true, "date"],
  ["productionYear", "Rok produkcji", true, "number"],
  ["fuelType", "Paliwo", true, "text"],
  ["engineCapacity", "Pojemność silnika", true, "number"],
  ["enginePower", "Moc silnika", true, "number"],
  ["seats", "Liczba miejsc", true, "number"],
  ["grossWeight", "DMC", true, "number"],
  ["mileage", "Przebieg", true, "number"],
  ["driverLicenseDate", "Prawo jazdy od", true, "text"],
];

const OVERLAY_NUMERIC_FIELDS = new Set([
  "engineCapacity",
  "enginePower",
  "grossWeight",
  "mileage",
]);

function overlayCopyValue(fieldName, value) {
  if (fieldName === "registration") return value.replace(/\s+/g, "");
  if (!OVERLAY_NUMERIC_FIELDS.has(fieldName)) return "";
  const match = value.match(/^(\d(?:[\d\s.,]*\d)?)/);
  return match ? match[1].replace(/\s+/g, "") : "";
}

export function buildClientInfoRows(vehicleInfo) {
  const values = vehicleInfo && typeof vehicleInfo === "object" ? vehicleInfo : {};
  return OVERLAY_FIELD_DEFINITIONS.map(([fieldName, label, editable, inputType]) => {
    const value = String(values[fieldName] ?? "").trim().slice(0, 200);
    return [
      label,
      value,
      overlayCopyValue(fieldName, value),
      fieldName,
      editable,
      inputType,
    ];
  });
}

function mountClientInfoOverlay(model) {
  const HOST_ID = "__bazaPolisDaneKlienta";
  if (!model || !Array.isArray(model.rows)) return;

  const mount = () => {
    if (!document.documentElement || document.getElementById(HOST_ID)) return;

    const host = document.createElement("div");
    host.id = HOST_ID;
    host.setAttribute("data-baza-polis-control", "");
    host.style.cssText = "all:initial; position:fixed; top:84px; right:16px; z-index:2147483646;";
    const shadow = host.attachShadow({ mode: "closed" });

    const style = document.createElement("style");
    style.textContent = `
      * { box-sizing: border-box; margin: 0; padding: 0; }
      button, input { font: inherit; }
      .panel {
        width: 284px; max-height: min(78vh, 680px); display: flex; flex-direction: column;
        border: 1px solid #c9d4e4; border-radius: 12px; overflow: hidden;
        background: #f6f9ff; color: #14243c;
        font: 12px/1.4 "Segoe UI", system-ui, sans-serif;
        box-shadow: 0 12px 34px rgba(10, 24, 46, .28);
      }
      .panel.zwiniety .cialo, .panel.zwiniety .akcje, .panel.zwiniety .status, .panel.zwiniety .stopka { display: none; }
      .panel.zwiniety { width: 166px; }
      .naglowek {
        display: flex; align-items: center; gap: 6px; padding: 8px 10px;
        background: #14324f; color: #fff; cursor: grab; user-select: none;
      }
      .naglowek:active { cursor: grabbing; }
      .naglowek strong { flex: 1; font-size: 12px; letter-spacing: .02em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
      .naglowek button {
        border: 0; width: 20px; height: 20px; border-radius: 5px; flex: none;
        background: rgba(255,255,255,.16); color: #fff; font-size: 12px; line-height: 1;
        cursor: pointer;
      }
      .naglowek button:hover { background: rgba(255,255,255,.32); }
      .cialo { overflow-y: auto; padding: 8px 10px; display: grid; gap: 7px; }
      .wiersz { display: grid; gap: 2px; }
      .wiersz dt { font-size: 9px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; color: #5a6e8c; }
      .wiersz dd { min-width: 0; }
      .wartosc {
        width: 100%; border: 0; text-align: left; background: transparent; color: #14243c;
        font-size: 12.5px; font-weight: 700; overflow-wrap: anywhere; cursor: copy;
        border-radius: 4px; padding: 2px 3px; margin: 0 -3px;
      }
      .wartosc:hover { background: #dbe7fb; }
      .wartosc.skopiowane { background: #cdeed3; }
      .brak { color: #8b99ad; font-size: 11px; font-weight: 600; }
      .edycja { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px; }
      .edycja input {
        min-width: 0; height: 28px; border: 1px solid #b8c7da; border-radius: 6px;
        padding: 4px 7px; background: #fff; color: #14243c; outline: 0;
      }
      .edycja input:focus { border-color: #2b7b64; box-shadow: 0 0 0 2px rgba(43,123,100,.14); }
      .edycja button, .akcje button {
        border: 1px solid #aac8bd; border-radius: 6px; padding: 4px 8px;
        background: #e8f5f0; color: #0a684e; font-weight: 750; cursor: pointer;
      }
      .edycja button:disabled, .akcje button:disabled { opacity: .55; cursor: wait; }
      .akcje { display: flex; padding: 7px 10px; border-top: 1px solid #dde5f1; }
      .akcje button { width: 100%; min-height: 30px; }
      .status { padding: 0 10px 7px; color: #296b55; font-size: 10px; font-weight: 650; }
      .status.blad { color: #a22929; }
      .status:empty { display: none; }
      .stopka { padding: 6px 10px 8px; color: #5a6e8c; font-size: 9.5px; border-top: 1px solid #dde5f1; }
    `;
    shadow.appendChild(style);

    const panel = document.createElement("div");
    panel.className = "panel";

    const header = document.createElement("div");
    header.className = "naglowek";
    const title = document.createElement("strong");
    title.textContent = "Dane klienta – Iseca";
    const collapseButton = document.createElement("button");
    collapseButton.type = "button";
    collapseButton.textContent = "–";
    collapseButton.title = "Zwiń / rozwiń";
    const closeButton = document.createElement("button");
    closeButton.type = "button";
    closeButton.textContent = "×";
    closeButton.title = "Zamknij okienko";
    header.append(title, collapseButton, closeButton);

    const body = document.createElement("dl");
    body.className = "cialo";
    const actions = document.createElement("div");
    actions.className = "akcje";
    const historyButton = document.createElement("button");
    historyButton.type = "button";
    historyButton.textContent = "HistoriaPojazdu.gov";
    historyButton.disabled = model.actionsEnabled !== true;
    actions.appendChild(historyButton);
    const status = document.createElement("div");
    status.className = "status";

    const setStatus = (message = "", error = false) => {
      status.textContent = String(message || "");
      status.classList.toggle("blad", Boolean(error));
    };

    const runAction = async (payload, busyButton) => {
      if (typeof globalThis[model.actionFunction] !== "function") {
        setStatus("Zapis z tej karty nie jest dostępny.", true);
        return null;
      }
      busyButton.disabled = true;
      setStatus("Zapisywanie…");
      try {
        const result = await globalThis[model.actionFunction](payload);
        if (!result?.ok) throw new Error(result?.error || "Nie udało się zapisać danych.");
        setStatus(result.message || "Dane zapisane w bazie.");
        if (Array.isArray(result.rows)) renderRows(result.rows);
        return result;
      } catch (error) {
        setStatus(error?.message || "Nie udało się zapisać danych.", true);
        return null;
      } finally {
        busyButton.disabled = false;
      }
    };

    const renderRows = (rows) => {
      body.replaceChildren();
      rows.forEach(([label, value, copyValue, fieldName, editable, inputType]) => {
        const item = document.createElement("div");
        item.className = "wiersz";
        const term = document.createElement("dt");
        term.textContent = label;
        const detail = document.createElement("dd");
        if (value) {
          const valueButton = document.createElement("button");
          valueButton.type = "button";
          valueButton.className = "wartosc";
          valueButton.textContent = value;
          valueButton.title = "Kliknij, aby skopiować";
          valueButton.addEventListener("click", () => {
            const markCopied = () => {
              valueButton.classList.add("skopiowane");
              setTimeout(() => valueButton.classList.remove("skopiowane"), 900);
            };
            if (navigator.clipboard?.writeText) {
              navigator.clipboard.writeText(copyValue || value).then(markCopied).catch(markCopied);
            } else {
              markCopied();
            }
          });
          detail.appendChild(valueButton);
        } else if (editable && model.actionsEnabled === true) {
          const editor = document.createElement("div");
          editor.className = "edycja";
          const input = document.createElement("input");
          input.type = ["date", "email", "tel", "number"].includes(inputType) ? inputType : "text";
          if (input.type === "text" || input.type === "email" || input.type === "tel") {
            input.maxLength = 200;
          }
          input.placeholder = "Uzupełnij";
          if (input.type === "number") input.min = "0";
          const saveButton = document.createElement("button");
          saveButton.type = "button";
          saveButton.textContent = "Zapisz";
          const save = async () => {
            const nextValue = String(input.value || "").trim();
            if (!nextValue) {
              input.focus();
              return;
            }
            await runAction({ type: "save_missing", fieldName, value: nextValue }, saveButton);
          };
          saveButton.addEventListener("click", save);
          input.addEventListener("keydown", (event) => {
            if (event.key !== "Enter") return;
            event.preventDefault();
            void save();
          });
          editor.append(input, saveButton);
          detail.appendChild(editor);
        } else {
          const missing = document.createElement("span");
          missing.className = "brak";
          missing.textContent = "Brak danych";
          detail.appendChild(missing);
        }
        item.append(term, detail);
        body.appendChild(item);
      });
    };
    renderRows(model.rows);

    historyButton.addEventListener("click", () => {
      void runAction({ type: "vehicle_history" }, historyButton);
    });

    const footer = document.createElement("div");
    footer.className = "stopka";
    footer.textContent = model.actionsEnabled === true
      ? "Kliknij wartość, aby ją skopiować. Brakujące pola możesz od razu dopisać do bazy."
      : "Kliknij wartość, aby ją skopiować. Przeciągnij pasek, aby przesunąć.";

    panel.append(header, body, actions, status, footer);
    shadow.appendChild(panel);
    document.documentElement.appendChild(host);

    let closedByUser = false;
    collapseButton.addEventListener("click", (event) => {
      event.stopPropagation();
      panel.classList.toggle("zwiniety");
      collapseButton.textContent = panel.classList.contains("zwiniety") ? "+" : "–";
    });
    closeButton.addEventListener("click", (event) => {
      event.stopPropagation();
      closedByUser = true;
      host.remove();
    });

    let dragOffset = null;
    header.addEventListener("pointerdown", (event) => {
      if (event.target === collapseButton || event.target === closeButton) return;
      const rect = host.getBoundingClientRect();
      dragOffset = { x: event.clientX - rect.left, y: event.clientY - rect.top };
      header.setPointerCapture?.(event.pointerId);
      event.preventDefault();
    });
    header.addEventListener("pointermove", (event) => {
      if (!dragOffset) return;
      const left = Math.min(Math.max(0, event.clientX - dragOffset.x), window.innerWidth - 60);
      const top = Math.min(Math.max(0, event.clientY - dragOffset.y), window.innerHeight - 40);
      host.style.left = `${left}px`;
      host.style.top = `${top}px`;
      host.style.right = "auto";
    });
    const stopDragging = () => { dragOffset = null; };
    header.addEventListener("pointerup", stopDragging);
    header.addEventListener("pointercancel", stopDragging);

    
    
    const watchdog = setInterval(() => {
      if (closedByUser) {
        clearInterval(watchdog);
        return;
      }
      if (!document.getElementById(HOST_ID) && document.documentElement) {
        document.documentElement.appendChild(host);
      }
    }, 3000);
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", mount, { once: true });
  } else {
    mount();
  }
}

export async function attachClientInfoOverlay(page, vehicleInfo, { onAction } = {}) {
  const actionsEnabled = typeof onAction === "function";
  if (actionsEnabled) {
    await page.exposeFunction(OVERLAY_ACTION_FUNCTION, async (payload) => {
      try {
        const result = await onAction(payload);
        return {
          ok: result?.ok === true,
          error: String(result?.error || "").slice(0, 300),
          message: String(result?.message || "").slice(0, 180),
          rows: result?.vehicleInfo ? buildClientInfoRows(result.vehicleInfo) : null,
        };
      } catch (error) {
        return {
          ok: false,
          error: String(error?.message || "Nie udało się zapisać danych.").slice(0, 300),
        };
      }
    }).catch(() => {});
  }
  const model = {
    rows: buildClientInfoRows(vehicleInfo),
    actionsEnabled,
    actionFunction: OVERLAY_ACTION_FUNCTION,
  };
  await page.evaluateOnNewDocument(mountClientInfoOverlay, model);
  await page.evaluate(mountClientInfoOverlay, model).catch(() => {});
}
