// Inject styles ONCE
if (!document.getElementById("kform-sidebar-style")) {
  const style = document.createElement("style");
  style.id = "kform-sidebar-style";
  style.textContent = `
      #Form label,
  .step-item .label,
  .sidebar .label {
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    width: 100%;
  }


  #Form .sidebar {
    width: 180px;
    background-color: #bae6ee;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 8px;
    position: sticky;
    top: 0;
    right: 0;
    flex-shrink: 0;
    gap: 10px;
    overflow-y: auto;
    border-radius: 0 10px 10px 0;
  }

  #Form .sidebar button {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 6px;
    border: 0;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: 0.18s;
    margin: 0;
    flex: 1 1 0;
    min-height: 48px;
    text-align: center;
    line-height: 1;
    overflow: hidden;
    background-color: #f1f2fd;
    width: 80%;
    box-shadow: rgba(0, 0, 0, 0.6) 0px 3px 8px;
  }

  #Form .sidebar button:hover {
    background-color: #d9f3ff;
  }

  #Form .sidebar button.active {
    background-color: #53d2ff;
    border-color: #7ed2e8;
    font-weight: bold;
  }

  #Form .sidebar button.child {
    margin-right: 20px;
    background-color: #fff7c2 !important;
    width: calc(80% - 20px);
  }

  #Form .sidebar button.child.active {
    background-color: #ffe680 !important;
  }

  #Form .sidebar img {
    display: block;
    width: auto;
    height: auto;
    max-width: 70%;
    max-height: 30px;
    object-fit: contain;
  }

  #Form .sidebar .label {
    font-size: 14px;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100%;
  }

  #Form .content-area {
    flex: 1;
    background-color: #fff;
    padding: 30px 40px;
    overflow-y: auto;
    border-radius: 10px 0 0 10px;
    box-sizing: border-box;
    scrollbar-gutter: stable;
    position: relative;
  }

  #Form .content {
    display: none;
  }

  #Form .content.active {
    display: block;
  }

  #Form .steps {
    display: flex;
    align-items: center;
    gap: 0;
    padding: 18px 12px;
    width: 50%;
    box-sizing: border-box;
    margin: auto;
  }

  #Form .step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 56px;
    z-index: 2;
    cursor: pointer;
    user-select: none;
  }

  #Form .step-item .circle {
    width: 44px;
    height: 44px;
    border-radius: 50%;
    border: 2px solid #9a9a9a;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    font-weight: 600;
    font-size: 14px;
    box-sizing: border-box;
  }

  #Form .step-item .label {
    margin-top: 8px;
    font-size: 13px;
    color: #555;
    white-space: nowrap;
    text-align: center;
  }

  #Form .connector {
    flex: 1 1 auto;
    height: 4px;
    background: #d0d0d0;
    border-radius: 2px;
    margin: 0 8px;
    align-self: center;
    z-index: 1;
    min-width: 28px;
    margin: -25px -30px 0 -30px;
  }

  #Form .step-item.active .circle {
    border-color: #00aaff;
    color: #00aaff;
  }
  #Form .step-item.active .label {
    color: #00aaff;
  }

  #Form .connector.active {
    background: #00aaff;
  }

  #Form .step-content {
    display: none;
    margin-top: 20px;
  }
  #Form .step-content.active {
    display: block;
  }
    #Form input[disabled] {
    color: #444 !important;
    }
    `;
  document.head.appendChild(style);
}
// -------------------------------
// Main dynamic UI builder
// -------------------------------
function createFormUI(config) {
  const container = document.getElementById(config.container);
  if (!container) return console.error("Container not found!");

  //--------------------------
  // Create sidebar
  //--------------------------
  const sidebar = document.createElement("div");
  sidebar.className = "sidebar";

  //--------------------------
  // Create content area
  //--------------------------
  const contentArea = document.createElement("div");
  contentArea.className = "content-area";

  let contentIndex = 1;
  const buttonElements = [];

  config.sidebar.forEach((item, buttonIndex) => {
    // ----------------------------------
    // PARENT BUTTON
    // ----------------------------------
    idx = buttonIndex + 1;
    const parentId = "content-" + contentIndex;

    const btn = createSidebarButton(item.label, item.icon, parentId);
    btn.setAttribute("number", idx);
    btn.addEventListener("click", (event) => {
      event.preventDefault();
    });
    sidebar.appendChild(btn);
    buttonElements.push(btn);

    // create parent content
    const page = createContentPage(parentId, config.steps?.[contentIndex]);
    contentArea.appendChild(page);
    contentIndex++;

    // ----------------------------------
    // CHILDREN?
    // ----------------------------------
    if (item.children) {
      item.children.forEach((child) => {
        const childId = "content-" + contentIndex;

        const childBtn = createSidebarButton(
          child.label,
          child.icon,
          childId,
          true
        );
        childBtn.setAttribute("number", idx);
        childBtn.addEventListener("click", (event) => {
          event.preventDefault();
        });
        sidebar.appendChild(childBtn);
        buttonElements.push(childBtn);

        const childPage = createContentPage(
          childId,
          config.steps?.[contentIndex]
        );
        contentArea.appendChild(childPage);
        contentIndex++;
      });
    }
  });

  //--------------------------
  // Append
  //--------------------------
  container.innerHTML = "";
  container.appendChild(sidebar);
  container.appendChild(contentArea);

  //--------------------------
  // Activation Logic
  //--------------------------
  const contents = container.querySelectorAll(".content");
  buttonElements[0].classList.add("active"); // first highlighted
  contents[0].classList.add("active");

  buttonElements.forEach((btn) => {
    btn.addEventListener("click", () => {
      // If clicking a parent button (group)
      if (!btn.classList.contains("child")) {
        const firstChild = container.querySelector(
          `button.child[number='${btn.getAttribute("number")}']`
        );
        if (firstChild) {
          firstChild.click(); // simulate click
          return; // STOP HERE
        }
      }

      // Normal click logic (children + single buttons)
      buttonElements.forEach((b) => b.classList.remove("active"));
      contents.forEach((c) => c.classList.remove("active"));

      btn.classList.add("active");
      document.getElementById(btn.dataset.target).classList.add("active");

      // If child → activate parent visually
      if (btn.classList.contains("child")) {
        const parentBtn = container.querySelector(
          `button[number='${btn.getAttribute("number")}']:not(.child)`
        );
        if (parentBtn) parentBtn.classList.add("active");
      }
    });
  });
}

//----------------------------------
// Create one sidebar button
//----------------------------------
function createSidebarButton(label, icon, target, isChild = false) {
  const btn = document.createElement("button");
  btn.dataset.target = target;
  if (isChild) {
    btn.classList.add("child");
  }

  const img = document.createElement("img");
  img.src = icon;
  img.alt = label;

  const span = document.createElement("span");
  span.className = "label";
  span.textContent = label;

  btn.appendChild(img);
  btn.appendChild(span);

  return btn;
}

//----------------------------------
// Create 1 tab page + steps
//----------------------------------
function createContentPage(id, stepsData) {
  const page = document.createElement("div");
  page.className = "content";
  page.id = id;

  if (stepsData) page.appendChild(createSteps(id, stepsData));

  return page;
}

// -------------------------------
// Step Section Creator
// -------------------------------
function createSteps(tabId, stepLabels) {
  const wrapper = document.createElement("div");

  // Step header
  const stepsContainer = document.createElement("div");
  stepsContainer.className = "steps";

  stepLabels.forEach((label, i) => {
    const stepItem = document.createElement("div");
    stepItem.className = "step-item";
    stepItem.dataset.step = i + 1;
    if (i === 0) stepItem.classList.add("active");

    stepItem.innerHTML = `
        <div class="circle">${i + 1}</div>
        <div class="label">${label}</div>
      `;

    stepsContainer.appendChild(stepItem);

    if (i < stepLabels.length - 1) {
      const connector = document.createElement("div");
      connector.className = "connector";
      stepsContainer.appendChild(connector);
    }
  });

  wrapper.appendChild(stepsContainer);

  // Step content area
  const contentWrapper = document.createElement("div");
  contentWrapper.className = "step-contents";

  stepLabels.forEach((label, i) => {
    const stepDiv = document.createElement("div");
    stepDiv.className = "step-content";
    stepDiv.dataset.step = i + 1;
    stepDiv.id = `${tabId}-step-${i + 1}`;
    if (i === 0) stepDiv.classList.add("active");
    contentWrapper.appendChild(stepDiv);
  });

  wrapper.appendChild(contentWrapper);

  // Navigation logic
  const stepBtns = wrapper.querySelectorAll(".step-item");
  const connectors = wrapper.querySelectorAll(".connector");
  const stepContents = wrapper.querySelectorAll(".step-content");

  stepBtns.forEach((stepBtn, idx) => {
    stepBtn.addEventListener("click", () => {
      stepBtns.forEach((s) => s.classList.remove("active"));
      connectors.forEach((c) => c.classList.remove("active"));
      stepContents.forEach((sc) => sc.classList.remove("active"));

      stepBtn.classList.add("active");

      // Activate connectors
      for (let i = 0; i < idx; i++) {
        connectors[i].classList.add("active");
        stepBtns[i].classList.add("active");
      }
      stepContents[idx].classList.add("active");
    });
  });

  return wrapper;
}

// ================================
// FORM NAVIGATION CORE
// ================================

function getForm() {
  return document.getElementById("Form");
}

function getActiveContent(form) {
  return form.querySelector(".content.active");
}

function getSidebarButtons(form) {
  return [...form.querySelectorAll(".sidebar button")];
}

function getActiveButton(form) {
  return (
    form.querySelector(".sidebar button.active:not(.child)") ||
    form.querySelector(".sidebar button.active")
  );
}

// -------------------------------
// STEP HELPERS
// -------------------------------

function getStepData(content) {
  const steps = [...content.querySelectorAll(".step-item")];
  const connectors = [...content.querySelectorAll(".connector")];
  const stepContents = [...content.querySelectorAll(".step-content")];

  const activeIndex = [...steps]
    .map((s, i) => (s.classList.contains("active") ? i : -1))
    .filter((i) => i !== -1)
    .pop();

  return { steps, connectors, stepContents, activeIndex };
}

function activateStep(content, index) {
  const { steps, connectors, stepContents } = getStepData(content);

  steps.forEach((s) => s.classList.remove("active"));
  connectors.forEach((c) => c.classList.remove("active"));
  stepContents.forEach((sc) => sc.classList.remove("active"));

  steps[index].classList.add("active");
  stepContents[index].classList.add("active");

  for (let i = 0; i < index; i++) {
    steps[i].classList.add("active");
    connectors[i]?.classList.add("active");
  }
}

// -------------------------------
// TAB HELPERS
// -------------------------------

function activateTab(form, btn) {
  const buttons = getSidebarButtons(form);
  const contents = [...form.querySelectorAll(".content")];

  buttons.forEach((b) => b.classList.remove("active"));
  contents.forEach((c) => c.classList.remove("active"));

  btn.classList.add("active");
  document.getElementById(btn.dataset.target).classList.add("active");

  // if child → highlight parent
  if (btn.classList.contains("child")) {
    const parent = form.querySelector(
      `button[number='${btn.getAttribute("number")}']:not(.child)`
    );
    parent?.classList.add("active");
  }
}

// -------------------------------
// FORWARD
// -------------------------------

function goForward() {
  const form = getForm();
  if (!form) return;

  const content = getActiveContent(form);
  if (!content) return;

  const { steps, activeIndex } = getStepData(content);

  // Next step
  if (activeIndex < steps.length - 1) {
    activateStep(content, activeIndex + 1);
    return;
  }

  // Next tab
  const buttons = getSidebarButtons(form);
  const activeBtn = getActiveButton(form);
  const nextBtn = buttons[buttons.indexOf(activeBtn) + 1];

  if (!nextBtn) return;

  activateTab(form, nextBtn);

  const nextContent = getActiveContent(form);
  if (!nextContent) return;

  activateStep(nextContent, 0);
}

// -------------------------------
// BACKWARD
// -------------------------------

function goBackward() {
  const form = getForm();
  if (!form) return;

  const content = getActiveContent(form);
  if (!content) return;

  const { activeIndex } = getStepData(content);

  // Previous step
  if (activeIndex > 0) {
    activateStep(content, activeIndex - 1);
    return;
  }

  // Previous tab
  const buttons = getSidebarButtons(form);
  const activeBtn = getActiveButton(form);
  const prevBtn = buttons[buttons.indexOf(activeBtn) - 1];

  if (!prevBtn) return;

  activateTab(form, prevBtn);

  const prevContent = getActiveContent(form);
  if (!prevContent) return;

  const lastIndex = prevContent.querySelectorAll(".step-item").length - 1;

  activateStep(prevContent, lastIndex);
}
