// EvikTools - Engineering Tools App

const API = '/api';

// Distance conversion factors to meters
const DISTANCE_TO_M = {
  mm: 0.001,
  cm: 0.01,
  m: 1,
  km: 1000,
  in: 0.0254,
  ft: 0.3048,
  yd: 0.9144,
  mi: 1609.344
};

const SHAPE_CONFIG = {
  cube: {
    label: 'Cube',
    icon: '◻',
    inputs: [{ key: 'a', label: 'Side (a)' }],
    calc: (d) => Math.pow(d.a, 3)
  },
  rect: {
    label: 'Rectangular prism',
    icon: '▭',
    inputs: [
      { key: 'l', label: 'Length (l)' },
      { key: 'w', label: 'Width (w)' },
      { key: 'h', label: 'Height (h)' }
    ],
    calc: (d) => d.l * d.w * d.h
  },
  cylinder: {
    label: 'Cylinder',
    icon: '○',
    inputs: [
      { key: 'r', label: 'Radius (r)' },
      { key: 'h', label: 'Height (h)' }
    ],
    calc: (d) => Math.PI * d.r * d.r * d.h
  },
  sphere: {
    label: 'Sphere',
    icon: '◎',
    inputs: [{ key: 'r', label: 'Radius (r)' }],
    calc: (d) => (4 / 3) * Math.PI * Math.pow(d.r, 3)
  },
  cone: {
    label: 'Cone',
    icon: '△',
    inputs: [
      { key: 'r', label: 'Radius (r)' },
      { key: 'h', label: 'Height (h)' }
    ],
    calc: (d) => (1 / 3) * Math.PI * d.r * d.r * d.h
  }
};

let currentTool = null;
let currentShape = 'cube';

// Load tools from API
async function loadTools() {
  try {
    const res = await fetch(`${API}/tools`);
    const tools = await res.json();
    renderToolGrid(tools);
  } catch (e) {
    renderToolGrid([
      { slug: 'slope', name: 'Slope Calculator', icon: '📐' },
      { slug: 'converter', name: 'Unit Converter', icon: '↔️' },
      { slug: 'volt-cables', name: 'Volt & Cables', icon: '⚡' },
      { slug: 'volume', name: 'Volume Calculator', icon: '📦' }
    ]);
  }
}

function renderToolGrid(tools) {
  const grid = document.getElementById('toolGrid');
  grid.innerHTML = tools.map(t => `
    <div class="tool-card" data-slug="${t.slug}">
      <span class="icon">${t.icon || '🔧'}</span>
      <span class="name">${t.name}</span>
    </div>
  `).join('');

  grid.querySelectorAll('.tool-card').forEach(card => {
    card.addEventListener('click', () => selectTool(card.dataset.slug));
  });
}

function selectTool(slug) {
  currentTool = slug;
  document.querySelectorAll('.tool-card').forEach(c => c.classList.remove('active'));
  const card = document.querySelector(`.tool-card[data-slug="${slug}"]`);
  if (card) card.classList.add('active');

  document.getElementById('panelPlaceholder').hidden = true;
  document.querySelectorAll('.tool-content').forEach(el => el.hidden = true);

  const panel = document.getElementById(`tool-${slug}`);
  if (panel) {
    panel.hidden = false;
    if (slug === 'volume') renderShapeInputs(currentShape);
  }
}

function renderShapeInputs(shape) {
  currentShape = shape;
  const cfg = SHAPE_CONFIG[shape];
  const container = document.getElementById('shapeInputs');
  container.innerHTML = cfg.inputs.map(i => `
    <div class="input-group">
      <label>${i.label}</label>
      <input type="number" id="vol-${i.key}" placeholder="0" step="any">
    </div>
  `).join('');
}

// Calculators
function calcSlope() {
  const rise = parseFloat(document.getElementById('slope-rise').value) || 0;
  const run = parseFloat(document.getElementById('slope-run').value) || 0;
  const box = document.getElementById('slope-result');
  if (run === 0) {
    box.textContent = 'Run cannot be zero.';
    box.className = 'result-box';
    return;
  }
  const ratio = rise / run;
  const percent = ratio * 100;
  const angle = Math.atan(ratio) * (180 / Math.PI);
  box.textContent = `Ratio: 1:${(1 / ratio).toFixed(2)} | Slope: ${percent.toFixed(2)}% | Angle: ${angle.toFixed(2)}°`;
  box.className = 'result-box has-result';
}

function calcConverter() {
  const val = parseFloat(document.getElementById('conv-value').value) || 0;
  const from = document.getElementById('conv-from').value;
  const to = document.getElementById('conv-to').value;
  const box = document.getElementById('converter-result');
  const m = val * DISTANCE_TO_M[from];
  const result = m / DISTANCE_TO_M[to];
  box.textContent = `${val} ${from} = ${result.toFixed(6)} ${to}`;
  box.className = 'result-box has-result';
}

function calcVoltCables() {
  const V = parseFloat(document.getElementById('volt-voltage').value) || 12;
  const I = parseFloat(document.getElementById('volt-current').value) || 10;
  const L = parseFloat(document.getElementById('volt-length').value) || 10;
  const rho = parseFloat(document.getElementById('volt-resistivity').value) || 0.0172;
  const A = parseFloat(document.getElementById('volt-cross').value) || 2.5;
  const box = document.getElementById('volt-result');
  const R = (rho * 2 * L) / A;
  const drop = I * R;
  const vEnd = V - drop;
  const pct = ((drop / V) * 100).toFixed(2);
  box.textContent = `Voltage drop: ${drop.toFixed(3)} V | End voltage: ${vEnd.toFixed(3)} V | Drop: ${pct}%`;
  box.className = 'result-box has-result';
}

function calcVolume() {
  const cfg = SHAPE_CONFIG[currentShape];
  const d = {};
  cfg.inputs.forEach(i => {
    d[i.key] = parseFloat(document.getElementById(`vol-${i.key}`).value) || 0;
  });
  const vol = cfg.calc(d);
  const box = document.getElementById('volume-result');
  box.textContent = `Volume = ${vol.toFixed(4)} units³`;
  box.className = 'result-box has-result';
}

// Event listeners
document.addEventListener('DOMContentLoaded', () => {
  loadTools();

  document.querySelectorAll('.btn-calc').forEach(btn => {
    btn.addEventListener('click', () => {
      const tool = btn.dataset.tool;
      if (tool === 'slope') calcSlope();
      else if (tool === 'converter') calcConverter();
      else if (tool === 'volt-cables') calcVoltCables();
      else if (tool === 'volume') calcVolume();
    });
  });

  document.getElementById('shapeSelector')?.addEventListener('click', e => {
    const btn = e.target.closest('.shape-btn');
    if (!btn) return;
    document.querySelectorAll('.shape-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    renderShapeInputs(btn.dataset.shape);
  });

});
