/**
 * Konica Minolta Ink Estimation Tool — Client Application Logic
 */

let selectedFile = null;
let currentResult = null;
let activeSeparation = 'composite';
let activePageIndex = 0;

// DOM Elements
const dropzone = document.getElementById('dropzone');
const fileInput = document.getElementById('fileInput');
const fileCard = document.getElementById('fileCard');
const fileName = document.getElementById('fileName');
const fileMeta = document.getElementById('fileMeta');
const btnRemoveFile = document.getElementById('btnRemoveFile');
const estimateForm = document.getElementById('estimateForm');
const btnCalculate = document.getElementById('btnCalculate');
const progressTracker = document.getElementById('progressTracker');

const emptyState = document.getElementById('emptyState');
const resultsDashboard = document.getElementById('resultsDashboard');

// Setup Drag & Drop
if (dropzone) {
  dropzone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropzone.classList.add('dragover');
  });

  dropzone.addEventListener('dragleave', () => {
    dropzone.classList.remove('dragover');
  });

  dropzone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropzone.classList.remove('dragover');
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      handleFileSelected(e.dataTransfer.files[0]);
    }
  });

  dropzone.addEventListener('click', () => {
    fileInput.click();
  });
}

if (fileInput) {
  fileInput.addEventListener('change', (e) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFileSelected(e.target.files[0]);
    }
  });
}

if (btnRemoveFile) {
  btnRemoveFile.addEventListener('click', (e) => {
    e.stopPropagation();
    selectedFile = null;
    fileInput.value = '';
    fileCard.style.display = 'none';
    dropzone.style.display = 'block';
  });
}

function handleFileSelected(file) {
  const ext = file.name.split('.').pop().toLowerCase();
  if (!['pdf', 'tif', 'tiff'].includes(ext)) {
    alert('Please upload a PDF or TIFF document.');
    return;
  }

  selectedFile = file;
  fileName.textContent = file.name;
  fileMeta.textContent = `${(file.size / (1024 * 1024)).toFixed(2)} MB • ${ext.toUpperCase()}`;

  dropzone.style.display = 'none';
  fileCard.style.display = 'flex';
}

// Sample file loaders
window.loadSampleFile = async function(type) {
  let samplePath = '';
  let sampleName = '';
  if (type === 'car_tif') {
    samplePath = '/static/samples/2_585x750_car_300dpi.tif';
    sampleName = '2_585x750_car_300dpi.tif';
  } else if (type === 'manual_pdf') {
    samplePath = '/static/samples/InkEstimationTool_20092024.pdf';
    sampleName = 'InkEstimationTool_20092024.pdf';
  }

  try {
    const res = await fetch(samplePath);
    if (!res.ok) throw new Error('Sample file not found on server');
    const blob = await res.blob();
    const file = new File([blob], sampleName, { type: blob.type });
    handleFileSelected(file);
  } catch (err) {
    console.error('Error loading sample:', err);
    alert('Could not load sample file directly. You can drag and drop any PDF or TIFF from your computer.');
  }
};

// Mode & Segmented Button Selection
document.querySelectorAll('.segmented-control').forEach(group => {
  group.querySelectorAll('.segment-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      group.querySelectorAll('.segment-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      const targetInput = document.getElementById(group.dataset.input);
      if (targetInput) {
        targetInput.value = btn.dataset.value;
      }
    });
  });
});

// Separation Toggles
document.querySelectorAll('.sep-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelectorAll('.sep-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    activeSeparation = btn.dataset.sep;
    updatePreviewImage();
  });
});

const currencySelect = document.getElementById('currencySelect');
const currencySymbolLabel = document.getElementById('currencySymbolLabel');

function getActiveCurrency() {
  if (!currencySelect) return { code: 'EUR', symbol: '€' };
  const opt = currencySelect.options[currencySelect.selectedIndex];
  return {
    code: currencySelect.value || 'EUR',
    symbol: opt ? (opt.dataset.sym || '€') : '€'
  };
}

if (currencySelect) {
  currencySelect.addEventListener('change', () => {
    const curr = getActiveCurrency();
    if (currencySymbolLabel) currencySymbolLabel.textContent = curr.symbol;
    if (currentResult) {
      currentResult.parameters.currency = curr.code;
      currentResult.parameters.currency_symbol = curr.symbol;
      renderResults(currentResult);
    }
  });
}

// Submit Form & Run Estimation
if (estimateForm) {
  estimateForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    if (!selectedFile) {
      alert('Please select or drop a PDF / TIFF file first.');
      return;
    }

    const curr = getActiveCurrency();
    const formData = new FormData();
    formData.append('file', selectedFile);
    formData.append('mode', document.getElementById('printMode').value);
    formData.append('media', document.getElementById('paperType').value);
    formData.append('quality', document.getElementById('qualityMode').value);
    formData.append('dpi', document.getElementById('resolutionDpi').value);
    formData.append('use_icc', document.getElementById('useIcc').checked);
    formData.append('quantity', document.getElementById('jobQuantity').value);
    formData.append('duplex', document.getElementById('isDuplex').checked);
    formData.append('cost_cyan', document.getElementById('priceCyan').value);
    formData.append('cost_magenta', document.getElementById('priceMagenta').value);
    formData.append('cost_yellow', document.getElementById('priceYellow').value);
    formData.append('cost_black', document.getElementById('priceBlack').value);
    formData.append('currency', curr.code);
    formData.append('currency_symbol', curr.symbol);

    // UI Loading state
    btnCalculate.disabled = true;
    btnCalculate.innerHTML = `<svg class="spin" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10" stroke-dasharray="32" stroke-dashoffset="10"/></svg> Processing Estimation...`;
    progressTracker.style.display = 'block';

    simulateProgress();

    try {
      const res = await fetch('/api/estimate', {
        method: 'POST',
        credentials: 'same-origin',
        body: formData
      });

      const responseText = await res.text();
      let resJson;
      try {
        resJson = JSON.parse(responseText);
      } catch (jsonErr) {
        if (responseText.includes('Access Restricted') || res.status === 403) {
          throw new Error('Access session expired. Please refresh the page with ?code=31337');
        }
        throw new Error(`Server returned status ${res.status}: ${responseText.substring(0, 150)}...`);
      }

      if (!res.ok) {
        throw new Error(resJson.detail || 'Estimation failed');
      }

      currentResult = resJson;
      renderResults(currentResult);

    } catch (err) {
      alert(`Error during ink estimation: ${err.message}`);
    } finally {
      btnCalculate.disabled = false;
      btnCalculate.innerHTML = `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"/></svg> Calculate Ink & Cost`;
      progressTracker.style.display = 'none';
    }
  });
}

function simulateProgress() {
  const steps = [
    document.getElementById('step1'),
    document.getElementById('step2'),
    document.getElementById('step3'),
    document.getElementById('step4')
  ];

  steps.forEach(s => {
    s.className = 'pipeline-step';
  });

  steps[0].classList.add('active');
  setTimeout(() => { steps[0].className = 'pipeline-step done'; steps[1].classList.add('active'); }, 500);
  setTimeout(() => { steps[1].className = 'pipeline-step done'; steps[2].classList.add('active'); }, 1100);
  setTimeout(() => { steps[2].className = 'pipeline-step done'; steps[3].classList.add('active'); }, 1800);
}

// Render Results Dashboard
function renderResults(data) {
  emptyState.style.display = 'none';
  resultsDashboard.style.display = 'flex';

  // Hero KPIs
  const ca = data.cost_analysis;
  const jt = data.job_totals;
  const sc = data.single_copy_metrics;
  const sym = (data.parameters && data.parameters.currency_symbol) ? data.parameters.currency_symbol : '€';

  document.getElementById('kpiTotalCost').textContent = `${sym}${ca.total_job_cost.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  
  if (data.document.page_count === 1) {
    document.getElementById('kpiCostSub').textContent = `${sym}${ca.cost_per_copy.toFixed(4)} / sheet • ${sym}${ca.cost_per_1000_copies.toFixed(2)} / 1k`;
  } else {
    const sheetMode = data.parameters.duplex ? 'duplex' : 'simplex';
    document.getElementById('kpiCostSub').textContent = `${sym}${ca.cost_per_copy.toFixed(4)} / copy • ${sym}${ca.cost_per_page.toFixed(4)} / pg side (${sym}${ca.cost_per_sheet.toFixed(4)} / ${sheetMode} sheet)`;
  }

  document.getElementById('kpiTotalVolume').textContent = `${jt.total_liters} L`;
  if (data.document.page_count === 1) {
    document.getElementById('kpiVolSub').textContent = `${jt.total_ml.toLocaleString()} ml across ${jt.quantity.toLocaleString()} sheet(s)`;
  } else {
    document.getElementById('kpiVolSub').textContent = `${jt.total_ml.toLocaleString()} ml • ${jt.total_physical_sheets.toLocaleString()} physical sheets (${jt.quantity.toLocaleString()} copies)`;
  }

  document.getElementById('kpiSingleCopy').textContent = `${sc.total_ml} ml`;
  document.getElementById('kpiSingleSub').textContent = `Weight: ${sc.total_grams} g • ${data.document.page_count} page(s) per copy`;

  document.getElementById('kpiTotalArea').textContent = `${data.document.total_area_m2} m²`;
  document.getElementById('kpiAreaSub').textContent = `${data.document.page_count} page(s) • ${data.parameters.dpi} DPI`;

  // CMYK Channel Cards
  const cov = data.coverage_percentages;
  renderChannelBox('c', sc.cyan_ml, sc.cyan_grams, cov.cyan_pct, jt.cyan_ml, ca.cyan_cost, sym);
  renderChannelBox('m', sc.magenta_ml, sc.magenta_grams, cov.magenta_pct, jt.magenta_ml, ca.magenta_cost, sym);
  renderChannelBox('y', sc.yellow_ml, sc.yellow_grams, cov.yellow_pct, jt.yellow_ml, ca.yellow_cost, sym);
  renderChannelBox('k', sc.black_ml, sc.black_grams, cov.black_pct, jt.black_ml, ca.black_cost, sym);

  // TAC Risk Distribution
  const tac = data.tac_distribution;
  document.getElementById('tacSafePct').textContent = `${tac.safe_0_150_pct}%`;
  document.getElementById('tacMidPct').textContent = `${tac.moderate_150_260_pct}%`;
  document.getElementById('tacHighPct').textContent = `${tac.warning_260_320_pct}%`;
  document.getElementById('tacCritPct').textContent = `${tac.critical_exceeded_320_pct}%`;

  // Page selector
  const pageSelect = document.getElementById('pageSelect');
  pageSelect.innerHTML = '';
  data.pages.forEach((p, idx) => {
    const opt = document.createElement('option');
    opt.value = idx;
    opt.textContent = `Page ${p.page_number} (${p.width_mm} × ${p.height_mm} mm)`;
    pageSelect.appendChild(opt);
  });
  activePageIndex = 0;
  pageSelect.addEventListener('change', (e) => {
    activePageIndex = parseInt(e.target.value);
    updatePreviewImage();
  });

  // Previews
  updatePreviewImage();

  // Per-Page Table
  const tableBody = document.getElementById('pagesTableBody');
  tableBody.innerHTML = '';
  data.pages.forEach(p => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td style="font-weight: 600;">Page ${p.page_number}</td>
      <td style="color: var(--text-muted);">${p.width_mm} × ${p.height_mm} mm</td>
      <td style="color: var(--c-cyan); font-weight: 600;">${p.cyan_ml} ml</td>
      <td style="color: var(--c-magenta); font-weight: 600;">${p.magenta_ml} ml</td>
      <td style="color: var(--c-yellow); font-weight: 600;">${p.yellow_ml} ml</td>
      <td style="color: var(--text-primary); font-weight: 600;">${p.black_ml} ml</td>
      <td style="font-weight: 700; color: #ffffff;">${p.total_ml} ml</td>
      <td>${p.coverage_c}% / ${p.coverage_m}% / ${p.coverage_y}% / ${p.coverage_k}%</td>
    `;
    tableBody.appendChild(tr);
  });

  // Scroll to results smoothly
  resultsDashboard.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

function renderChannelBox(prefix, ml, grams, covPct, jobMl, cost, sym = '€') {
  document.getElementById(`stat_${prefix}_ml`).textContent = `${ml} ml`;
  document.getElementById(`stat_${prefix}_cov`).textContent = `${covPct}% Cov`;
  document.getElementById(`stat_${prefix}_sub`).textContent = `${grams} g • Job: ${jobMl.toLocaleString()} ml (${sym}${cost.toFixed(2)})`;
  document.getElementById(`meter_${prefix}`).style.width = `${Math.min(100, covPct * 2)}%`;
}

function updatePreviewImage() {
  if (!currentResult || !currentResult.pages[activePageIndex]) return;
  const page = currentResult.pages[activePageIndex];
  const previews = page.previews;
  const imgEl = document.getElementById('previewImg');

  if (previews && previews[activeSeparation]) {
    imgEl.src = previews[activeSeparation];
    imgEl.style.display = 'block';
  } else if (previews && previews.composite) {
    imgEl.src = previews.composite;
    imgEl.style.display = 'block';
  }
}

// Export Handlers
window.exportPdf = async function() {
  if (!currentResult) return;
  try {
    const res = await fetch('/api/export/pdf', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(currentResult)
    });
    if (!res.ok) throw new Error('PDF export failed');
    const blob = await res.blob();
    downloadBlob(blob, `Ink_Quote_${currentResult.document.filename.replace(/\.[^/.]+$/, "")}.pdf`);
  } catch (err) {
    alert(`Error exporting PDF: ${err.message}`);
  }
};

window.exportExcel = async function() {
  if (!currentResult) return;
  try {
    const res = await fetch('/api/export/xlsx', {
      method: 'POST',
      credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(currentResult)
    });
    if (!res.ok) throw new Error('Excel export failed');
    const blob = await res.blob();
    downloadBlob(blob, `Ink_Estimate_${currentResult.document.filename.replace(/\.[^/.]+$/, "")}.xlsx`);
  } catch (err) {
    alert(`Error exporting Excel: ${err.message}`);
  }
};

window.exportJson = function() {
  if (!currentResult) return;
  const str = JSON.stringify(currentResult, null, 2);
  const blob = new Blob([str], { type: 'application/json' });
  downloadBlob(blob, `Ink_Data_${currentResult.document.filename.replace(/\.[^/.]+$/, "")}.json`);
};

function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}
