(() => {
  if (window.__medtoolsLakmusContentBooted) {
    return;
  }
  window.__medtoolsLakmusContentBooted = true;

const MEDTOOLS_ALLOWED_LAKMUS_FIELDS = {
  complaints: ["Скарги", "Скарги під час огляду"],
  disease_history: ["Анамнез захворювання"],
  life_history: ["Анамнез життя"]
};

const MEDTOOLS_RECORDER_OVERLAY_ID = "medtools-recorder-overlay";
const MEDTOOLS_RECORDER_IFRAME_ID = "medtools-recorder-frame";
const MEDTOOLS_RECORDER_TITLEBAR_ID = "medtools-recorder-titlebar";
const MEDTOOLS_RECORDER_HOST_STATUS_ID = "medtools-recorder-host-status";
const MEDTOOLS_RECORDER_HOST_DURATION_ID = "medtools-recorder-host-duration";
const MEDTOOLS_RECORDER_HOST_AUDIO_BAR_ID = "medtools-recorder-host-audio-bar";
const MEDTOOLS_RECORDER_HOST_TOTAL_PROGRESS_ID = "medtools-recorder-host-total-progress";
const MEDTOOLS_RECORDER_HOST_PROGRESS_ID = "medtools-recorder-host-progress";
const MEDTOOLS_RECORDER_HOST_MIC_ID = "medtools-recorder-host-mic";
const MEDTOOLS_APP_OVERLAY_ID = "medtools-app-overlay";
const MEDTOOLS_APP_IFRAME_ID = "medtools-app-frame";
const MEDTOOLS_APP_TITLEBAR_ID = "medtools-app-titlebar";
const MEDTOOLS_OVERLAY_BASE_Z = 2147483000;
const MEDTOOLS_RECORDER_FULL_HEIGHT = 620;
const MEDTOOLS_RECORDER_COMPACT_HEIGHT = 146;
const MEDTOOLS_RECORDER_MINIMIZED_HEIGHT = 36;
const MEDTOOLS_RECORDER_TITLEBAR_HEIGHT = 30;
const MEDTOOLS_RECORDER_WIDTH = 420;
const MEDTOOLS_APP_HEIGHT = 660;
const MEDTOOLS_APP_MINIMIZED_HEIGHT = 34;
const MEDTOOLS_APP_TITLEBAR_HEIGHT = 30;
const MEDTOOLS_APP_WIDTH = 430;

let medtoolsRecorderFrame = null;
let medtoolsRecorderDrag = null;
let medtoolsAppFrame = null;
let medtoolsAppDrag = null;
let medtoolsOverlayZ = MEDTOOLS_OVERLAY_BASE_Z;

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message?.type === "MEDTOOLS_FILL_VISIBLE_LAKMUS_FIELDS") {
    const result = fillVisibleLakmusFields(message.fields || {});
    sendResponse(result);
    return false;
  }

  if (message?.type === "MEDTOOLS_CHECK_VISIBLE_LAKMUS_FIELDS") {
    sendResponse(inspectVisibleLakmusFields());
    return false;
  }

  if (message?.type === "MEDTOOLS_SHOW_RECORDER_OVERLAY") {
    const result = showRecorderOverlay(message.options || {});
    sendResponse(result);
    return false;
  }

  if (message?.type === "MEDTOOLS_SHOW_APP_OVERLAY") {
    const result = showAppOverlay();
    sendResponse(result);
    return false;
  }

  return false;
});

window.addEventListener("message", handleRecorderOverlayMessage);
window.addEventListener("message", handleAppOverlayMessage);
window.addEventListener("resize", () => {
  resizeRecorderOverlay();
  resizeAppOverlay();
});

function showAppOverlay() {
  const overlay = ensureAppOverlay();
  overlay.hidden = false;
  overlay.style.display = "block";
  bringOverlayToFront(overlay);
  setAppOverlayMinimized(false);
  resizeAppOverlay();
  medtoolsAppFrame?.focus();
  return { ok: true, shown: true };
}

function ensureAppOverlay() {
  let overlay = document.getElementById(MEDTOOLS_APP_OVERLAY_ID);
  if (overlay) {
    medtoolsAppFrame = document.getElementById(MEDTOOLS_APP_IFRAME_ID);
    return overlay;
  }

  overlay = createOverlayShell({
    id: MEDTOOLS_APP_OVERLAY_ID,
    width: MEDTOOLS_APP_WIDTH,
    height: MEDTOOLS_APP_HEIGHT + MEDTOOLS_APP_TITLEBAR_HEIGHT,
    background: "#f8fbf8",
    border: "1px solid rgba(15, 118, 110, 0.28)"
  });

  const titlebar = createOverlayTitlebar({
    id: MEDTOOLS_APP_TITLEBAR_ID,
    title: "Parallax Health",
    background: "#173326",
    height: MEDTOOLS_APP_TITLEBAR_HEIGHT,
    onMinimize: () => setAppOverlayMinimized(true),
    onRestore: () => {
      setAppOverlayMinimized(false);
      resizeAppOverlay();
    }
  });
  titlebar.addEventListener("pointerdown", startAppOverlayDrag);

  medtoolsAppFrame = document.createElement("iframe");
  medtoolsAppFrame.id = MEDTOOLS_APP_IFRAME_ID;
  medtoolsAppFrame.title = "Parallax Health";
  medtoolsAppFrame.src = chrome.runtime.getURL("popup.html?embedded=1");
  medtoolsAppFrame.allow = "microphone";
  Object.assign(medtoolsAppFrame.style, {
    display: "block",
    width: "100%",
    height: `calc(100% - ${MEDTOOLS_APP_TITLEBAR_HEIGHT}px)`,
    border: "0",
    background: "#f8fbf8"
  });

  overlay.append(titlebar, medtoolsAppFrame);
  document.documentElement.append(overlay);
  return overlay;
}

function handleAppOverlayMessage(event) {
  if (!medtoolsAppFrame || event.source !== medtoolsAppFrame.contentWindow) {
    return;
  }
  const data = event.data || {};
  if (data.source !== "MEDTOOLS_APP") {
    return;
  }
  if (data.type === "SHOW_RECORDER") {
    setAppOverlayMinimized(true);
    showRecorderOverlay({ compact: false });
  }
  if (data.type === "HIDE") {
    setAppOverlayMinimized(true);
  }
}

function createOverlayShell({ id, width, height, background, border }) {
  const overlay = document.createElement("div");
  overlay.id = id;
  Object.assign(overlay.style, {
    position: "fixed",
    top: "12px",
    right: "12px",
    width: `${width}px`,
    height: `${height}px`,
    maxWidth: "calc(100vw - 24px)",
    maxHeight: "calc(100vh - 24px)",
    overflow: "hidden",
    border,
    borderRadius: "10px",
    boxShadow: "0 18px 48px rgba(0, 0, 0, 0.38)",
    background,
    zIndex: String(MEDTOOLS_OVERLAY_BASE_Z)
  });
  overlay.addEventListener("pointerdown", () => bringOverlayToFront(overlay));
  return overlay;
}

function createOverlayTitlebar({ id, title, background, height, onMinimize, onRestore }) {
  const titlebar = document.createElement("div");
  titlebar.id = id;
  Object.assign(titlebar.style, {
    height: `${height}px`,
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: "8px",
    padding: "0 8px 0 10px",
    color: "#e5edf7",
    background,
    borderBottom: "1px solid rgba(148, 163, 184, 0.22)",
    cursor: "move",
    userSelect: "none",
    font: "700 12px/1.2 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
  });

  const titleText = document.createElement("span");
  titleText.textContent = title;
  Object.assign(titleText.style, {
    minWidth: "0",
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap"
  });

  const controls = document.createElement("div");
  Object.assign(controls.style, {
    display: "flex",
    alignItems: "center",
    gap: "6px",
    flex: "0 0 auto"
  });

  const minimizeButton = recorderOverlayButton("Згорнути");
  minimizeButton.dataset.role = "minimize";
  minimizeButton.addEventListener("click", (event) => {
    event.stopPropagation();
    onMinimize();
  });

  const restoreButton = recorderOverlayButton("Розгорнути");
  restoreButton.dataset.role = "restore";
  restoreButton.style.display = "none";
  restoreButton.addEventListener("click", (event) => {
    event.stopPropagation();
    onRestore();
  });

  controls.append(minimizeButton, restoreButton);
  titlebar.append(titleText, controls);
  return titlebar;
}

function resizeAppOverlay() {
  const overlay = document.getElementById(MEDTOOLS_APP_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  const targetHeight = overlay.dataset.minimized === "1"
    ? MEDTOOLS_APP_MINIMIZED_HEIGHT
    : MEDTOOLS_APP_HEIGHT + MEDTOOLS_APP_TITLEBAR_HEIGHT;
  applySpecificOverlayBounds(overlay, MEDTOOLS_APP_WIDTH, targetHeight, MEDTOOLS_APP_MINIMIZED_HEIGHT);
}

function setAppOverlayMinimized(minimized) {
  const overlay = document.getElementById(MEDTOOLS_APP_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  overlay.dataset.minimized = minimized ? "1" : "0";
  if (medtoolsAppFrame) {
    medtoolsAppFrame.style.display = minimized ? "none" : "block";
  }
  const minimizeButton = overlay.querySelector("[data-role='minimize']");
  const restoreButton = overlay.querySelector("[data-role='restore']");
  if (minimizeButton) {
    minimizeButton.style.display = minimized ? "none" : "inline-flex";
  }
  if (restoreButton) {
    restoreButton.style.display = minimized ? "inline-flex" : "none";
  }
  resizeAppOverlay();
}

function startAppOverlayDrag(event) {
  const button = event.target.closest?.("button");
  if (button) {
    return;
  }
  const overlay = document.getElementById(MEDTOOLS_APP_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  const rect = overlay.getBoundingClientRect();
  medtoolsAppDrag = {
    pointerId: event.pointerId,
    startX: event.clientX,
    startY: event.clientY,
    left: rect.left,
    top: rect.top
  };
  overlay.style.right = "auto";
  overlay.style.left = `${rect.left}px`;
  overlay.style.top = `${rect.top}px`;
  event.currentTarget.setPointerCapture?.(event.pointerId);
  window.addEventListener("pointermove", moveAppOverlay);
  window.addEventListener("pointerup", stopAppOverlayDrag, { once: true });
}

function moveAppOverlay(event) {
  if (!medtoolsAppDrag) {
    return;
  }
  const overlay = document.getElementById(MEDTOOLS_APP_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  const nextLeft = medtoolsAppDrag.left + event.clientX - medtoolsAppDrag.startX;
  const nextTop = medtoolsAppDrag.top + event.clientY - medtoolsAppDrag.startY;
  overlay.style.left = `${nextLeft}px`;
  overlay.style.top = `${nextTop}px`;
  clampOverlayToViewport(overlay);
}

function stopAppOverlayDrag() {
  medtoolsAppDrag = null;
  window.removeEventListener("pointermove", moveAppOverlay);
}

function showRecorderOverlay(options = {}) {
  const overlay = ensureRecorderOverlay();
  overlay.hidden = false;
  overlay.style.display = "block";
  bringOverlayToFront(overlay);
  setRecorderOverlayMinimized(false);
  resizeRecorderOverlay(Boolean(options.compact));
  if (medtoolsRecorderFrame?.contentWindow) {
    medtoolsRecorderFrame.contentWindow.postMessage({
      source: "MEDTOOLS_LAKMUS_HOST",
      type: "SET_COMPACT",
      compact: Boolean(options.compact)
    }, "*");
    medtoolsRecorderFrame.focus();
  }
  return { ok: true, shown: true };
}

function ensureRecorderOverlay() {
  let overlay = document.getElementById(MEDTOOLS_RECORDER_OVERLAY_ID);
  if (overlay) {
    medtoolsRecorderFrame = document.getElementById(MEDTOOLS_RECORDER_IFRAME_ID);
    return overlay;
  }

  overlay = document.createElement("div");
  overlay.id = MEDTOOLS_RECORDER_OVERLAY_ID;
  Object.assign(overlay.style, {
    position: "fixed",
    top: "12px",
    right: "12px",
    width: `${MEDTOOLS_RECORDER_WIDTH}px`,
    height: `${MEDTOOLS_RECORDER_FULL_HEIGHT + MEDTOOLS_RECORDER_TITLEBAR_HEIGHT}px`,
    maxWidth: "calc(100vw - 24px)",
    maxHeight: "calc(100vh - 24px)",
    overflow: "hidden",
    border: "1px solid rgba(45, 212, 191, 0.38)",
    borderRadius: "10px",
    boxShadow: "0 18px 48px rgba(0, 0, 0, 0.38)",
    background: "#111b2b",
    transform: "translateZ(0)",
    contain: "layout style",
    zIndex: String(MEDTOOLS_OVERLAY_BASE_Z)
  });
  overlay.addEventListener("pointerdown", () => bringOverlayToFront(overlay));

  const titlebar = document.createElement("div");
  titlebar.id = MEDTOOLS_RECORDER_TITLEBAR_ID;
  Object.assign(titlebar.style, {
    height: `${MEDTOOLS_RECORDER_TITLEBAR_HEIGHT}px`,
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: "8px",
    padding: "0 8px 0 10px",
    color: "#e5edf7",
    background: "#172235",
    borderBottom: "1px solid rgba(148, 163, 184, 0.22)",
    cursor: "move",
    userSelect: "none",
    font: "700 12px/1.2 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
  });

  const titleGroup = document.createElement("div");
  Object.assign(titleGroup.style, {
    display: "flex",
    alignItems: "center",
    gap: "8px",
    minWidth: "0",
    flex: "1 1 auto",
    overflow: "hidden"
  });

  const title = document.createElement("span");
  title.textContent = "Запис консультації";
  Object.assign(title.style, {
    minWidth: "0",
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap"
  });

  const hostSummary = document.createElement("div");
  Object.assign(hostSummary.style, {
    display: "grid",
    gridTemplateColumns: "auto auto minmax(42px, 74px)",
    gridTemplateAreas: "'status duration meter' 'progress progress progress' 'mic mic mic'",
    alignItems: "center",
    columnGap: "6px",
    rowGap: "2px",
    minWidth: "132px",
    flex: "1 1 156px"
  });

  const hostStatus = document.createElement("span");
  hostStatus.id = MEDTOOLS_RECORDER_HOST_STATUS_ID;
  hostStatus.textContent = "Очікує";
  Object.assign(hostStatus.style, {
    gridArea: "status",
    minWidth: "48px",
    borderRadius: "7px",
    padding: "4px 6px",
    background: "#1e293b",
    color: "#cbd5e1",
    textAlign: "center",
    font: "800 10px/1 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif"
  });

  const hostDuration = document.createElement("span");
  hostDuration.id = MEDTOOLS_RECORDER_HOST_DURATION_ID;
  hostDuration.textContent = "00:00";
  Object.assign(hostDuration.style, {
    gridArea: "duration",
    minWidth: "38px",
    color: "#f8fafc",
    textAlign: "center",
    font: "700 12px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"
  });

  const hostMeter = document.createElement("span");
  Object.assign(hostMeter.style, {
    gridArea: "meter",
    position: "relative",
    display: "block",
    height: "7px",
    minWidth: "42px",
    overflow: "hidden",
    borderRadius: "999px",
    background: "#1e293b",
    boxShadow: "inset 0 0 0 1px rgba(45, 212, 191, 0.18)"
  });

  const hostAudioBar = document.createElement("span");
  hostAudioBar.id = MEDTOOLS_RECORDER_HOST_AUDIO_BAR_ID;
  Object.assign(hostAudioBar.style, {
    position: "absolute",
    inset: "0 auto 0 0",
    width: "0%",
    borderRadius: "inherit",
    background: "linear-gradient(90deg, #22d3ee, #2dd4bf, #84cc16)",
    transition: "width 80ms linear"
  });
  hostMeter.append(hostAudioBar);
  const hostProgress = document.createElement("span");
  Object.assign(hostProgress.style, {
    gridArea: "progress",
    position: "relative",
    display: "block",
    height: "4px",
    minWidth: "0",
    overflow: "hidden",
    borderRadius: "999px",
    background: "rgba(15, 23, 42, 0.9)",
    boxShadow: "inset 0 0 0 1px rgba(148, 163, 184, 0.16)"
  });
  const hostProgressBar = document.createElement("span");
  hostProgressBar.id = MEDTOOLS_RECORDER_HOST_TOTAL_PROGRESS_ID;
  Object.assign(hostProgressBar.style, {
    position: "absolute",
    inset: "0 auto 0 0",
    width: "0%",
    borderRadius: "inherit",
    background: "rgba(148, 163, 184, 0.38)",
    transition: "width 180ms ease"
  });
  const hostProcessedBar = document.createElement("span");
  hostProcessedBar.id = MEDTOOLS_RECORDER_HOST_PROGRESS_ID;
  Object.assign(hostProcessedBar.style, {
    position: "absolute",
    inset: "0 auto 0 0",
    width: "0%",
    borderRadius: "inherit",
    background: "linear-gradient(90deg, #2dd4bf, #22d3ee)",
    boxShadow: "0 0 12px rgba(45, 212, 191, 0.24)",
    transition: "width 180ms ease"
  });
  hostProgress.append(hostProgressBar, hostProcessedBar);
  const hostMic = document.createElement("span");
  hostMic.id = MEDTOOLS_RECORDER_HOST_MIC_ID;
  hostMic.textContent = "мікрофон не вибрано";
  Object.assign(hostMic.style, {
    gridArea: "mic",
    minWidth: "0",
    maxWidth: "170px",
    overflow: "hidden",
    color: "#a8bdd6",
    font: "800 9px/1.1 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap"
  });
  hostSummary.append(hostStatus, hostDuration, hostMeter, hostProgress, hostMic);
  titleGroup.append(title, hostSummary);

  const controls = document.createElement("div");
  Object.assign(controls.style, {
    display: "flex",
    alignItems: "center",
    gap: "6px",
    flex: "0 0 auto"
  });

  const minimizeButton = recorderOverlayButton("Згорнути");
  minimizeButton.dataset.role = "minimize";
  minimizeButton.addEventListener("click", (event) => {
    event.stopPropagation();
    setRecorderOverlayMinimized(true);
  });

  const restoreButton = recorderOverlayButton("Розгорнути");
  restoreButton.dataset.role = "restore";
  restoreButton.style.display = "none";
  restoreButton.addEventListener("click", (event) => {
    event.stopPropagation();
    setRecorderOverlayMinimized(false);
    resizeRecorderOverlay();
  });

  controls.append(minimizeButton, restoreButton);
  titlebar.append(titleGroup, controls);
  titlebar.addEventListener("pointerdown", startRecorderOverlayDrag);

  medtoolsRecorderFrame = document.createElement("iframe");
  medtoolsRecorderFrame.id = MEDTOOLS_RECORDER_IFRAME_ID;
  medtoolsRecorderFrame.title = "Запис консультації";
  medtoolsRecorderFrame.src = chrome.runtime.getURL("recorder.html?embedded=1");
  medtoolsRecorderFrame.allow = "microphone";
  Object.assign(medtoolsRecorderFrame.style, {
    display: "block",
    width: "100%",
    height: `calc(100% - ${MEDTOOLS_RECORDER_TITLEBAR_HEIGHT}px)`,
    border: "0",
    background: "#111b2b"
  });

  overlay.append(titlebar, medtoolsRecorderFrame);
  document.documentElement.append(overlay);
  return overlay;
}

function handleRecorderOverlayMessage(event) {
  if (!medtoolsRecorderFrame || event.source !== medtoolsRecorderFrame.contentWindow) {
    return;
  }
  const data = event.data || {};
  if (data.source !== "MEDTOOLS_RECORDER") {
    return;
  }
  if (data.type === "RESIZE") {
    setRecorderOverlayMinimized(false);
    resizeRecorderOverlay(Boolean(data.compactMode));
  }
  if (data.type === "HIDE") {
    setRecorderOverlayMinimized(true);
  }
  if (data.type === "STATUS") {
    updateRecorderHostStatus(data);
  }
}

function updateRecorderHostStatus(data) {
  const status = document.getElementById(MEDTOOLS_RECORDER_HOST_STATUS_ID);
  const duration = document.getElementById(MEDTOOLS_RECORDER_HOST_DURATION_ID);
  const audioBar = document.getElementById(MEDTOOLS_RECORDER_HOST_AUDIO_BAR_ID);
  const totalBar = document.getElementById(MEDTOOLS_RECORDER_HOST_TOTAL_PROGRESS_ID);
  const progressBar = document.getElementById(MEDTOOLS_RECORDER_HOST_PROGRESS_ID);
  const mic = document.getElementById(MEDTOOLS_RECORDER_HOST_MIC_ID);
  if (!status || !duration || !audioBar) {
    return;
  }
  const statusKind = data.statusClass || "idle";
  const palette = {
    recording: ["#7f1d1d", "#fecaca"],
    processing: ["#78350f", "#fde68a"],
    stopped: ["#78350f", "#fde68a"],
    idle: ["#1e293b", "#cbd5e1"]
  };
  const [background, color] = palette[statusKind] || palette.idle;
  status.textContent = data.statusLabel || "Очікує";
  status.style.background = background;
  status.style.color = color;
  duration.textContent = data.duration || "00:00";
  const audioLevel = Math.max(0, Math.min(100, Number(data.audioLevel || 0)));
  audioBar.style.width = `${audioLevel}%`;
  if (totalBar) {
    const recordedPercent = Math.max(0, Math.min(100, Number(data.recordedPercent || 0)));
    totalBar.style.width = `${recordedPercent}%`;
  }
  if (progressBar) {
    const processedPercent = Math.max(0, Math.min(100, Number(data.processedPercent || 0)));
    progressBar.style.width = `${processedPercent}%`;
  }
  const recordedLabel = data.recordedLabel || "00:00";
  const transcribedLabel = data.transcribedLabel || "00:00";
  const progressTitle = data.processedLabel
    ? `Записано ${recordedLabel}; транскрибовано ${transcribedLabel}`
    : "";
  if (totalBar) {
    totalBar.title = progressTitle;
  }
  if (progressBar) {
    progressBar.title = progressTitle;
  }
  if (mic) {
    const microphoneLabel = String(data.microphoneLabel || "мікрофон не вибрано").trim();
    mic.textContent = microphoneLabel;
    mic.title = microphoneLabel;
  }
}

function resizeRecorderOverlay(compactMode = null) {
  const overlay = document.getElementById(MEDTOOLS_RECORDER_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  if (overlay.dataset.minimized === "1") {
    applyRecorderOverlayBounds(overlay, MEDTOOLS_RECORDER_MINIMIZED_HEIGHT);
    return;
  }
  const targetHeight = compactMode === true
    ? MEDTOOLS_RECORDER_COMPACT_HEIGHT
    : compactMode === false
      ? MEDTOOLS_RECORDER_FULL_HEIGHT
      : Number.parseInt(overlay.dataset.height || MEDTOOLS_RECORDER_FULL_HEIGHT, 10);
  overlay.dataset.height = String(targetHeight);
  applyRecorderOverlayBounds(overlay, targetHeight + MEDTOOLS_RECORDER_TITLEBAR_HEIGHT);
}

function recorderOverlayButton(label) {
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = label;
  Object.assign(button.style, {
    border: "0",
    borderRadius: "7px",
    padding: "4px 8px",
    color: "#eaf2ff",
    background: "#334155",
    font: "700 11px/1 -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
    cursor: "pointer"
  });
  return button;
}

function setRecorderOverlayMinimized(minimized) {
  const overlay = document.getElementById(MEDTOOLS_RECORDER_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  overlay.dataset.minimized = minimized ? "1" : "0";
  if (medtoolsRecorderFrame) {
    medtoolsRecorderFrame.style.display = minimized ? "none" : "block";
  }
  overlay.style.boxShadow = minimized
    ? "0 10px 28px rgba(0, 0, 0, 0.36)"
    : "0 18px 48px rgba(0, 0, 0, 0.38)";
  const minimizeButton = overlay.querySelector("[data-role='minimize']");
  const restoreButton = overlay.querySelector("[data-role='restore']");
  if (minimizeButton) {
    minimizeButton.style.display = minimized ? "none" : "inline-flex";
  }
  if (restoreButton) {
    restoreButton.style.display = minimized ? "inline-flex" : "none";
  }
  if (minimized) {
    applyRecorderOverlayBounds(overlay, MEDTOOLS_RECORDER_MINIMIZED_HEIGHT);
  } else {
    resizeRecorderOverlay();
  }
}

function applyRecorderOverlayBounds(overlay, targetHeight) {
  applySpecificOverlayBounds(overlay, MEDTOOLS_RECORDER_WIDTH, targetHeight, MEDTOOLS_RECORDER_MINIMIZED_HEIGHT);
}

function applySpecificOverlayBounds(overlay, targetWidth, targetHeight, minHeight) {
  const minimumWidth = overlay.dataset.minimized === "1" ? 340 : 320;
  const width = Math.min(targetWidth, Math.max(minimumWidth, window.innerWidth - 24));
  const height = Math.min(targetHeight, Math.max(minHeight, window.innerHeight - 24));
  overlay.style.width = `${width}px`;
  overlay.style.height = `${height}px`;
  clampOverlayToViewport(overlay);
}

function startRecorderOverlayDrag(event) {
  const button = event.target.closest?.("button");
  if (button) {
    return;
  }
  const overlay = document.getElementById(MEDTOOLS_RECORDER_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  const rect = overlay.getBoundingClientRect();
  medtoolsRecorderDrag = {
    pointerId: event.pointerId,
    startX: event.clientX,
    startY: event.clientY,
    left: rect.left,
    top: rect.top
  };
  overlay.style.right = "auto";
  overlay.style.left = `${rect.left}px`;
  overlay.style.top = `${rect.top}px`;
  event.currentTarget.setPointerCapture?.(event.pointerId);
  window.addEventListener("pointermove", moveRecorderOverlay);
  window.addEventListener("pointerup", stopRecorderOverlayDrag, { once: true });
}

function moveRecorderOverlay(event) {
  if (!medtoolsRecorderDrag) {
    return;
  }
  const overlay = document.getElementById(MEDTOOLS_RECORDER_OVERLAY_ID);
  if (!overlay) {
    return;
  }
  const nextLeft = medtoolsRecorderDrag.left + event.clientX - medtoolsRecorderDrag.startX;
  const nextTop = medtoolsRecorderDrag.top + event.clientY - medtoolsRecorderDrag.startY;
  overlay.style.left = `${nextLeft}px`;
  overlay.style.top = `${nextTop}px`;
  clampOverlayToViewport(overlay);
}

function stopRecorderOverlayDrag() {
  medtoolsRecorderDrag = null;
  window.removeEventListener("pointermove", moveRecorderOverlay);
}

function clampOverlayToViewport(overlay) {
  const rect = overlay.getBoundingClientRect();
  const margin = 8;
  const maxLeft = Math.max(margin, window.innerWidth - rect.width - margin);
  const maxTop = Math.max(margin, window.innerHeight - rect.height - margin);
  const left = Number.isFinite(rect.left) ? Math.min(Math.max(rect.left, margin), maxLeft) : margin;
  const top = Number.isFinite(rect.top) ? Math.min(Math.max(rect.top, margin), maxTop) : margin;
  overlay.style.left = `${left}px`;
  overlay.style.top = `${top}px`;
  overlay.style.right = "auto";
}

function bringOverlayToFront(overlay) {
  medtoolsOverlayZ = Math.min(medtoolsOverlayZ + 1, 2147483647);
  overlay.style.zIndex = String(medtoolsOverlayZ);
}

function fillVisibleLakmusFields(fields) {
  const filled = [];
  const skipped = [];

  for (const [key, labels] of Object.entries(MEDTOOLS_ALLOWED_LAKMUS_FIELDS)) {
    const value = String(fields[key] || "").trim();
    if (!value) {
      skipped.push(`${labels[0]}: немає значення`);
      continue;
    }

    const target = findVisibleFieldByLabels(labels);
    if (!target) {
      skipped.push(`${labels[0]}: поле не відкрите або не видиме`);
      continue;
    }
    if (fieldAlreadyContains(target, value)) {
      skipped.push(`${labels[0]}: цей текст уже є`);
      continue;
    }

    appendFieldValue(target, value);
    filled.push(labels[0]);
  }

  return { ok: true, filled, skipped };
}

function inspectVisibleLakmusFields() {
  const visible = [];
  const missing = [];
  for (const [key, labels] of Object.entries(MEDTOOLS_ALLOWED_LAKMUS_FIELDS)) {
    const item = {
      key,
      label: labels[0],
      visible: Boolean(findVisibleFieldByLabels(labels))
    };
    if (item.visible) {
      visible.push(item);
    } else {
      missing.push(item);
    }
  }
  return {
    ok: true,
    ready: missing.length === 0,
    visible,
    missing
  };
}

function findVisibleFieldByLabels(labels) {
  for (const label of labels) {
    const labelElement = findVisibleLabel(label);
    if (!labelElement) {
      continue;
    }
    const target = findEditableNearLabel(labelElement);
    if (target && isVisibleOnScreen(target)) {
      return target;
    }
  }
  return null;
}

function findVisibleLabel(label) {
  const normalizedLabel = normalizeText(label);
  const elements = Array.from(document.querySelectorAll("label, td, th, div, span, p"));
  const exact = elements.find((element) => {
    if (!isVisibleOnScreen(element)) {
      return false;
    }
    const text = normalizeText(element.innerText || element.textContent || "");
    return text === normalizedLabel;
  }) || null;
  if (exact) {
    return exact;
  }
  return elements.find((element) => {
    if (!isVisibleOnScreen(element)) {
      return false;
    }
    const text = normalizeText(element.innerText || element.textContent || "");
    return text.startsWith(`${normalizedLabel} `) && text.length <= normalizedLabel.length + 24;
  }) || null;
}

function findEditableNearLabel(labelElement) {
  const labelControl = directLabelControl(labelElement);
  if (labelControl && isVisibleOnScreen(labelControl)) {
    return labelControl;
  }

  let current = labelElement;
  for (let depth = 0; current && depth < 6; depth += 1) {
    const candidate = firstVisibleEditable(current);
    if (candidate && candidate !== labelElement) {
      return candidate;
    }

    const siblingCandidate = firstVisibleEditableInSiblings(current);
    if (siblingCandidate) {
      return siblingCandidate;
    }
    current = current.parentElement;
  }

  return null;
}

function directLabelControl(labelElement) {
  if (labelElement.tagName === "LABEL") {
    const forId = labelElement.getAttribute("for");
    if (forId) {
      const control = document.getElementById(forId);
      if (isEditable(control)) {
        return control;
      }
    }
    const nested = firstVisibleEditable(labelElement);
    if (nested) {
      return nested;
    }
  }
  return null;
}

function firstVisibleEditableInSiblings(element) {
  let sibling = element.nextElementSibling;
  while (sibling) {
    const candidate = firstVisibleEditable(sibling);
    if (candidate) {
      return candidate;
    }
    sibling = sibling.nextElementSibling;
  }
  return null;
}

function firstVisibleEditable(root) {
  const editables = Array.from(root.querySelectorAll("textarea, input, [contenteditable='true'], [role='textbox']"));
  return editables.find((element) => isEditable(element) && isVisibleOnScreen(element)) || null;
}

function isEditable(element) {
  if (!element) {
    return false;
  }
  if (element.matches("textarea, [contenteditable='true'], [role='textbox']")) {
    return true;
  }
  if (element.matches("input")) {
    const type = String(element.getAttribute("type") || "text").toLowerCase();
    return ["", "text", "search", "number"].includes(type);
  }
  return false;
}

function appendFieldValue(element, value) {
  if (element.matches("[contenteditable='true'], [role='textbox']") && !element.matches("input, textarea")) {
    appendToRichText(element, value);
  } else {
    appendToInput(element, value);
  }
  element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: value }));
  element.dispatchEvent(new Event("change", { bubbles: true }));
}

function fieldAlreadyContains(element, value) {
  const existing = element.matches("input, textarea")
    ? element.value
    : (element.innerText || element.textContent || "");
  return normalizeText(existing).includes(normalizeText(value));
}

function appendToInput(element, value) {
  const current = String(element.value || "");
  const appendix = `${appendPrefix(current)}${value}`;
  if (typeof element.setRangeText === "function") {
    const end = current.length;
    element.setRangeText(appendix, end, end, "end");
  } else {
    element.value = `${current}${appendix}`;
  }
}

function appendToRichText(element, value) {
  const hasText = Boolean(normalizeText(element.innerText || element.textContent || ""));
  if (hasText) {
    element.append(document.createElement("br"), document.createElement("br"));
  }
  element.append(document.createTextNode(value));
}

function appendPrefix(current) {
  if (!current) {
    return "";
  }
  if (current.endsWith("\n\n")) {
    return "";
  }
  if (current.endsWith("\n")) {
    return "\n";
  }
  return "\n\n";
}

function isVisibleOnScreen(element) {
  if (!element || !element.isConnected) {
    return false;
  }
  const style = window.getComputedStyle(element);
  if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) {
    return false;
  }
  const rects = element.getClientRects();
  if (!rects.length) {
    return false;
  }
  const rect = element.getBoundingClientRect();
  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
  return rect.width > 0
    && rect.height > 0
    && rect.bottom > 0
    && rect.right > 0
    && rect.top < viewportHeight
    && rect.left < viewportWidth;
}

function normalizeText(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}

if (window.__MEDTOOLS_LAKMUS_TEST__) {
  window.__MEDTOOLS_LAKMUS_TEST_API__ = {
    fillVisibleLakmusFields,
    inspectVisibleLakmusFields,
    findVisibleFieldByLabels,
    fieldAlreadyContains,
    normalizeText
  };
}

})();
