export type TCreateExportStaticHtmlSnippetOptions = {
  embeddedConfigJson: string;
  runtimeScriptPath: string;
  runtimeVersion?: string;
  mountNodeId?: string;
  configScriptId?: string;
  projectId: string;
  projectSlug: string;
  projectUpdatedAt: string;
  themePreset?: string | null;
  xpressuiVersion: string;
  configuredSuccessMessage?: string;
  configuredErrorMessage?: string;
  wordpressRestSubmitRoute: string;
  wordpressRestSubmitEndpointPlaceholder: string;
};

export function createExportStaticHtmlSnippet(options: TCreateExportStaticHtmlSnippetOptions): string {
  const mountNodeId = options.mountNodeId ?? 'xpressui-root';
  const configScriptId = options.configScriptId ?? 'xpressui-form-config';

  return [
    `<div id="${mountNodeId}"></div>`,
    `<script type="application/json" id="${configScriptId}">`,
    options.embeddedConfigJson,
    '</script>',
    `<script src="./${options.runtimeScriptPath}"></script>`,
    '<script type="module">',
    `  const mountNode = document.getElementById('${mountNodeId}');`,
    `  const configNode = document.getElementById('${configScriptId}');`,
    "  const feedbackNode = document.querySelector('[data-submit-feedback]');",
    "  const feedbackMessageNode = document.querySelector('[data-submit-feedback-message]');",
    "  const feedbackTitleNode = document.querySelector('.template-submit-feedback-title');",
    "  const submitRowNode = document.querySelector('[data-template-zone=\"submit_actions\"]');",
    "  const stepActionsNode = document.querySelector('[data-form-step-actions]');",
    "  const formElement = mountNode?.querySelector('form');",
    '  const runtimeApi = window.XPressUI || window.xpressui || {};',
    `  const configuredSuccessMessage = ${JSON.stringify(options.configuredSuccessMessage ?? '')};`,
    `  const configuredErrorMessage = ${JSON.stringify(options.configuredErrorMessage ?? '')};`,
    "  const defaultSuccessMessage = 'Submission received.';",
    "  const defaultErrorMessage = 'Submission failed. Please review the form and try again.';",
    '',
    '  const fallbackSyncPostSubmitUi = (state) => {',
    '    const hideActions = state === "success";',
    '    if (submitRowNode instanceof HTMLElement) {',
    '      submitRowNode.style.display = hideActions ? "none" : "";',
    '    }',
    '    if (stepActionsNode instanceof HTMLElement) {',
    '      stepActionsNode.style.display = hideActions ? "none" : "";',
    '    }',
    '  };',
    '',
    '  const applyShellFeedbackState = (state, message, title = "Submission status") => {',
    '    if (mountNode instanceof HTMLElement && typeof runtimeApi.setShellFeedbackState === "function") {',
    '      runtimeApi.setShellFeedbackState(mountNode, state, message, title);',
    '    } else {',
    '      if (feedbackNode instanceof HTMLElement) {',
    "        feedbackNode.style.display = '';",
    '        feedbackNode.dataset.submitFeedbackState = state;',
    '      }',
    '      if (feedbackTitleNode instanceof HTMLElement) {',
    '        feedbackTitleNode.textContent = title;',
    '      }',
    '      if (feedbackMessageNode instanceof HTMLElement) {',
    '        feedbackMessageNode.textContent = message;',
    '      }',
    '    }',
    '    if (mountNode instanceof HTMLElement && typeof runtimeApi.syncShellPostSubmitUi === "function") {',
    '      runtimeApi.syncShellPostSubmitUi(mountNode, state);',
    '    } else {',
    '      fallbackSyncPostSubmitUi(state);',
    '    }',
    '  };',
    '',
    '  const buildSubmissionId = () => {',
    "    const alphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';",
    '    const encodeTime = (value, length) => {',
    "      let result = '';",
    '      let nextValue = value;',
    '      for (let index = 0; index < length; index += 1) {',
    '        result = alphabet[nextValue % 32] + result;',
    '        nextValue = Math.floor(nextValue / 32);',
    '      }',
    '      return result;',
    '    };',
    '    const randomValues = new Uint8Array(16);',
    '    if (window.crypto?.getRandomValues) {',
    '      window.crypto.getRandomValues(randomValues);',
    '    } else {',
    '      for (let index = 0; index < randomValues.length; index += 1) {',
    '        randomValues[index] = Math.floor(Math.random() * 256);',
    '      }',
    '    }',
    "    let randomPart = '';",
    '    for (let index = 0; index < 16; index += 1) {',
    '      randomPart += alphabet[randomValues[index] % 32];',
    '    }',
    '    return `${encodeTime(Date.now(), 10)}${randomPart}`;',
    '  };',
    '',
    '  const projectConfigSnapshot = JSON.parse(configNode?.textContent || "{}");',
    '',
    '  const resolveWordPressRestEndpoint = () => {',
    '    if (window.location.protocol === "file:" || !["http:", "https:"].includes(window.location.protocol)) {',
    '      return "";',
    '    }',
    '    if (typeof window.XPRESSUI_WORDPRESS_REST_URL === "string" && window.XPRESSUI_WORDPRESS_REST_URL.trim() !== "") {',
    '      return window.XPRESSUI_WORDPRESS_REST_URL;',
    '    }',
    '    const apiRootLink = document.querySelector(\'link[rel="https://api.w.org/"]\');',
    '    const apiRootHref = apiRootLink instanceof HTMLLinkElement ? apiRootLink.href : "";',
    '    if (apiRootHref) {',
    `      return new URL(${JSON.stringify(options.wordpressRestSubmitRoute)}, apiRootHref).toString();`,
    '    }',
    '    const currentUrl = new URL(window.location.href);',
    '    const contentIndex = currentUrl.pathname.indexOf("/wp-content/");',
    '    const sitePath = contentIndex >= 0 ? currentUrl.pathname.slice(0, contentIndex) : "";',
    '    const basePath = sitePath ? `${sitePath.replace(/\\/$/, "")}/` : "/";',
    `    return new URL(\`${'${basePath}'}?rest_route=/${options.wordpressRestSubmitRoute}\`, currentUrl.origin).toString();`,
    '  };',
    '',
    '  const collectSubmitterVerificationToken = (values) => {',
    '    const enrichedValues = { ...(values || {}) };',
    '    const tokenInput = document.querySelector("[data-submitter-verification-token]");',
    '    if (tokenInput instanceof HTMLInputElement && tokenInput.name && tokenInput.value) {',
    '      enrichedValues[tokenInput.name] = tokenInput.value;',
    '    }',
    '    return enrichedValues;',
    '  };',
    '',
    '  const ensureSubmitMetadata = (values) => ({',
    '    ...collectSubmitterVerificationToken(values),',
    `    projectId: ${JSON.stringify(options.projectId)},`,
    `    projectSlug: ${JSON.stringify(options.projectSlug)},`,
    `    projectConfigVersion: ${JSON.stringify(`${options.projectId}:${options.projectUpdatedAt}`)},`,
    '    submissionId: values?.submissionId || buildSubmissionId(),',
    '    projectConfigSnapshotJson: JSON.stringify(projectConfigSnapshot),',
    '  });',
    '',
    '  const attachFallbackSubmitHandler = (form) => {',
    '    if (!(form instanceof HTMLFormElement) || form.dataset.xpressuiFallbackSubmitAttached === "true") {',
    '      return;',
    '    }',
    '    form.dataset.xpressuiFallbackSubmitAttached = "true";',
    '    form.addEventListener("submit", async (event) => {',
    '      event.preventDefault();',
    '      const formData = new FormData(form);',
    '      if (!formData.get("submissionId")) {',
    '        formData.append("submissionId", buildSubmissionId());',
    '      }',
    `      if (!formData.get("projectId")) { formData.append("projectId", ${JSON.stringify(options.projectId)}); }`,
    `      if (!formData.get("projectSlug")) { formData.append("projectSlug", ${JSON.stringify(options.projectSlug)}); }`,
    `      if (!formData.get("projectConfigVersion")) { formData.append("projectConfigVersion", ${JSON.stringify(`${options.projectId}:${options.projectUpdatedAt}`)}); }`,
    '      if (!formData.get("projectConfigSnapshotJson")) {',
    '        formData.append("projectConfigSnapshotJson", JSON.stringify(projectConfigSnapshot));',
    '      }',
    '      applyShellFeedbackState("loading", "Submitting...", "Submitting");',
    '      try {',
    '        const submitEndpoint = typeof formConfig.submit?.endpoint === "string" && formConfig.submit.endpoint',
    '          ? formConfig.submit.endpoint',
    '          : resolveWordPressRestEndpoint();',
    '        if (!submitEndpoint) {',
    '          throw new Error("Missing WordPress submit endpoint. Open this package inside WordPress or define XPRESSUI_WORDPRESS_REST_URL.");',
    '        }',
    '        const response = await fetch(submitEndpoint, {',
    '          method: (form.method || "POST").toUpperCase(),',
    '          body: formData,',
    '          headers: { Accept: "application/json" },',
    '        });',
    '        const responseText = await response.text();',
    '        let result = null;',
    '        try {',
    '          result = responseText ? JSON.parse(responseText) : null;',
    '        } catch {',
    '          result = null;',
    '        }',
    '        if (!response.ok) {',
    '          throw new Error(result?.message || `Submit failed with status ${response.status}.`);',
    '        }',
    '        applyShellFeedbackState("success", configuredSuccessMessage || result?.message || defaultSuccessMessage, "Submission received");',
    '        if (typeof runtimeApi.handleShellSuccessRedirect === "function") {',
    '          runtimeApi.handleShellSuccessRedirect(result, formConfig);',
    '        }',
    '      } catch (error) {',
    '        console.error(error);',
    '        const message = typeof runtimeApi.resolveShellSubmitErrorMessage === "function"',
    '          ? runtimeApi.resolveShellSubmitErrorMessage(null, error, configuredErrorMessage, defaultErrorMessage)',
    '          : (configuredErrorMessage || (error instanceof Error ? error.message : "") || defaultErrorMessage);',
    '        applyShellFeedbackState("error", message, "Submission failed");',
    '      }',
    '    });',
    '  };',
    '',
    '  if (!configNode) {',
    "    throw new Error('Missing embedded form config.');",
    '  }',
    '  const formConfig = projectConfigSnapshot;',
    '  formConfig.submit = formConfig.submit || {};',
    `  if (!formConfig.submit.endpoint || formConfig.submit.endpoint === ${JSON.stringify(options.wordpressRestSubmitEndpointPlaceholder)}) {`,
    '    const resolvedEndpoint = resolveWordPressRestEndpoint();',
    '    if (resolvedEndpoint) {',
    '      formConfig.submit.endpoint = resolvedEndpoint;',
    '    }',
    '  }',
    '  const hydrateForm = window.hydrateForm',
    '    || window.XPressUI?.hydrateForm',
    '    || window.xpressui?.hydrateForm;',
    '  if (typeof hydrateForm !== "function") {',
    "    throw new Error('Missing bundled XPressUI runtime.');",
    '  }',
    '  try {',
    '    const hydrated = hydrateForm(mountNode, formConfig);',
    '    if (!hydrated) {',
    "      throw new Error('XPressUI runtime could not hydrate the exported form shell.');",
    '    }',
    '    if (hydrated.formConfig) {',
    '      hydrated.formConfig.submit = hydrated.formConfig.submit || {};',
    '      hydrated.formConfig.submit.lifecycle = hydrated.formConfig.submit.lifecycle || {};',
    '      hydrated.formConfig.submit.lifecycle.preSubmit = ({ values }) => ensureSubmitMetadata(values);',
    '    }',
    '    if (mountNode instanceof HTMLElement && typeof runtimeApi.attachShellFeedbackHandlers === "function") {',
    '      runtimeApi.attachShellFeedbackHandlers(mountNode, formConfig);',
    '    }',
    '  } catch (error) {',
    '    console.error(error);',
    '    attachFallbackSubmitHandler(formElement);',
    '    applyShellFeedbackState("warning", error instanceof Error ? error.message : "Runtime hydration failed. Native browser fallback is active.", "Runtime warning");',
    '  }',
    '</script>',
    `<!-- Bundled runtime: ${options.runtimeScriptPath}${options.runtimeVersion ? ` (${options.runtimeVersion})` : ''} -->`,
    `<!-- Theme preset: ${options.themePreset ?? 'console-clean'} -->`,
    `<!-- Generated for ${options.projectSlug} targeting XPressUI ${options.xpressuiVersion} -->`,
  ].join('\n');
}
