Total Project Cost
${formatCurrency(quote.totalCost)}
`;
renderCostBreakdownChart();
attachEstimatorListeners();
};
const renderCostBreakdownChart = () => {
const { costs, margins } = appData;
const costPerUnit = costs.material + costs.labor + costs.overhead;
const profitAmount = costPerUnit * (margins.profit / (100 - margins.profit - margins.contingency));
const ctx = document.getElementById('costBreakdownChart').getContext('2d');
if (charts.costBreakdown) charts.costBreakdown.destroy();
charts.costBreakdown = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Material', 'Labor', 'Overhead', 'Profit Margin'],
datasets: [{
data: [costs.material, costs.labor, costs.overhead, profitAmount],
backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6']
}]
},
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } } }
});
};
const renderCostConfig = () => {
const configContent = document.getElementById('content-cost-config');
if (!configContent) return;
configContent.innerHTML = `
Configure Costs & Margins
`;
document.getElementById('cost-config-form').addEventListener('submit', handleCostConfigUpdate);
};
const renderDiscountConfig = () => {
const configContent = document.getElementById('content-discount-config');
if (!configContent) return;
let tiersHtml = appData.discounts.sort((a,b) => a.quantity - b.quantity).map((tier, index) => `
`).join('');
configContent.innerHTML = `
Configure Volume Discounts
Minimum Quantity
Discount (%)
${tiersHtml}
`;
lucide.createIcons();
attachDiscountConfigListeners();
};
// --- EVENT HANDLERS ---
const attachEstimatorListeners = () => {
const quantityInput = document.getElementById('quote-quantity');
const feeInput = document.getElementById('customization-fee');
const handler = () => {
appData.currentQuote.quantity = parseInt(quantityInput.value) || 0;
appData.currentQuote.customizationFee = parseFloat(feeInput.value) || 0;
renderEstimator();
};
quantityInput.addEventListener('input', handler);
feeInput.addEventListener('input', handler);
document.getElementById('download-pdf-btn').addEventListener('click', generatePdf);
};
const handleCostConfigUpdate = (e) => {
e.preventDefault();
appData.costs.material = parseFloat(document.getElementById('cost-material').value) || 0;
appData.costs.labor = parseFloat(document.getElementById('cost-labor').value) || 0;
appData.costs.overhead = parseFloat(document.getElementById('cost-overhead').value) || 0;
appData.margins.profit = parseFloat(document.getElementById('margin-profit').value) || 0;
appData.margins.contingency = parseFloat(document.getElementById('margin-contingency').value) || 0;
alert('Costs and margins updated!');
renderEstimator();
};
const attachDiscountConfigListeners = () => {
document.getElementById('add-tier-btn').addEventListener('click', () => {
appData.discounts.push({ quantity: 0, discount: 0 });
renderDiscountConfig();
});
document.querySelectorAll('.remove-tier-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const index = parseInt(e.currentTarget.dataset.index);
appData.discounts.splice(index, 1);
renderDiscountConfig();
});
});
document.getElementById('save-discounts-btn').addEventListener('click', () => {
const newDiscounts = [];
document.querySelectorAll('#discount-tiers-container .grid').forEach(row => {
const quantity = parseFloat(row.querySelector('[data-field="quantity"]').value) || 0;
const discount = parseFloat(row.querySelector('[data-field="discount"]').value) || 0;
if (quantity > 0) newDiscounts.push({ quantity, discount });
});
appData.discounts = newDiscounts;
alert('Volume discounts updated!');
renderEstimator();
});
};
const generatePdf = () => {
loadingOverlay.style.display = 'flex';
const { jsPDF } = window.jspdf;
const pdfContent = document.getElementById('pdf-content-area');
const pdfHeader = document.getElementById('pdf-header');
document.getElementById('pdf-generated-date').textContent = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
pdfHeader.classList.remove('hidden');
html2canvas(pdfContent, { scale: 2, useCORS: true, logging: false })
.then(canvas => {
pdfHeader.classList.add('hidden');
const imgData = canvas.toDataURL('image/jpeg', 0.95);
const pdf = new jsPDF({ orientation: 'portrait', unit: 'px', format: 'a4' });
const pdfWidth = pdf.internal.pageSize.getWidth();
const imgProps = pdf.getImageProperties(imgData);
const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, imgHeight);
pdf.save('B2B-Pricing-Quote.pdf');
loadingOverlay.style.display = 'none';
}).catch(err => {
console.error("PDF generation failed:", err);
pdfHeader.classList.add('hidden');
loadingOverlay.style.display = 'none';
alert('An error occurred generating the PDF.');
});
};
// --- TAB NAVIGATION & INITIALIZATION ---
const switchTab = (tabIndex) => {
activeTabIndex = tabIndex;
document.querySelectorAll('.tab-btn').forEach((btn, i) => btn.classList.toggle('active', i === tabIndex));
document.querySelectorAll('.tab-content').forEach((content, i) => content.classList.toggle('hidden', i !== tabIndex));
updateNavButtons();
};
const updateNavButtons = () => {
prevTabBtn.disabled = activeTabIndex === 0;
nextTabBtn.disabled = activeTabIndex === tabIdentifiers.length - 1;
};
const initializeUI = () => {
const tabs = [
{ name: 'Pricing Estimator', id: 'estimator' },
{ name: 'Cost & Margin Config', id: 'cost-config' },
{ name: 'Volume Discounts', id: 'discount-config' }
];
tabIdentifiers = tabs.map(t => t.id);
tabsContainer.innerHTML = tabs.map(tab => ``).join('');
mainContent.innerHTML = tabs.map(tab => ``).join('');
tabs.forEach((tab, index) => {
document.getElementById(`tab-${tab.id}`).addEventListener('click', () => switchTab(index));
});
renderEstimator();
renderCostConfig();
renderDiscountConfig();
switchTab(0);
};
initializeUI();
prevTabBtn.addEventListener('click', () => { if (activeTabIndex > 0) switchTab(activeTabIndex - 1); });
nextTabBtn.addEventListener('click', () => { if (activeTabIndex < tabIdentifiers.length - 1) switchTab(activeTabIndex + 1); });
});