jQuery(document).ready(function ($) {
	$('form.prevent-default').on('submit', function (e) {
		e.preventDefault();
	});
	// Register the plugin globally (only needed once)
	Chart.register(ChartDataLabels);

	const updateChart = (principal, interest) => {
		// Using jQuery to select the canvas
		const $element = $('#mortgage-payment-chart');

		// Prepare data
		const data = {
			labels: ['Principal', 'Interest'],
			datasets: [
				{
					data: [principal, interest],
					backgroundColor: ['#9D0612', '#000000'], // slice background colors
				},
			],
		};

		// Configure chart options
		const options = {
			plugins: {
				legend: {
					display: false, // Hide default legend
				},
				tooltip: {
					enabled: false, // Disable tooltips
				},
				datalabels: {
					// White labels for both slices
					font: {
						align: 'center',
						size: 14,
						weight: 'bold',
					},
					color: (context) => {
						return '#ffffff';
					},
					// Format each slice label: "Label\n$Value\nPercentage%"
					formatter: (value, context) => {
						const label =
							context.chart.data.labels[context.dataIndex];
						const dataset = context.dataset.data;
						const total = dataset.reduce(
							(acc, val) => acc + val,
							0
						);
						const percentage =
							((value / total) * 100).toFixed(1) + '%';

						// Format value as currency with two decimals, e.g. $200.00
						const formattedValue = `$${value.toFixed(2)}`;

						return `${label}\n${formattedValue}\n${percentage}`;
					},
					align: 'center',
					anchor: 'center',
				},
			},
		};

		// If the chart already exists on this canvas, destroy it before re-creating
		if ($element[0].chartInstance) {
			$element[0].chartInstance.destroy();
		}

		// Create the pie chart
		const ctx = $element[0].getContext('2d');
		const chartInstance = new Chart(ctx, {
			type: 'pie',
			data,
			options,
		});

		// Store reference if you want to update/destroy later
		$element[0].chartInstance = chartInstance;
	};

	function recalcMortgage() {
		// 1. Read input values
		let propertyPrice = parseFloat($('#property-price').val()) || 0;
		let downPayment = parseFloat($('#down-payment').val()) || 0;
		let lengthVal = $('#length-of-mortgage').val() || '0';
		let interestVal = $('#interest-rate').val() || '0';

		// If your fields contain masking (like "30 years" or "6%"), you'll need
		// to remove non-numeric characters:
		lengthVal = lengthVal.replace(/\D/g, ''); // strip all non-digits
		interestVal = interestVal.replace(/[^\d.]/g, ''); // keep digits/dot

		let lengthYears = parseInt(lengthVal, 10) || 0;
		let annualInterestRate = parseFloat(interestVal) || 0;

		// 2. Compute principal, monthly interest rate, and total months
		let principal = propertyPrice - downPayment;
		let monthlyInterestRate = annualInterestRate / 100 / 12;
		let numberOfMonthlyPeriods = lengthYears * 12;

		// Safety check: avoid negative principal
		if (0 > principal) {
			principal = 0;
		}

		// 3. Calculate monthly mortgage payment (standard formula)
		//    Payment = P * ( i * (1 + i)^n ) / ( (1 + i)^n - 1 )
		//    where:
		//         P = principal
		//         i = monthlyInterestRate
		//         n = numberOfMonthlyPeriods
		let monthlyPayment = 0;
		if (0 < numberOfMonthlyPeriods && 0 < monthlyInterestRate) {
			monthlyPayment =
				(principal *
					(monthlyInterestRate *
						Math.pow(
							1 + monthlyInterestRate,
							numberOfMonthlyPeriods
						))) /
				(Math.pow(1 + monthlyInterestRate, numberOfMonthlyPeriods) - 1);
		} else if (0 < numberOfMonthlyPeriods) {
			// If interest rate = 0, simply divide principal across months
			monthlyPayment = principal / numberOfMonthlyPeriods;
		}

		// 4. Calculate first-month interest portion and principal portion
		//    (Note that in reality, these portions change each month as you amortize)
		let firstMonthInterest = principal * monthlyInterestRate;
		let firstMonthPrincipal = monthlyPayment - firstMonthInterest;

		const monthlyPaymentOutput = `
			<p class="mb-2"><strong><u>Estimated Payments</u></strong></p>
			<table class="mb-5">
			<tr><td>Payment</td><td>$${monthlyPayment.toFixed(2)}</td></tr>
			<tr><td colspan="2"><p class="my-2"><strong><u>Estimated Breakdown</u></strong></p></td></tr>
			<tr><td>Principal</td><td>$${firstMonthPrincipal.toFixed(2)}</td></tr>
			<tr><td>Interest</td><td>$${firstMonthInterest.toFixed(2)}</td></tr>
			</table>
		
		`;

		// 5. Output results (format to two decimals, etc.)
		$('#monthly-payment').html(monthlyPaymentOutput);

		updateChart(firstMonthPrincipal, firstMonthInterest);
	}

	// When any of these fields change, recalculate:
	$(
		'#property-price, #down-payment, #down-payment-percentage, #length-of-mortgage, #interest-rate'
	).on('input', function () {
		recalcMortgage();
	});

	// Run once on page load to populate the initial display
	recalcMortgage();

	$('#interest-rate, #down-payment-percentage').inputmask({
		mask: '99%',
		placeholder: '',
		greedy: false,
		numericInput: true,
	});

	$('#down-payment, #property-price').inputmask({
		alias: 'numeric',
		prefix: '$', // Always show "$"
		groupSeparator: ',', // Use commas for thousands
		autoGroup: true, // Only add commas when needed
		digits: 0, // No decimal places
		allowMinus: false, // No negative values
		rightAlign: false, // Align left like normal input
		placeholder: '', // Start blank
		showMaskOnHover: false,
		showMaskOnFocus: false,
	});

	$('#length-of-mortgage').inputmask({
		mask: '99 ye\\ars', // Escape the "a" in "years"
		placeholder: '', // Start blank
		showMaskOnHover: false,
		showMaskOnFocus: false,
		greedy: false,
		definitions: {
			9: {
				validator: '[0-9]', // Allow only numbers
				cardinality: 1,
			},
		},
	});
});
