// Single function plotting
var expression = '';
var variable = 'x';

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
  console.log('Plot page loaded');

  if (typeof math === 'undefined') {
    showError('Math.js library failed to load. Please reload the extension.');
    return;
  }

  // Event listeners
  document.getElementById('updateBtn').addEventListener('click', updatePlot);

  // Load plot from storage
  chrome.storage.local.get('calculatorPlot', function(data) {
    if (chrome.runtime.lastError) {
      showError('Error reading plot data: ' + chrome.runtime.lastError.message);
      return;
    }

    if (data.calculatorPlot) {
      var config = data.calculatorPlot;
      expression = config.expression;
      variable = config.variable || 'x';
      document.getElementById('xMin').value = config.start || -10;
      document.getElementById('xMax').value = config.end || 10;
      document.getElementById('functionInfo').textContent = 'f(' + variable + ') = ' + expression;
      updatePlot();
    }
  });
});

function showError(message) {
  var container = document.getElementById('errorContainer');
  var div = document.createElement('div');
  div.className = 'error-message';
  div.textContent = message;
  container.innerHTML = '';
  container.appendChild(div);
}

function clearError() {
  document.getElementById('errorContainer').innerHTML = '';
}

function generatePlotData(expr, xMin, xMax, numPoints) {
  var data = [];
  var compiledExpr;

  try {
    compiledExpr = math.compile(expr);
  } catch (e) {
    throw new Error('Invalid expression: ' + e.message);
  }

  var step = (xMax - xMin) / numPoints;
  var xValues = math.range(xMin, xMax, step, true).toArray();

  for (var i = 0; i < xValues.length; i++) {
    var x = xValues[i];
    try {
      var scope = {};
      scope[variable] = x;
      var y = compiledExpr.evaluate(scope);

      if (typeof y === 'number' && isFinite(y) && !isNaN(y)) {
        data.push({ x: x, y: y });
      }
    } catch (e) {
      // Skip invalid points
    }
  }

  return data;
}

function updatePlot() {
  clearError();

  if (!expression) {
    showError('No function to plot. Use the calculator to plot a function.');
    return;
  }

  var xMin = parseFloat(document.getElementById('xMin').value);
  var xMax = parseFloat(document.getElementById('xMax').value);
  var numPoints = parseInt(document.getElementById('points').value);

  if (xMin >= xMax) {
    showError('X min must be less than X max.');
    return;
  }

  try {
    var data = generatePlotData(expression, xMin, xMax, numPoints);

    if (data.length === 0) {
      showError('No valid data points could be generated.');
      return;
    }

    renderChart(data, xMin, xMax);
    updateInfoPanel(data, xMin, xMax);
  } catch (e) {
    showError(e.message);
  }
}

function renderChart(data, xMin, xMax) {
  var svg = document.getElementById('chart');
  var width = 1000;
  var height = 500;
  var padding = { top: 40, right: 40, bottom: 60, left: 70 };
  var chartWidth = width - padding.left - padding.right;
  var chartHeight = height - padding.top - padding.bottom;

  // Calculate Y range
  var yValues = data.map(function(d) { return d.y; });
  var yMin = Math.min.apply(null, yValues);
  var yMax = Math.max.apply(null, yValues);
  var yRange = yMax - yMin || 1;
  var yPadding = yRange * 0.1;
  yMin -= yPadding;
  yMax += yPadding;

  function scaleX(x) {
    return padding.left + ((x - xMin) / (xMax - xMin)) * chartWidth;
  }
  function scaleY(y) {
    return padding.top + chartHeight - ((y - yMin) / (yMax - yMin)) * chartHeight;
  }

  // Generate ticks
  var xTicks = [];
  for (var i = 0; i <= 10; i++) {
    xTicks.push(xMin + (i / 10) * (xMax - xMin));
  }
  var yTicks = [];
  for (var j = 0; j <= 8; j++) {
    yTicks.push(yMin + (j / 8) * (yMax - yMin));
  }

  var zeroY = (yMin <= 0 && yMax >= 0) ? scaleY(0) : null;
  var zeroX = (xMin <= 0 && xMax >= 0) ? scaleX(0) : null;

  // Build SVG
  var svgContent = '';

  // Background
  svgContent += '<rect x="' + padding.left + '" y="' + padding.top + '" width="' + chartWidth + '" height="' + chartHeight + '" fill="#0f172a"/>';

  // Grid
  xTicks.forEach(function(x) {
    svgContent += '<line x1="' + scaleX(x) + '" y1="' + padding.top + '" x2="' + scaleX(x) + '" y2="' + (height - padding.bottom) + '" stroke="#334155" stroke-width="1" stroke-dasharray="4,4"/>';
  });
  yTicks.forEach(function(y) {
    svgContent += '<line x1="' + padding.left + '" y1="' + scaleY(y) + '" x2="' + (width - padding.right) + '" y2="' + scaleY(y) + '" stroke="#334155" stroke-width="1" stroke-dasharray="4,4"/>';
  });

  // Zero lines
  if (zeroY !== null) {
    svgContent += '<line x1="' + padding.left + '" y1="' + zeroY + '" x2="' + (width - padding.right) + '" y2="' + zeroY + '" stroke="#64748b" stroke-width="2"/>';
  }
  if (zeroX !== null) {
    svgContent += '<line x1="' + zeroX + '" y1="' + padding.top + '" x2="' + zeroX + '" y2="' + (height - padding.bottom) + '" stroke="#64748b" stroke-width="2"/>';
  }

  // Axes
  svgContent += '<line x1="' + padding.left + '" y1="' + (height - padding.bottom) + '" x2="' + (width - padding.right) + '" y2="' + (height - padding.bottom) + '" stroke="#94a3b8" stroke-width="2"/>';
  svgContent += '<line x1="' + padding.left + '" y1="' + padding.top + '" x2="' + padding.left + '" y2="' + (height - padding.bottom) + '" stroke="#94a3b8" stroke-width="2"/>';

  // X-axis labels
  xTicks.forEach(function(x) {
    svgContent += '<line x1="' + scaleX(x) + '" y1="' + (height - padding.bottom) + '" x2="' + scaleX(x) + '" y2="' + (height - padding.bottom + 6) + '" stroke="#94a3b8" stroke-width="2"/>';
    svgContent += '<text x="' + scaleX(x) + '" y="' + (height - padding.bottom + 24) + '" fill="#94a3b8" font-size="12" text-anchor="middle" font-family="monospace">' + x.toFixed(1) + '</text>';
  });

  // Y-axis labels
  yTicks.forEach(function(y) {
    svgContent += '<line x1="' + (padding.left - 6) + '" y1="' + scaleY(y) + '" x2="' + padding.left + '" y2="' + scaleY(y) + '" stroke="#94a3b8" stroke-width="2"/>';
    svgContent += '<text x="' + (padding.left - 12) + '" y="' + (scaleY(y) + 4) + '" fill="#94a3b8" font-size="12" text-anchor="end" font-family="monospace">' + y.toFixed(1) + '</text>';
  });

  // Axis labels
  svgContent += '<text x="' + (width / 2) + '" y="' + (height - 10) + '" fill="#94a3b8" font-size="14" text-anchor="middle">' + variable + '</text>';
  svgContent += '<text x="20" y="' + (height / 2) + '" fill="#94a3b8" font-size="14" text-anchor="middle" transform="rotate(-90, 20, ' + (height / 2) + ')">f(' + variable + ')</text>';

  // Plot the function
  var pathData = data.map(function(d, i) {
    return (i === 0 ? 'M' : 'L') + ' ' + scaleX(d.x).toFixed(2) + ' ' + scaleY(d.y).toFixed(2);
  }).join(' ');

  svgContent += '<path d="' + pathData + '" fill="none" stroke="#22d3ee" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>';

  // Title
  svgContent += '<text x="' + (width / 2) + '" y="24" fill="#e2e8f0" font-size="16" text-anchor="middle" font-weight="500">f(' + variable + ') = ' + expression + '</text>';

  svg.innerHTML = svgContent;
}

function updateInfoPanel(data, xMin, xMax) {
  var yValues = data.map(function(d) { return d.y; });
  var visibleYMin = Math.min.apply(null, yValues);
  var visibleYMax = Math.max.apply(null, yValues);

  document.getElementById('domainInfo').textContent = '[' + xMin + ', ' + xMax + ']';
  document.getElementById('rangeInfo').textContent = '[' + visibleYMin.toFixed(4) + ', ' + visibleYMax.toFixed(4) + ']';

  // Find X intercepts
  var intercepts = [];
  for (var i = 1; i < data.length; i++) {
    if ((data[i-1].y <= 0 && data[i].y >= 0) || (data[i-1].y >= 0 && data[i].y <= 0)) {
      var x0 = data[i-1].x;
      var x1 = data[i].x;
      var y0 = data[i-1].y;
      var y1 = data[i].y;
      var xIntercept = x0 - y0 * (x1 - x0) / (y1 - y0);
      intercepts.push(xIntercept.toFixed(3));
    }
  }

  document.getElementById('xIntercepts').textContent = intercepts.length > 0
    ? intercepts.slice(0, 5).join(', ') + (intercepts.length > 5 ? '...' : '')
    : 'none found';
}
