(function initFivaPreviewRenderer(global) {
  "use strict";

  function render(container, records = []) {
    if (!container) return;
    container.innerHTML = "";

    records.forEach((record) => {
      const row = document.createElement("label");
      row.className = [
        "fiva-field-row",
        record.required && !record.value ? "is-missing" : "",
        record.requiresReview ? "requires-review" : ""
      ].filter(Boolean).join(" ");
      row.dataset.fieldKey = record.key;

      const label = document.createElement("span");
      label.textContent = record.required ? `${record.label} *` : record.label;
      const meta = document.createElement("small");
      meta.textContent = `${Number(record.confidence || 0)}% confidence - ${record.source || "unknown"}`;
      label.appendChild(meta);

      const control = document.createElement("div");
      control.className = "fiva-field-control";
      const input = document.createElement("input");
      input.type = record.key.includes("Date") || record.key === "dateOfBirth" ? "date" : "text";
      input.value = record.value || "";
      input.dataset.fivaField = record.key;
      input.dataset.confidence = String(record.confidence || 0);
      input.dataset.source = record.source || "manual";
      input.dataset.required = record.required ? "true" : "false";
      input.dataset.requiresReview = record.requiresReview ? "true" : "false";
      input.placeholder = record.required ? "Required" : "Optional";
      control.appendChild(input);

      if (record.required) {
        const verify = document.createElement("label");
        verify.className = "fiva-verify-row";
        const checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.dataset.fivaVerify = record.key;
        checkbox.checked = record.verified === true || (!record.requiresReview && Boolean(record.value));
        verify.appendChild(checkbox);
        verify.appendChild(document.createTextNode("Verified"));
        control.appendChild(verify);
      }

      row.append(label, control);
      container.appendChild(row);
    });
  }

  function collect(container) {
    if (!container) return [];
    return Array.from(container.querySelectorAll("[data-fiva-field]")).map((input) => ({
      key: input.dataset.fivaField,
      value: input.value,
      confidence: Number(input.dataset.confidence || 0),
      source: input.dataset.source || "manual",
      required: input.dataset.required === "true",
      requiresReview: input.dataset.requiresReview === "true",
      verified: container.querySelector(`[data-fiva-verify="${input.dataset.fivaField}"]`)?.checked === true
    }));
  }

  const PreviewRenderer = Object.freeze({
    collect,
    render
  });

  global.FIVA = Object.assign(global.FIVA || {}, { PreviewRenderer });
})(typeof globalThis !== "undefined" ? globalThis : this);
