(function () {
  console.log("[WebAppClone] LoadEnd ultra compact export start");

  /*
    WebAppClone LoadEnd.txt ultra compact version

    方針:
    - 元DOMを cloneNode しない
    - AI解析に必要な画面構造だけを軽量HTMLとして再構成
    - computed style は最小限のみ取得
    - 位置、サイズ、色、背景色、文字サイズ、太字、枠線程度
    - script/style/svg/img/nav/header/footer 等は除外
    - 結果は window.__WEBAPPCLONE_VIRTUAL_HTML__ に保存
  */

  const MAX_TEXT = 80;
  const MAX_ATTR = 120;
  const MAX_VALUE = 120;
  const MAX_ELEMENTS = 800;
  const MAX_OUTPUT = 120000;

  function s(v) {
    if (v === undefined || v === null) return "";
    return String(v);
  }

  function cut(v, n) {
    v = s(v).replace(/\s+/g, " ").trim();
    if (v.length > n) return v.substring(0, n);
    return v;
  }

  function esc(v) {
    return s(v)
      .replace(/&/g, "&amp;")
      .replace(/"/g, "&quot;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;");
  }

  function attr(name, value) {
    value = s(value);
    if (value === "") return "";
    return " " + name + "=\"" + esc(value) + "\"";
  }

  function isSensitiveName(v) {
    v = s(v).toLowerCase();
    return (
      v.indexOf("password") >= 0 ||
      v.indexOf("passwd") >= 0 ||
      v.indexOf("pwd") >= 0 ||
      v.indexOf("token") >= 0 ||
      v.indexOf("csrf") >= 0 ||
      v.indexOf("xsrf") >= 0 ||
      v.indexOf("cookie") >= 0 ||
      v.indexOf("session") >= 0 ||
      v.indexOf("secret") >= 0 ||
      v.indexOf("auth") >= 0
    );
  }

  function roleOf(el) {
    const tag = el.tagName ? el.tagName.toLowerCase() : "";
    const type = (el.getAttribute("type") || "").toLowerCase();
    const role = (el.getAttribute("role") || "").toLowerCase();

    if (role) return role;

    if (tag === "input") {
      if (type === "button" || type === "submit" || type === "reset") return "button";
      if (type === "checkbox") return "checkbox";
      if (type === "radio") return "radio";
      if (type === "hidden") return "hidden";
      if (type === "password") return "password";
      if (type === "search") return "search";
      if (type === "email") return "email";
      if (type === "number") return "number";
      if (type === "date") return "date";
      return "input";
    }

    if (tag === "textarea") return "textarea";
    if (tag === "select") return "select";
    if (tag === "button") return "button";
    if (tag === "a") return "link";
    if (tag === "label") return "label";
    if (tag === "form") return "form";
    if (tag === "table") return "table";
    if (tag === "tr") return "row";
    if (tag === "th") return "header-cell";
    if (tag === "td") return "cell";

    if (/^h[1-6]$/.test(tag)) return "heading";

    return "";
  }

  function skipTag(tag) {
    return (
      tag === "script" ||
      tag === "style" ||
      tag === "noscript" ||
      tag === "meta" ||
      tag === "link" ||
      tag === "template" ||
      tag === "svg" ||
      tag === "canvas" ||
      tag === "iframe" ||
      tag === "img" ||
      tag === "nav" ||
      tag === "header" ||
      tag === "footer" ||
      tag === "aside"
    );
  }

  function textOf(el, tag) {
    if (
      tag !== "label" &&
      tag !== "button" &&
      tag !== "th" &&
      tag !== "td" &&
      tag !== "span" &&
      tag !== "p" &&
      tag !== "a" &&
      tag !== "li" &&
      !/^h[1-6]$/.test(tag)
    ) {
      return "";
    }

    try {
      return cut(el.innerText || el.textContent || "", MAX_TEXT);
    } catch (e) {
      return "";
    }
  }

  function hasImportantChild(el) {
    try {
      return !!el.querySelector("form,input,textarea,select,button,table,tr,th,td,label,h1,h2,h3,h4,h5,h6");
    } catch (e) {
      return false;
    }
  }

  function isVisible(rect, cs) {
    if (!rect) return false;
    if (rect.width <= 0 || rect.height <= 0) return false;
    if (!cs) return true;
    if (cs.display === "none") return false;
    if (cs.visibility === "hidden") return false;
    if (cs.opacity === "0") return false;
    return true;
  }

  function styleMini(el, cs) {
    const parts = [];

    function add(prop, value) {
      value = s(value).trim();
      if (value === "") return;
      if (value === "normal") return;
      if (value === "none") return;
      if (value === "auto") return;
      if (value === "0") return;
      if (value === "0px") return;
      if (value === "rgba(0, 0, 0, 0)") return;
      if (value === "transparent") return;
      parts.push(prop + ":" + value);
    }

    try {
      add("color", cs.getPropertyValue("color"));
      add("bg", cs.getPropertyValue("background-color"));
      add("fs", cs.getPropertyValue("font-size"));
      add("fw", cs.getPropertyValue("font-weight"));
      add("ta", cs.getPropertyValue("text-align"));

      const bw = cs.getPropertyValue("border-top-width");
      const bs = cs.getPropertyValue("border-top-style");
      const bc = cs.getPropertyValue("border-top-color");

      if (bw && bw !== "0px" && bs && bs !== "none") {
        add("border", bw + " " + bs + " " + bc);
      }

      const br = cs.getPropertyValue("border-radius");
      add("radius", br);
    } catch (e) {
    }

    return parts.join(";");
  }

  function valueInfo(el, tag, type) {
    try {
      const keyName = el.getAttribute("name") || el.getAttribute("id") || "";

      if (isSensitiveName(keyName)) return "";

      if (tag === "input") {
        if (type === "password" || type === "hidden") return "";
        if (type === "checkbox" || type === "radio") {
          return el.checked ? "checked" : "";
        }
        return cut(el.value || "", MAX_VALUE);
      }

      if (tag === "textarea") {
        return cut(el.value || "", MAX_VALUE);
      }

      if (tag === "select") {
        const opt = el.options[el.selectedIndex];
        if (!opt) return "";
        return cut(opt.text || opt.value || "", MAX_VALUE);
      }
    } catch (e) {
    }

    return "";
  }

  function optionInfo(el) {
    try {
      if (!el || el.tagName.toLowerCase() !== "select") return "";

      const arr = [];
      const opts = el.querySelectorAll("option");

      for (let i = 0; i < opts.length && i < 20; i++) {
        const t = cut(opts[i].innerText || opts[i].textContent || opts[i].value || "", 40);
        if (t) arr.push(t);
      }

      return arr.join("|");
    } catch (e) {
      return "";
    }
  }

  function build() {
    const nodes = document.documentElement.querySelectorAll("*");
    const out = [];

    let count = 0;

    out.push("<!DOCTYPE html>");
    out.push("<html");
    out.push(attr("data-wac-mode", "ultra-compact"));
    out.push(attr("data-wac-url", location.href));
    out.push(attr("data-wac-title", document.title || ""));
    out.push(attr("data-wac-vw", window.innerWidth));
    out.push(attr("data-wac-vh", window.innerHeight));
    out.push(">");
    out.push("<body>");

    for (let i = 0; i < nodes.length; i++) {
      if (count >= MAX_ELEMENTS) break;

      const el = nodes[i];
      const tag = el.tagName ? el.tagName.toLowerCase() : "";

      if (!tag || skipTag(tag)) continue;

      let rect = null;
      let cs = null;

      try {
        rect = el.getBoundingClientRect();
        cs = window.getComputedStyle(el);
      } catch (e) {
        continue;
      }

      if (!isVisible(rect, cs)) continue;

      const role = roleOf(el);
      const text = textOf(el, tag);

      const important =
        role ||
        text ||
        tag === "form" ||
        tag === "input" ||
        tag === "textarea" ||
        tag === "select" ||
        tag === "button" ||
        tag === "table" ||
        tag === "tr" ||
        tag === "th" ||
        tag === "td" ||
        tag === "label" ||
        /^h[1-6]$/.test(tag) ||
        ((tag === "div" || tag === "section" || tag === "main") && hasImportantChild(el));

      if (!important) continue;

      const x = Math.round(rect.x);
      const y = Math.round(rect.y);
      const w = Math.round(rect.width);
      const h = Math.round(rect.height);

      const id = cut(el.getAttribute("id") || "", MAX_ATTR);
      const name = cut(el.getAttribute("name") || "", MAX_ATTR);
      const type = cut(el.getAttribute("type") || "", MAX_ATTR);
      const placeholder = cut(el.getAttribute("placeholder") || "", MAX_ATTR);
      const aria = cut(el.getAttribute("aria-label") || "", MAX_ATTR);
      const title = cut(el.getAttribute("title") || "", MAX_ATTR);
      const href = cut(el.getAttribute("href") || "", MAX_ATTR);

      const val = valueInfo(el, tag, type.toLowerCase());
      const opts = optionInfo(el);
      const st = styleMini(el, cs);

      let line = "<div";
      line += attr("data-i", count);
      line += attr("data-tag", tag);
      line += attr("data-role", role);
      line += attr("data-x", x);
      line += attr("data-y", y);
      line += attr("data-w", w);
      line += attr("data-h", h);

      if (id && !isSensitiveName(id)) line += attr("data-id", id);
      if (name && !isSensitiveName(name)) line += attr("data-name", name);
      if (type) line += attr("data-type", type);
      if (placeholder) line += attr("data-placeholder", placeholder);
      if (aria) line += attr("data-aria", aria);
      if (title) line += attr("data-title", title);
      if (href && href.indexOf("javascript:") !== 0) line += attr("data-href", href);
      if (val) line += attr("data-value", val);
      if (opts) line += attr("data-options", opts);
      if (st) line += attr("data-style", st);

      line += ">";

      if (text) line += esc(text);

      line += "</div>";

      out.push(line);
      count++;
    }

    out.push("</body>");
    out.push("</html>");

    let html = out.join("\n");

    if (html.length > MAX_OUTPUT) {
      html = html.substring(0, MAX_OUTPUT) + "\n<!-- WEBAPPCLONE_TRUNCATED -->";
    }

    return {
      html: html,
      count: count,
      length: html.length
    };
  }

  try {
    const result = build();

    window.__WEBAPPCLONE_VIRTUAL_HTML__ = result.html;
    window.__WEBAPPCLONE_META__ = {
      version: "2.0",
      mode: "ultra-compact",
      url: location.href,
      title: document.title || "",
      viewportWidth: window.innerWidth,
      viewportHeight: window.innerHeight,
      collectedElements: result.count,
      htmlLength: result.length,
      createdAt: new Date().toISOString()
    };
    window.__WEBAPPCLONE_COLLECTED_ELEMENTS__ = result.count;
    window.__WEBAPPCLONE_DONE__ = true;
    window.__WEBAPPCLONE_ERROR__ = "";

    console.log("[WebAppClone] LoadEnd ultra compact export done:", result.count, result.length);

    return "WEBAPPCLONE_OK:" + String(result.count) + ":" + String(result.length);
  } catch (e) {
    console.log("[WebAppClone] LoadEnd ultra compact fatal error:", e);

    window.__WEBAPPCLONE_VIRTUAL_HTML__ = "";
    window.__WEBAPPCLONE_META__ = {
      version: "2.0",
      mode: "error",
      url: location.href,
      title: document.title || "",
      error: String(e && e.message ? e.message : e)
    };
    window.__WEBAPPCLONE_COLLECTED_ELEMENTS__ = 0;
    window.__WEBAPPCLONE_DONE__ = false;
    window.__WEBAPPCLONE_ERROR__ = String(e && e.message ? e.message : e);

    return "WEBAPPCLONE_ERROR:" + String(e && e.message ? e.message : e);
  }
})();