document.addEventListener("DOMContentLoaded", function () {
  // ========== SETTINGS ==========
  const SETTINGS = {
    goldPercentage: 18,
    hallmarks: [375, 583, 750, 875, 916, 999],
    hallmarkPrices: {
      375: 400,
      583: 64,
      750: 82,
      875: 96,
      916: 100,
      999: 510
    },
    limits: {
      gram: { min: 1, max: 1000 },
      month: { min: 1, max: 36 },
      credit: { min: 1, max: 5000 }
    }
  };

  const calcForm = document.getElementById("loanCalcForm");
  if (!calcForm) return;

  let currentItemIndex = 1;

  // ========== TAB SWITCHING ==========
  const tabBtns = document.querySelectorAll("[data-calc-tab]");
  tabBtns.forEach(btn => {
    btn.addEventListener("click", () => {
      tabBtns.forEach(b => b.classList.remove("active"));
      btn.classList.add("active");
      const tabName = btn.getAttribute("data-calc-tab");

      document.querySelectorAll("[data-calc-panel]").forEach(panel => {
        panel.style.display = panel.getAttribute("data-calc-panel") === tabName ? "" : "none";
      });
      calculateAll();
    });
  });

  // ========== RENDER HALLMARKS ==========
  function renderHallmarks() {
    document.querySelectorAll(".hallmark-options").forEach((container, containerIdx) => {
      const formName = container.getAttribute("data-form-name");
      container.innerHTML = "";
      SETTINGS.hallmarks.forEach((hm, i) => {
        const price = SETTINGS.hallmarkPrices[hm];
        const id = `hm_${containerIdx}_${i}`;
        container.innerHTML += `
          <input type="radio" name="${formName}" value="${price}" ${i === 0 ? "checked" : ""} id="${id}">
          <label for="${id}">${hm}</label>
        `;
      });
    });
  }

  // ========== SETUP RANGE + INPUT SYNC ==========
  function setupRangeInputs(scope) {
    const rangeInputs = scope.querySelectorAll(".calc-range[data-unit]");
    rangeInputs.forEach(range => {
      const box = range.parentElement.querySelector(".calc-input-box");
      const valueInput = box.querySelector(".calc-input-value");
      const unitSpan = box.querySelector(".calc-unit");

      valueInput.value = range.value;
      unitSpan.textContent = range.getAttribute("data-unit");
      adjustWidth(valueInput);
      updateRangeBg(range);

      // Range → input
      range.addEventListener("input", () => {
        valueInput.value = range.value;
        adjustWidth(valueInput);
        updateRangeBg(range);
        calculateAll();
      });

      // Input → range
      valueInput.addEventListener("input", () => {
        let val = parseInt(valueInput.value);
        if (isNaN(val)) return;
        val = Math.min(val, parseInt(range.max));
        val = Math.max(val, parseInt(range.min));
        range.value = val;
        adjustWidth(valueInput);
        updateRangeBg(range);
        calculateAll();
      });

      valueInput.addEventListener("blur", () => {
        let val = parseInt(valueInput.value);
        if (isNaN(val) || val < parseInt(range.min)) val = parseInt(range.min);
        if (val > parseInt(range.max)) val = parseInt(range.max);
        valueInput.value = val;
        range.value = val;
        adjustWidth(valueInput);
        updateRangeBg(range);
        calculateAll();
      });

      // Click on box focuses input
      box.addEventListener("click", () => valueInput.focus());
    });
  }

  function adjustWidth(input) {
    input.style.width = `${Math.max(2, String(input.value).length + 1)}ch`;
  }

  function updateRangeBg(range) {
    const pct = ((range.value - range.min) / (range.max - range.min)) * 100;
    const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
    const trackBg = isDark ? 'rgba(255,255,255,0.1)' : '#ddd';
    range.style.background = `linear-gradient(to right, var(--brand) ${pct}%, ${trackBg} ${pct}%)`;
  }

  // ========== ANNUITY CALCULATION ==========
  function calcMonthlyPayment(period, amount) {
    const r = SETTINGS.goldPercentage / 12 / 100;
    const compounded = Math.pow(1 + r, period);
    return ((r * compounded) / (compounded - 1)) * amount;
  }

  // ========== CALCULATE ALL ==========
  function calculateAll() {
    // Hallmark tab
    const hallmarkItems = document.querySelectorAll('[data-calc-panel="hallmarkTab"] .calc-item');
    let totalLoan = 0;
    let totalMonthly = 0;

    hallmarkItems.forEach(item => {
      const hallmarkInput = item.querySelector('.hallmark-options input[type="radio"]:checked');
      const goldWeightRange = item.querySelector('.goldWeightRange');
      const creditPeriodRange = item.querySelector('.creditPeriodRange');

      if (hallmarkInput && goldWeightRange && creditPeriodRange) {
        const price = parseFloat(hallmarkInput.value);
        const weight = parseFloat(goldWeightRange.value);
        const period = parseFloat(creditPeriodRange.value);
        const loan = price * weight;
        totalLoan += loan;
        totalMonthly += calcMonthlyPayment(period, loan);
      }
    });

    const loanAmountEl = document.getElementById("loanAmount");
    const monthlyEl = document.getElementById("monthlyPayment");
    if (loanAmountEl) loanAmountEl.textContent = totalLoan.toFixed(2);
    if (monthlyEl) monthlyEl.textContent = totalMonthly.toFixed(2);

    // Price tab
    const pricePanel = document.querySelector('[data-calc-panel="priceTab"]');
    if (pricePanel) {
      const hallmarkInput = pricePanel.querySelector('.hallmark-options input[type="radio"]:checked');
      const amountRange = pricePanel.querySelector('.creditRangeLimit');
      const periodRange = pricePanel.querySelector('.creditPeriodRange');

      if (hallmarkInput && amountRange && periodRange) {
        const price = parseFloat(hallmarkInput.value);
        const amount = parseFloat(amountRange.value);
        const period = parseFloat(periodRange.value);

        const goldWeightResultEl = document.getElementById("goldWeightResult");
        const priceMonthlyEl = document.getElementById("priceMonthlyPayment");

        if (price && amount && period) {
          if (goldWeightResultEl) goldWeightResultEl.textContent = (amount / price).toFixed(3);
          if (priceMonthlyEl) priceMonthlyEl.textContent = calcMonthlyPayment(period, amount).toFixed(2);
        }
      }
    }

    // Re-bind hallmark change events
    document.querySelectorAll('.hallmark-options input[type="radio"]').forEach(inp => {
      inp.removeEventListener("change", calculateAll);
      inp.addEventListener("change", calculateAll);
    });
  }

  // ========== ADD MORE GOLD ==========
  function setupAddMore() {
    const addBtn = document.getElementById("addMoreGold");
    if (!addBtn) return;

    addBtn.addEventListener("click", () => {
      // Save checked state of ALL existing hallmark items before any DOM changes
      const existingItems = document.querySelectorAll('[data-calc-panel="hallmarkTab"] .calc-item');
      const savedStates = [];
      existingItems.forEach(item => {
        const checked = item.querySelector('.hallmark-options input[type="radio"]:checked');
        savedStates.push(checked ? checked.value : null);
      });

      const firstItem = document.querySelector('[data-calc-panel="hallmarkTab"] .calc-item');
      const clone = firstItem.cloneNode(true);
      clone.setAttribute("data-item-index", currentItemIndex);

      // Add remove button
      const header = clone.querySelector(".calc-item__header");
      const removeBtn = document.createElement("button");
      removeBtn.type = "button";
      removeBtn.style.cssText = "color:#ff4757;font-size:13px;text-decoration:none;font-weight:600;padding:0;border:none;background:none;cursor:pointer;";
      removeBtn.textContent = "Sil";
      removeBtn.addEventListener("click", () => {
        const prevDivider = clone.previousElementSibling;
        if (prevDivider && prevDivider.classList.contains("calc-divider")) prevDivider.remove();
        clone.remove();
        calculateAll();
      });
      header.appendChild(removeBtn);

      // Build new hallmark radios with UNIQUE name for this clone
      const hallmarkContainer = clone.querySelector(".hallmark-options");
      const newFormName = `data[hallmarkTab][${currentItemIndex}][hallmark]`;
      hallmarkContainer.setAttribute("data-form-name", newFormName);
      hallmarkContainer.innerHTML = "";

      SETTINGS.hallmarks.forEach((hm, i) => {
        const price = SETTINGS.hallmarkPrices[hm];
        const uniqueId = `hm_${currentItemIndex}_${i}_${Date.now()}`;

        const radio = document.createElement("input");
        radio.type = "radio";
        radio.name = newFormName;
        radio.value = price;
        radio.id = uniqueId;
        if (i === 0) radio.checked = true;
        radio.addEventListener("change", calculateAll);

        const label = document.createElement("label");
        label.setAttribute("for", uniqueId);
        label.textContent = hm;

        hallmarkContainer.appendChild(radio);
        hallmarkContainer.appendChild(label);
      });

      // Update range input names
      const goldRange = clone.querySelector(".goldWeightRange");
      goldRange.name = `data[hallmarkTab][${currentItemIndex}][goldWeight]`;
      goldRange.value = goldRange.min;

      const periodRange = clone.querySelector(".creditPeriodRange");
      periodRange.name = `data[hallmarkTab][${currentItemIndex}][creditPeriod]`;
      periodRange.value = periodRange.min;

      // Insert divider + clone before addBtn
      const divider = document.createElement("div");
      divider.className = "calc-divider";
      addBtn.parentElement.insertBefore(divider, addBtn);
      addBtn.parentElement.insertBefore(clone, addBtn);

      // Restore checked states of all EXISTING items
      existingItems.forEach((item, idx) => {
        if (savedStates[idx] !== null) {
          const radios = item.querySelectorAll('.hallmark-options input[type="radio"]');
          radios.forEach(r => {
            r.checked = (r.value === savedStates[idx]);
          });
        }
      });

      setupRangeInputs(clone);
      calculateAll();
      currentItemIndex++;
    });
  }

  // ========== INIT ==========
  renderHallmarks();
  setupRangeInputs(document);
  calculateAll();
  setupAddMore();
});
