const segmentsTable = document.getElementById('segmentsTable');
const segmentTypeSelect = document.getElementById('segmentTypeSelect');
const segmentLengthInput = document.getElementById('segmentLengthInput');
const addSegmentButton = document.getElementById('addSegmentButton');
const valuePDV = document.getElementById('valuePDV');
const valuePVV = document.getElementById('valuePVV');
const errorsContainer = document.getElementById('errorsContainer');

const ALL_SEGMENTS = {
/*  */ '10BASE5': { leftBase: 11.8, midBase: 46.5, rightBase: 169.5, delayPerM: 0.0866, repL: 16.0, repM: 11.0, maxLen: 500 },
/*  */ '10BASE2': { leftBase: 11.8, midBase: 46.5, rightBase: 169.5, delayPerM: 0.1026, repL: 16.0, repM: 11.0, maxLen: 185 },
/* */ '10BASE-T': { leftBase: 15.3, midBase: 42.0, rightBase: 165.0, delayPerM: 0.1130, repL: 10.5, repM: 8.00, maxLen: 100 },
/**/ '10BASE-FL': { leftBase: 12.3, midBase: 33.5, rightBase: 156.5, delayPerM: 0.1000, repL: 10.5, repM: 8.00, maxLen: 2000 },
/*    */ 'FOIRL': { leftBase: 7.80, midBase: 29.0, rightBase: 152.0, delayPerM: 0.1000, repL: 7.80, repM: 0.00, maxLen: 1000 },
/*      */ 'AUI': { leftBase: 0.00, midBase: 0.00, rightBase: 0.000, delayPerM: 0.1026, repL: 0.00, repM: 0.00, maxLen: 50 },
};

function populateSelect() {
  for (const type in ALL_SEGMENTS) {
    const option = document.createElement('option');
    option.value = type;
    option.textContent = `${type} (${ALL_SEGMENTS[type].maxLen} м)`;
    segmentTypeSelect.appendChild(option);
  }
}
populateSelect();

function updateSegmentType() {
  segmentLengthInput.disabled = segmentTypeSelect.value === '';
  const segment = ALL_SEGMENTS[segmentTypeSelect.value];
  if (!segment) {
    segmentTypeSelect.value = '';
    return;
  }
  setTimeout(() => segmentLengthInput.focus());
}

function updateSegmentLength() {
  const segment = ALL_SEGMENTS[segmentTypeSelect.value];
  if (!segment || !segmentLengthInput.value) {
    addSegmentButton.disabled = true;
    return false;
  }
  segmentLengthInput.classList.remove('error');
  if (segmentLengthInput.value > segment.maxLen) {
    segmentLengthInput.classList.add('error');
  }
  addSegmentButton.disabled = false;
  segmentLengthInput.value = Math.round(Math.max(1, Math.min(99999, segmentLengthInput.value)));
  return true;
}

function createSegment() {
  if (!updateSegmentLength()) return;
  segments.push({ type: segmentTypeSelect.value, length: segmentLengthInput.value });
  updateSegmentsList();
  setTimeout(() => segmentTypeSelect.focus());
}
segmentTypeSelect.addEventListener('change', updateSegmentType);
segmentLengthInput.addEventListener('keypress', (event) => {
  if (event.key === 'Enter') {
    event.preventDefault();
    createSegment();
  }
})
segmentLengthInput.addEventListener('input', updateSegmentLength);

const segments = [];
addSegmentButton.addEventListener('click', createSegment);

function updateSegmentsList() {
  segmentsTable.querySelectorAll(".row.item").forEach(row => row.remove());
  const headrow = segmentsTable.querySelector('.headrow');

  let index = segments.length;
  for (const segment of [...segments].reverse()) {
    const row = document.createElement('div');
    row.classList.add('row', 'item');
    row.innerHTML = `
            <div>${index--}</div>
            <div>${segment.type}</div>
            <div class="num">${segment.length} м</div>
        `;
    const button = document.createElement('button');
    button.type = 'button';
    button.textContent = '✕';
    button.addEventListener('click', () => {
      segments.splice(segments.indexOf(segment), 1);
      updateSegmentsList();
    });
    const baseSegment = ALL_SEGMENTS[segment.type];
    if (baseSegment && segment.length > baseSegment.maxLen) {
      row.classList.add('error');
    }
    row.appendChild(button);
    headrow.after(row);
  }
  segmentTypeSelect.value = '';
  segmentLengthInput.value = '';
  updateSegmentLength();
  updateSegmentType();

  const { pdv, pvv, errors } = calculatePDV_PVV(segments);
  valuePDV.textContent = pdv.toFixed(2);
  valuePVV.textContent = pvv.toFixed(0);

  [...errorsContainer.childNodes].forEach(node => node.remove());
  errorsContainer.hidden = segments.length === 0;
  if (errors.length > 0) {
    errorsContainer.classList.remove("success");
  } else {
    errorsContainer.classList.add("success");
    errors.push("Сеть работоспособна");
  }
  errors.forEach(error => {
    const errDiv = document.createElement('div');
    errDiv.textContent = error;
    errorsContainer.appendChild(errDiv);
  });
} 
updateSegmentsList();

function calculatePDV_PVV(segments) {
  let pdv = 0;
  let pvv = 0;
  const errors = [];

  for (let i = 0; i < segments.length; i++) {
    const seg = segments[i];
    const spec = ALL_SEGMENTS[seg.type];

    if (!spec) throw Error(`Неизвестный тип сегмента: ${seg.type}`);


    if (seg.length < 0) throw Error(`Отрицательная длина сегмента ${seg.type}: ${seg.length} м`);

    if (seg.length > spec.maxLen) {
      errors.push(`Превышена максимальная длина для сегмента №${i + 1}`);
      errors.push(`${seg.type}: ${seg.length}м/${spec.maxLen}м`);
    }

    let base;
    if (i === 0) {
      base = spec.leftBase;
    } else if (i === segments.length - 1) {
      base = spec.rightBase;
    } else {
      base = spec.midBase;
    }

    pdv += base + (seg.length * spec.delayPerM);
    pvv += i === 0 ? spec.repL : spec.repM;
  }
  if (pdv > 595) {
    errors.push(`Превышен предел PDV: ${pdv.toFixed(2)}/595`);
  }
  if (pvv > 49) {
    errors.push(`Превышен предел PVV: ${pvv.toFixed(2)}/49`);
  }
  if (segments.length > 1024) {
    errors.push(`Превышен предел станций в сети: ${segments.length}/1024`);
  }
  return { pdv, pvv, errors };
}
