// Kostenrechner client-side logic
// Manages form state, calls API, renders results
// Features: URL sharing, scenario comparison, branded print

import { initI18n, t, getLang, onLangChange } from "./i18n";
import { initSidebar } from "./sidebar";

interface InstanceInput {
  enabled: boolean;
  feeVersion?: string;
  numAttorneys?: number;
  numPatentAttorneys?: number;
  numClients?: number;
  oralHearing?: boolean;
  isSME?: boolean;
  includeRevocation?: boolean;
}

interface AttorneyBreakdown {
  baseFee: number;
  verfahrensgebuehr: number;
  erhoehungsgebuehr: number;
  terminsgebuehr: number;
  pauschale: number;
  nettoTotal: number;
  mwst: number;
  bruttoPerAttorney: number;
  count: number;
  bruttoTotal: number;
}

interface DEResult {
  instance: string;
  label: string;
  labelEN: string;
  enabled: boolean;
  courtFee: number;
  courtFeeBasis: string;
  attorney?: AttorneyBreakdown;
  patentAttorney?: AttorneyBreakdown;
  instanceTotal: number;
}

interface UPCResult {
  instance: string;
  label: string;
  labelEN: string;
  enabled: boolean;
  fixedFee: number;
  valueBasedFee: number;
  courtFeesTotal: number;
  courtFeesSME: number;
  recoverableCostsCeiling: number;
  instanceTotal: number;
}

interface EPAResult {
  instance: string;
  label: string;
  labelEN: string;
  enabled: boolean;
  fee: number;
  isSME: boolean;
  instanceTotal: number;
}

interface CostResponse {
  deResults: DEResult[];
  upcResults: UPCResult[];
  epaResults: EPAResult[];
  totals: {
    courtFees: number;
    attorneyFees: number;
    patentAttorneyFees: number;
    epaFees: number;
    grandTotal: number;
  };
}

interface FormState {
  streitwert: number;
  vatRate: number;
  instances: Record<string, InstanceInput>;
}

let lastResponse: CostResponse | null = null;
let compareMode = false;
let scenarioAState: FormState | null = null;
let scenarioAResponse: CostResponse | null = null;
let scenarioBResponse: CostResponse | null = null;

onLangChange(() => {
  if (lastResponse) renderResults(lastResponse);
  if (compareMode) renderComparison();
});

function formatEUR(value: number): string {
  return new Intl.NumberFormat("de-DE", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(value);
}

function parseGermanNumber(s: string): number {
  return parseInt(s.replace(/\./g, "").replace(/,/g, ""), 10) || 0;
}

function formatGermanNumber(n: number): string {
  return new Intl.NumberFormat("de-DE", { maximumFractionDigits: 0 }).format(n);
}

// Debounce helper
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
function debounce(fn: () => void, ms: number) {
  if (debounceTimer) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(fn, ms);
}

// --- Form state ---

function getStreitwert(): number {
  const input = document.getElementById("streitwert-input") as HTMLInputElement;
  return parseGermanNumber(input.value);
}

function getVATRate(): number {
  const select = document.getElementById("vat-rate") as HTMLSelectElement;
  return parseFloat(select.value);
}

function getInstanceInputs(): Record<string, InstanceInput> {
  const instances: Record<string, InstanceInput> = {};
  document.querySelectorAll<HTMLElement>(".instance-card").forEach((card) => {
    const key = card.dataset.instance!;
    const group = card.dataset.group!;
    const checkbox = card.querySelector<HTMLInputElement>('input[type="checkbox"][data-key]');
    const enabled = checkbox?.checked ?? false;

    const input: InstanceInput = { enabled };

    if (enabled) {
      const details = card.querySelector(".instance-details");
      if (details) {
        if (group === "DE") {
          const fv = details.querySelector<HTMLSelectElement>('[data-field="feeVersion"]');
          const na = details.querySelector<HTMLSelectElement>('[data-field="numAttorneys"]');
          const np = details.querySelector<HTMLSelectElement>('[data-field="numPatentAttorneys"]');
          const nc = details.querySelector<HTMLSelectElement>('[data-field="numClients"]');
          const oh = details.querySelector<HTMLInputElement>('[data-field="oralHearing"]');
          if (fv) input.feeVersion = fv.value;
          if (na) input.numAttorneys = parseInt(na.value, 10);
          if (np) input.numPatentAttorneys = parseInt(np.value, 10);
          if (nc) input.numClients = parseInt(nc.value, 10);
          if (oh) input.oralHearing = oh.checked;
        } else if (group === "UPC") {
          const fv = details.querySelector<HTMLSelectElement>('[data-field="feeVersion"]');
          const sme = details.querySelector<HTMLInputElement>('[data-field="isSME"]');
          const rev = details.querySelector<HTMLInputElement>('[data-field="includeRevocation"]');
          if (fv) input.feeVersion = fv.value;
          if (sme) input.isSME = sme.checked;
          if (rev) input.includeRevocation = rev.checked;
        } else if (group === "EPA") {
          const sme = details.querySelector<HTMLInputElement>('[data-field="isSME"]');
          if (sme) input.isSME = sme.checked;
        }
      }
    }

    instances[key] = input;
  });
  return instances;
}

function getFormState(): FormState {
  return {
    streitwert: getStreitwert(),
    vatRate: getVATRate(),
    instances: getInstanceInputs(),
  };
}

// --- URL sharing ---

function stateToParams(state: FormState): URLSearchParams {
  const params = new URLSearchParams();
  params.set("sw", String(state.streitwert));
  params.set("vat", String(state.vatRate));

  for (const [key, inst] of Object.entries(state.instances)) {
    if (!inst.enabled) continue;
    let flags = "1"; // enabled
    if (inst.feeVersion) flags += `,fv=${inst.feeVersion}`;
    if (inst.numAttorneys !== undefined) flags += `,na=${inst.numAttorneys}`;
    if (inst.numPatentAttorneys !== undefined) flags += `,np=${inst.numPatentAttorneys}`;
    if (inst.numClients !== undefined) flags += `,nc=${inst.numClients}`;
    if (inst.oralHearing) flags += ",oh";
    if (inst.isSME) flags += ",sme";
    if (inst.includeRevocation) flags += ",rev";
    params.set(key, flags);
  }
  return params;
}

function paramsToState(params: URLSearchParams): FormState | null {
  const sw = params.get("sw");
  const vat = params.get("vat");
  if (!sw) return null;

  const streitwert = parseInt(sw, 10);
  if (streitwert <= 0) return null;

  const vatRate = vat ? parseFloat(vat) : 0.19;
  const instances: Record<string, InstanceInput> = {};

  for (const [key, val] of params.entries()) {
    if (key === "sw" || key === "vat") continue;
    const parts = val.split(",");
    if (parts[0] !== "1") continue;

    const inst: InstanceInput = { enabled: true };
    for (let i = 1; i < parts.length; i++) {
      const p = parts[i];
      if (p.startsWith("fv=")) inst.feeVersion = p.slice(3);
      else if (p.startsWith("na=")) inst.numAttorneys = parseInt(p.slice(3), 10);
      else if (p.startsWith("np=")) inst.numPatentAttorneys = parseInt(p.slice(3), 10);
      else if (p.startsWith("nc=")) inst.numClients = parseInt(p.slice(3), 10);
      else if (p === "oh") inst.oralHearing = true;
      else if (p === "sme") inst.isSME = true;
      else if (p === "rev") inst.includeRevocation = true;
    }
    instances[key] = inst;
  }

  return { streitwert, vatRate, instances };
}

function restoreState(state: FormState) {
  const slider = document.getElementById("streitwert-slider") as HTMLInputElement;
  const input = document.getElementById("streitwert-input") as HTMLInputElement;
  const vatSelect = document.getElementById("vat-rate") as HTMLSelectElement;

  input.value = formatGermanNumber(state.streitwert);
  slider.value = String(Math.min(state.streitwert, 50000000));
  vatSelect.value = String(state.vatRate);

  // Update preset button active state
  document.querySelectorAll<HTMLButtonElement>(".streitwert-presets button").forEach((btn) => {
    btn.classList.toggle("active", parseInt(btn.dataset.value!, 10) === state.streitwert);
  });

  // Restore instance states
  document.querySelectorAll<HTMLElement>(".instance-card").forEach((card) => {
    const key = card.dataset.instance!;
    const checkbox = card.querySelector<HTMLInputElement>('input[type="checkbox"][data-key]')!;
    const details = card.querySelector<HTMLElement>(".instance-details")!;
    const inst = state.instances[key];

    if (inst?.enabled) {
      checkbox.checked = true;
      card.classList.add("enabled");
      details.style.display = "block";

      // Restore detail fields
      if (inst.feeVersion) {
        const fv = details.querySelector<HTMLSelectElement>('[data-field="feeVersion"]');
        if (fv) fv.value = inst.feeVersion;
      }
      if (inst.numAttorneys !== undefined) {
        const na = details.querySelector<HTMLSelectElement>('[data-field="numAttorneys"]');
        if (na) na.value = String(inst.numAttorneys);
      }
      if (inst.numPatentAttorneys !== undefined) {
        const np = details.querySelector<HTMLSelectElement>('[data-field="numPatentAttorneys"]');
        if (np) np.value = String(inst.numPatentAttorneys);
      }
      if (inst.numClients !== undefined) {
        const nc = details.querySelector<HTMLSelectElement>('[data-field="numClients"]');
        if (nc) nc.value = String(inst.numClients);
      }
      if (inst.oralHearing !== undefined) {
        const oh = details.querySelector<HTMLInputElement>('[data-field="oralHearing"]');
        if (oh) oh.checked = inst.oralHearing;
      }
      if (inst.isSME) {
        const sme = details.querySelector<HTMLInputElement>('[data-field="isSME"]');
        if (sme) sme.checked = true;
      }
      if (inst.includeRevocation) {
        const rev = details.querySelector<HTMLInputElement>('[data-field="includeRevocation"]');
        if (rev) rev.checked = true;
      }
    } else {
      checkbox.checked = false;
      card.classList.remove("enabled");
      details.style.display = "none";
    }
  });
}

function buildShareURL(): string {
  const state = getFormState();
  const params = stateToParams(state);
  const url = new URL(window.location.pathname, window.location.origin);
  url.search = params.toString();
  return url.toString();
}

async function copyShareLink() {
  const url = buildShareURL();
  // Also update browser URL without reload
  history.replaceState(null, "", url);

  try {
    await navigator.clipboard.writeText(url);
  } catch {
    // Fallback for older browsers
    const input = document.createElement("input");
    input.value = url;
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
  }

  const btn = document.getElementById("share-btn")!;
  const original = btn.textContent;
  btn.textContent = t("kosten.share.copied");
  btn.classList.add("copied");
  setTimeout(() => {
    btn.textContent = original;
    btn.classList.remove("copied");
  }, 2000);
}

// --- API call ---

async function callAPI(state: FormState): Promise<CostResponse | null> {
  if (state.streitwert <= 0) return null;

  const body = JSON.stringify({
    streitwert: state.streitwert,
    vatRate: state.vatRate,
    instances: state.instances,
  });

  try {
    const resp = await fetch("/api/tools/kostenrechner", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body,
    });

    if (!resp.ok) {
      const err = await resp.json();
      console.error("API error:", err);
      return null;
    }

    return await resp.json();
  } catch (e) {
    console.error("Fetch error:", e);
    return null;
  }
}

async function calculate() {
  const state = getFormState();
  const data = await callAPI(state);
  if (!data) return;

  lastResponse = data;
  renderResults(data);

  // In compare mode, this becomes scenario B
  if (compareMode) {
    scenarioBResponse = data;
    renderComparison();
  }
}

// --- Rendering ---

function instanceLabel(r: { label: string; labelEN: string }): string {
  return getLang() === "en" ? r.labelEN : r.label;
}

function renderAttorneyDetail(label: string, bd: AttorneyBreakdown): string {
  return `
    <div class="result-attorney-detail">
      <div class="result-detail-label">${label} (${bd.count}\u00d7)</div>
      <div class="result-detail-row"><span>${t("kosten.detail.procedure")}</span><span>${formatEUR(bd.verfahrensgebuehr)}</span></div>
      ${bd.erhoehungsgebuehr > 0 ? `<div class="result-detail-row"><span>${t("kosten.detail.increase")}</span><span>${formatEUR(bd.erhoehungsgebuehr)}</span></div>` : ""}
      ${bd.terminsgebuehr > 0 ? `<div class="result-detail-row"><span>${t("kosten.detail.hearing")}</span><span>${formatEUR(bd.terminsgebuehr)}</span></div>` : ""}
      <div class="result-detail-row"><span>${t("kosten.detail.lump")}</span><span>${formatEUR(bd.pauschale)}</span></div>
      <div class="result-detail-row"><span>${t("kosten.detail.vat")}</span><span>${formatEUR(bd.mwst)}</span></div>
      <div class="result-detail-row result-detail-sum"><span>${t("kosten.detail.total")}</span><span>${formatEUR(bd.bruttoTotal)}</span></div>
    </div>
  `;
}

function renderResultHTML(data: CostResponse): string {
  const enabledDE = data.deResults.filter((r) => r.enabled);
  const enabledUPC = data.upcResults.filter((r) => r.enabled);
  const enabledEPA = data.epaResults.filter((r) => r.enabled);

  if (enabledDE.length === 0 && enabledUPC.length === 0 && enabledEPA.length === 0) {
    return `<div class="result-empty">${t("kosten.empty")}</div>`;
  }

  let html = "";

  // Total
  html += `<div class="result-total-section">
    <div class="result-total-label">${t("kosten.total")}</div>
    <div class="result-total">${formatEUR(data.totals.grandTotal)}</div>
  </div>`;

  // Summary row
  html += `<div class="result-summary">
    <div class="result-summary-row"><span>${t("kosten.court.fees")}</span><span>${formatEUR(data.totals.courtFees)}</span></div>
    <div class="result-summary-row"><span>${t("kosten.attorney.fees")}</span><span>${formatEUR(data.totals.attorneyFees)}</span></div>
    <div class="result-summary-row"><span>${t("kosten.patent.attorney.fees")}</span><span>${formatEUR(data.totals.patentAttorneyFees)}</span></div>
    ${data.totals.epaFees > 0 ? `<div class="result-summary-row"><span>${t("kosten.epa.fees")}</span><span>${formatEUR(data.totals.epaFees)}</span></div>` : ""}
  </div>`;

  // DE results
  for (const r of enabledDE) {
    html += `<div class="result-section">
      <div class="result-section-header">
        <span class="result-section-label">${instanceLabel(r)}</span>
        <span class="result-section-total">${formatEUR(r.instanceTotal)}</span>
      </div>
      <div class="result-detail-row"><span>${t("kosten.court.fees")} (${r.courtFeeBasis})</span><span>${formatEUR(r.courtFee)}</span></div>
      ${r.attorney ? renderAttorneyDetail(t("kosten.attorney.label"), r.attorney) : ""}
      ${r.patentAttorney ? renderAttorneyDetail(t("kosten.patent.attorney.label"), r.patentAttorney) : ""}
    </div>`;
  }

  // UPC results
  for (const r of enabledUPC) {
    html += `<div class="result-section">
      <div class="result-section-header">
        <span class="result-section-label">${instanceLabel(r)}</span>
        <span class="result-section-total">${formatEUR(r.instanceTotal)}</span>
      </div>
      <div class="result-detail-row"><span>${t("kosten.upc.fixed")}</span><span>${formatEUR(r.fixedFee)}</span></div>
      <div class="result-detail-row"><span>${t("kosten.upc.value")}</span><span>${formatEUR(r.valueBasedFee)}</span></div>
      <div class="result-detail-row"><span>${t("kosten.upc.court.total")}</span><span>${formatEUR(r.courtFeesTotal)}</span></div>
      ${r.courtFeesSME !== r.courtFeesTotal ? `<div class="result-detail-row"><span>${t("kosten.upc.sme")}</span><span>${formatEUR(r.courtFeesSME)}</span></div>` : ""}
      <div class="result-detail-row"><span>${t("kosten.upc.recoverable")}</span><span>${formatEUR(r.recoverableCostsCeiling)}</span></div>
    </div>`;
  }

  // EPA results
  for (const r of enabledEPA) {
    html += `<div class="result-section">
      <div class="result-section-header">
        <span class="result-section-label">${t("kosten.epa")}: ${instanceLabel(r)}</span>
        <span class="result-section-total">${formatEUR(r.instanceTotal)}</span>
      </div>
      <div class="result-detail-row"><span>${t("kosten.epa.official")}</span><span>${formatEUR(r.fee)}</span></div>
      <div class="result-detail-note">${t("kosten.epa.note")}</div>
    </div>`;
  }

  return html;
}

function renderResults(data: CostResponse) {
  const totalEl = document.getElementById("result-grand-total")!;
  const breakdownEl = document.getElementById("result-breakdown")!;
  const actionsEl = document.getElementById("result-actions")!;

  totalEl.textContent = formatEUR(data.totals.grandTotal);

  const enabledDE = data.deResults.filter((r) => r.enabled);
  const enabledUPC = data.upcResults.filter((r) => r.enabled);
  const enabledEPA = data.epaResults.filter((r) => r.enabled);

  if (enabledDE.length === 0 && enabledUPC.length === 0 && enabledEPA.length === 0) {
    breakdownEl.innerHTML = `<div class="result-empty">${t("kosten.empty")}</div>`;
    actionsEl.style.display = "none";
    return;
  }

  let html = "";

  // Summary row
  html += `<div class="result-summary">
    <div class="result-summary-row"><span>${t("kosten.court.fees")}</span><span>${formatEUR(data.totals.courtFees)}</span></div>
    <div class="result-summary-row"><span>${t("kosten.attorney.fees")}</span><span>${formatEUR(data.totals.attorneyFees)}</span></div>
    <div class="result-summary-row"><span>${t("kosten.patent.attorney.fees")}</span><span>${formatEUR(data.totals.patentAttorneyFees)}</span></div>
    ${data.totals.epaFees > 0 ? `<div class="result-summary-row"><span>${t("kosten.epa.fees")}</span><span>${formatEUR(data.totals.epaFees)}</span></div>` : ""}
  </div>`;

  // DE results
  for (const r of enabledDE) {
    html += `<div class="result-section">
      <div class="result-section-header">
        <span class="result-section-label">${instanceLabel(r)}</span>
        <span class="result-section-total">${formatEUR(r.instanceTotal)}</span>
      </div>
      <div class="result-detail-row"><span>${t("kosten.court.fees")} (${r.courtFeeBasis})</span><span>${formatEUR(r.courtFee)}</span></div>
      ${r.attorney ? renderAttorneyDetail(t("kosten.attorney.label"), r.attorney) : ""}
      ${r.patentAttorney ? renderAttorneyDetail(t("kosten.patent.attorney.label"), r.patentAttorney) : ""}
    </div>`;
  }

  // UPC results
  for (const r of enabledUPC) {
    html += `<div class="result-section">
      <div class="result-section-header">
        <span class="result-section-label">${instanceLabel(r)}</span>
        <span class="result-section-total">${formatEUR(r.instanceTotal)}</span>
      </div>
      <div class="result-detail-row"><span>${t("kosten.upc.fixed")}</span><span>${formatEUR(r.fixedFee)}</span></div>
      <div class="result-detail-row"><span>${t("kosten.upc.value")}</span><span>${formatEUR(r.valueBasedFee)}</span></div>
      <div class="result-detail-row"><span>${t("kosten.upc.court.total")}</span><span>${formatEUR(r.courtFeesTotal)}</span></div>
      ${r.courtFeesSME !== r.courtFeesTotal ? `<div class="result-detail-row"><span>${t("kosten.upc.sme")}</span><span>${formatEUR(r.courtFeesSME)}</span></div>` : ""}
      <div class="result-detail-row"><span>${t("kosten.upc.recoverable")}</span><span>${formatEUR(r.recoverableCostsCeiling)}</span></div>
    </div>`;
  }

  // EPA results
  for (const r of enabledEPA) {
    html += `<div class="result-section">
      <div class="result-section-header">
        <span class="result-section-label">${t("kosten.epa")}: ${instanceLabel(r)}</span>
        <span class="result-section-total">${formatEUR(r.instanceTotal)}</span>
      </div>
      <div class="result-detail-row"><span>${t("kosten.epa.official")}</span><span>${formatEUR(r.fee)}</span></div>
      <div class="result-detail-note">${t("kosten.epa.note")}</div>
    </div>`;
  }

  breakdownEl.innerHTML = html;
  actionsEl.style.display = "flex";
}

// --- Print support ---

function updatePrintMeta() {
  const meta = document.getElementById("print-meta");
  if (!meta) return;

  const state = getFormState();
  const dateStr = new Date().toLocaleDateString(getLang() === "de" ? "de-DE" : "en-GB", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });

  const vatLabel = state.vatRate === 0.19 ? "19%" : state.vatRate === 0.16 ? "16%" : "0%";

  // Collect enabled instance labels
  const enabledLabels: string[] = [];
  if (lastResponse) {
    for (const r of lastResponse.deResults) if (r.enabled) enabledLabels.push(instanceLabel(r));
    for (const r of lastResponse.upcResults) if (r.enabled) enabledLabels.push(instanceLabel(r));
    for (const r of lastResponse.epaResults) if (r.enabled) enabledLabels.push(instanceLabel(r));
  }

  meta.innerHTML = `
    <div><strong>${t("kosten.print.date")}:</strong> ${dateStr}</div>
    <div><strong>${t("kosten.print.streitwert")}:</strong> ${formatEUR(state.streitwert)}</div>
    <div><strong>${t("kosten.print.vat")}:</strong> ${vatLabel}</div>
    ${enabledLabels.length > 0 ? `<div><strong>${t("kosten.print.instances")}:</strong> ${enabledLabels.join(", ")}</div>` : ""}
  `;
}

// --- Scenario comparison ---

function enterCompareMode() {
  compareMode = true;

  // Snapshot current state as Scenario A
  scenarioAState = getFormState();
  scenarioAResponse = lastResponse;

  // Also compute scenario B from current state
  scenarioBResponse = lastResponse;

  const container = document.getElementById("comparison-container")!;
  const compareBtn = document.getElementById("compare-btn")!;

  container.style.display = "block";
  compareBtn.textContent = t("kosten.compare.exit");
  compareBtn.setAttribute("data-i18n", "kosten.compare.exit");

  renderComparison();

  // Scroll to comparison
  container.scrollIntoView({ behavior: "smooth", block: "start" });
}

function exitCompareMode() {
  compareMode = false;
  scenarioAState = null;
  scenarioAResponse = null;
  scenarioBResponse = null;

  const container = document.getElementById("comparison-container")!;
  const compareBtn = document.getElementById("compare-btn")!;

  container.style.display = "none";
  compareBtn.textContent = t("kosten.compare");
  compareBtn.setAttribute("data-i18n", "kosten.compare");
}

function renderComparison() {
  const colA = document.getElementById("compare-result-a")!;
  const colB = document.getElementById("compare-result-b")!;
  const diffEl = document.getElementById("compare-diff")!;

  if (scenarioAResponse) {
    colA.innerHTML = renderResultHTML(scenarioAResponse);
  }
  if (scenarioBResponse) {
    colB.innerHTML = renderResultHTML(scenarioBResponse);
  }

  // Render diff summary
  if (scenarioAResponse && scenarioBResponse) {
    const a = scenarioAResponse.totals;
    const b = scenarioBResponse.totals;
    const diff = b.grandTotal - a.grandTotal;
    const pct = a.grandTotal > 0 ? ((diff / a.grandTotal) * 100) : 0;
    const sign = diff >= 0 ? "+" : "";
    const diffClass = diff > 0 ? "diff-increase" : diff < 0 ? "diff-decrease" : "diff-neutral";

    diffEl.innerHTML = `
      <div class="comparison-diff-card ${diffClass}">
        <div class="comparison-diff-label">${t("kosten.scenario.diff")}</div>
        <div class="comparison-diff-value">${sign}${formatEUR(diff)}</div>
        <div class="comparison-diff-pct">${sign}${pct.toFixed(1)}%</div>
        <div class="comparison-diff-detail">
          <div class="result-summary-row">
            <span>${t("kosten.court.fees")}</span>
            <span>${sign}${formatEUR(b.courtFees - a.courtFees)}</span>
          </div>
          <div class="result-summary-row">
            <span>${t("kosten.attorney.fees")}</span>
            <span>${sign}${formatEUR(b.attorneyFees - a.attorneyFees)}</span>
          </div>
          <div class="result-summary-row">
            <span>${t("kosten.patent.attorney.fees")}</span>
            <span>${sign}${formatEUR(b.patentAttorneyFees - a.patentAttorneyFees)}</span>
          </div>
          ${(a.epaFees > 0 || b.epaFees > 0) ? `<div class="result-summary-row">
            <span>${t("kosten.epa.fees")}</span>
            <span>${sign}${formatEUR(b.epaFees - a.epaFees)}</span>
          </div>` : ""}
        </div>
      </div>
    `;
  }
}

// --- Initialize ---

document.addEventListener("DOMContentLoaded", () => {
  initI18n();
  initSidebar();

  const slider = document.getElementById("streitwert-slider") as HTMLInputElement;
  const input = document.getElementById("streitwert-input") as HTMLInputElement;

  // Check for URL params to restore state
  const urlParams = new URLSearchParams(window.location.search);
  const restoredState = paramsToState(urlParams);
  if (restoredState) {
    restoreState(restoredState);
  }

  // Sync slider <-> input
  slider.addEventListener("input", () => {
    input.value = formatGermanNumber(parseInt(slider.value, 10));
    debounce(calculate, 200);
  });

  input.addEventListener("input", () => {
    const val = parseGermanNumber(input.value);
    if (val > 0) {
      slider.value = String(Math.min(val, 50000000));
    } else if (val < 0) {
      // Negative entry — drop slider to min so the displayed slider doesn't
      // imply the (now-invalid) old value is still in effect. Final cleanup
      // happens on blur.
      slider.value = String(slider.min || 0);
    }
    debounce(calculate, 400);
  });

  input.addEventListener("blur", () => {
    const val = parseGermanNumber(input.value);
    if (val < 0) {
      // Reject negative Streitwert: clear input + reset slider so the user
      // sees their entry was discarded, and re-run the calc against a
      // zero (no-op) state instead of silently keeping the stale result.
      input.value = "";
      slider.value = String(slider.min || 0);
      calculate();
      return;
    }
    if (val > 0) {
      input.value = formatGermanNumber(val);
    }
  });

  // Preset buttons
  document.querySelectorAll<HTMLButtonElement>(".streitwert-presets button").forEach((btn) => {
    btn.addEventListener("click", () => {
      const val = parseInt(btn.dataset.value!, 10);
      input.value = formatGermanNumber(val);
      slider.value = String(val);
      document.querySelectorAll(".streitwert-presets button").forEach((b) => b.classList.remove("active"));
      btn.classList.add("active");
      calculate();
    });
  });

  // VAT change
  document.getElementById("vat-rate")!.addEventListener("change", () => calculate());

  // Instance toggles
  document.querySelectorAll<HTMLElement>(".instance-card").forEach((card) => {
    const checkbox = card.querySelector<HTMLInputElement>('input[type="checkbox"][data-key]')!;
    const toggleBtn = card.querySelector<HTMLButtonElement>(".instance-toggle")!;
    const details = card.querySelector<HTMLElement>(".instance-details")!;

    checkbox.addEventListener("change", () => {
      card.classList.toggle("enabled", checkbox.checked);
      if (checkbox.checked) {
        details.style.display = "block";
      } else {
        details.style.display = "none";
      }
      calculate();
    });

    toggleBtn.addEventListener("click", () => {
      if (!checkbox.checked) return;
      const visible = details.style.display !== "none";
      details.style.display = visible ? "none" : "block";
    });

    // Re-calculate on any field change within instance details
    details.querySelectorAll("select, input").forEach((el) => {
      el.addEventListener("change", () => calculate());
    });
  });

  // Print button
  document.getElementById("print-btn")!.addEventListener("click", () => {
    updatePrintMeta();
    window.print();
  });

  // Share button
  document.getElementById("share-btn")!.addEventListener("click", () => copyShareLink());

  // Compare button
  document.getElementById("compare-btn")!.addEventListener("click", () => {
    if (compareMode) {
      exitCompareMode();
    } else {
      enterCompareMode();
    }
  });

  // Compare exit button
  document.getElementById("compare-exit-btn")!.addEventListener("click", () => exitCompareMode());

  // Initial calculation
  calculate();
});
