(function (root, factory) {
  const reviewRenderer = factory();
  if (typeof module === "object" && module.exports) {
    module.exports = reviewRenderer;
  } else {
    root.MealSnapshotReviewRenderer = reviewRenderer;
  }
}(typeof globalThis !== "undefined" ? globalThis : this, function () {
  "use strict";

  const MACROS = Object.freeze([
    Object.freeze({ field: "calories", label: "Estimated calories", unit: "kcal" }),
    Object.freeze({ field: "protein", label: "Protein", unit: "g" }),
    Object.freeze({ field: "carbs", label: "Carbs", unit: "g" }),
    Object.freeze({ field: "fat", label: "Fat", unit: "g" })
  ]);

  function element(documentRef, tagName, className, text) {
    const node = documentRef.createElement(tagName);
    if (className) node.className = className;
    if (text !== undefined && text !== null) node.textContent = String(text);
    return node;
  }

  function labeledInput(documentRef, options) {
    const wrapper = element(documentRef, "label", options.className || "meal-snapshot-review-field");
    const label = element(documentRef, "span", "meal-snapshot-review-label", options.label);
    const input = element(documentRef, "input", "meal-snapshot-review-input");
    input.type = options.type || "text";
    input.value = String(options.value ?? "");
    input.setAttribute("autocomplete", "off");
    input.setAttribute(options.attributeName, options.attributeValue);
    if (options.ingredientId) input.setAttribute("data-ingredient-id", options.ingredientId);
    if (options.inputMode) input.setAttribute("inputmode", options.inputMode);
    if (typeof options.onInput === "function") {
      input.addEventListener("input", () => options.onInput(input.value));
    }
    wrapper.append(label, input);
    return wrapper;
  }

  function reviewButton(documentRef, action, label, callback) {
    const button = element(documentRef, "button", "meal-snapshot-review-action", label);
    button.type = "button";
    button.setAttribute("data-review-action", action);
    if (typeof callback === "function") button.addEventListener("click", callback);
    return button;
  }

  function renderMealSnapshotMockReview(container, draft = {}, options = {}) {
    if (!container || typeof container.replaceChildren !== "function") {
      throw new TypeError("Meal Snapshot review requires a target DOM element.");
    }
    const documentRef = options.documentRef || container.ownerDocument;
    if (!documentRef || typeof documentRef.createElement !== "function") {
      throw new TypeError("Meal Snapshot review requires a document interface.");
    }

    const section = element(documentRef, "section", "meal-snapshot-review");
    section.setAttribute("role", "region");
    section.setAttribute("aria-labelledby", "mealSnapshotReviewTitle");
    section.append(
      element(documentRef, "p", "meal-snapshot-beta-eyebrow", "Meal Snapshot Beta"),
      element(documentRef, "h1", "meal-snapshot-beta-title", "Estimated Meal Snapshot")
    );
    section.children[1].setAttribute("id", "mealSnapshotReviewTitle");
    section.append(
      element(
        documentRef,
        "p",
        "meal-snapshot-review-context",
        "Sample estimate for testing: this data is not based on your photo. Real AI analysis is not connected yet."
      ),
      element(documentRef, "p", "meal-snapshot-beta-estimate-label", draft.confidenceLabel || "Local mock estimate - review required")
    );

    const titleField = labeledInput(documentRef, {
      label: "Meal title",
      value: draft.title,
      attributeName: "data-review-field",
      attributeValue: "title",
      onInput: (value) => options.onEdit?.({ field: "title", value })
    });
    section.append(titleField);

    const macroHeading = element(documentRef, "h2", "meal-snapshot-review-section-title", "Estimated nutrition");
    const macroGrid = element(documentRef, "div", "meal-snapshot-review-macros");
    for (const macro of MACROS) {
      macroGrid.append(labeledInput(documentRef, {
        label: `${macro.label} (${macro.unit})`,
        value: draft[macro.field],
        type: "number",
        inputMode: "decimal",
        className: "meal-snapshot-review-macro",
        attributeName: "data-review-field",
        attributeValue: macro.field,
        onInput: (value) => options.onEdit?.({ field: macro.field, value })
      }));
    }
    section.append(macroHeading, macroGrid);

    const ingredientHeading = element(documentRef, "h2", "meal-snapshot-review-section-title", "Ingredients and portions");
    const ingredientList = element(documentRef, "div", "meal-snapshot-review-ingredients");
    const ingredients = Array.isArray(draft.ingredients) ? draft.ingredients : [];
    for (const ingredient of ingredients) {
      const row = element(documentRef, "div", "meal-snapshot-review-ingredient");
      row.append(
        labeledInput(documentRef, {
          label: "Ingredient",
          value: ingredient.name,
          attributeName: "data-ingredient-field",
          attributeValue: "name",
          ingredientId: String(ingredient.id || ""),
          onInput: (value) => options.onIngredientEdit?.({ id: ingredient.id, field: "name", value })
        }),
        labeledInput(documentRef, {
          label: "Estimated portion",
          value: ingredient.amount,
          attributeName: "data-ingredient-field",
          attributeValue: "amount",
          ingredientId: String(ingredient.id || ""),
          onInput: (value) => options.onIngredientEdit?.({ id: ingredient.id, field: "amount", value })
        })
      );
      ingredientList.append(row);
    }
    section.append(ingredientHeading, ingredientList);

    if (draft.leanerNote) {
      section.append(element(documentRef, "p", "meal-snapshot-review-note", draft.leanerNote));
    }
    const disclaimer = element(documentRef, "p", "meal-snapshot-beta-disclaimer", draft.disclaimer || "");
    disclaimer.setAttribute("role", "note");
    section.append(disclaimer);

    const actions = element(documentRef, "div", "meal-snapshot-review-actions");
    actions.setAttribute("role", "group");
    actions.setAttribute("aria-label", "Local mock review options");
    actions.append(
      reviewButton(documentRef, "reset", "Reset sample", options.onReset),
      reviewButton(documentRef, "back", "Back to photo check", options.onBack)
    );
    section.append(actions);

    container.replaceChildren(section);
    return section;
  }

  return Object.freeze({ renderMealSnapshotMockReview });
}));
