/**
 * Global variables
 */
var $kan        = jQuery(document),
		$window     = jQuery(window),
		intialWidth = window.innerWidth,
		kan_loader  = '<div class="kanews-loader kanews-loader-sm">Loading...</div>';
		kan_loader2  = '<div class="kanews-loader kanews-loader-md">Loading...</div>';

(function($) {
	"use strict";

	/**
	 * Calculator Functions
	 */
	const KanewsCalculator = {
		init() {
			this.setupCurrencyCalculator();
			this.setupCryptoCalculator();
			this.setupBMICalculator();
			this.setupExchangeIconHandler();
			this.updateCalculatorInfo();
			this.setupHoroscopeCalculator();
			this.setupCreditCalculator();
			this.setupSavingsCalculator();
			// Setup commodity calculator if it exists on page load
			this.setupCommodityCalculator();
			this.setupDefaultCalculator();
			this.setupCalculatorSwitcher();
		},

		setupDefaultCalculator() {
			// Check if calculator container already has content (initial load)
			const $calculatorContainer = $('.kanews-calculator-container');
			const $existingForm = $calculatorContainer.find('form');
			
			// If form already exists, determine calculator type from form ID
			if ($existingForm.length) {
				const formId = $existingForm.attr('id');
				const calcTypeMap = {
					'doviz_calc': 'doviz',
					'coin_calc': 'coin',
					'emtia_calc': 'emtia',
					'burc_calc': 'burc',
					'kredi_calc': 'kredi',
					'birikim_calc': 'birikim'
				};
				
				const existingCalcType = calcTypeMap[formId];
				if (existingCalcType) {
					// Check if there are tabs and if the active tab matches
					const $activeTab = $('.calculator-tab.active');
					const $tabs = $('.calculator-tab');
					
					// If tabs exist, check if active tab matches the existing calculator
					if ($tabs.length > 0) {
						const activeCalcType = $activeTab.length ? $activeTab.data('calculator') : null;
						if (activeCalcType === existingCalcType) {
							// Calculator already loaded and tab is active, just initialize it
							this.initCalculator(existingCalcType);
							return;
						}
					} else {
						// No tabs, calculator already loaded, just initialize it
						this.initCalculator(existingCalcType);
						return;
					}
				}
			}
			
			// Get default calculator from URL parameter or active tab or use 'doviz' as default
			const urlParams = new URLSearchParams(window.location.search);
			const urlCalc = urlParams.get('calculator');
			const $activeTab = $('.calculator-tab.active');
			const activeTabCalc = $activeTab.length ? $activeTab.data('calculator') : null;
			const defaultCalc = urlCalc || activeTabCalc || 'doviz';
			
			// Find and click the default calculator tab
			const $calculatorTab = $(`.calculator-tab[data-calculator="${defaultCalc}"]`);
			if ($calculatorTab.length) {
				$calculatorTab.trigger('click');
			} else if ($('.calculator-tab').length > 0) {
				// If no specific calculator is found, trigger the first tab
				$('.calculator-tab:first').trigger('click');
			}
		},

		setupCalculatorSwitcher() {
			// Store reference to this object
			const self = this;
			
			// Check if calculator container already has content (initial load)
			const $calculatorContainer = $('.kanews-calculator-container');
			const $existingForm = $calculatorContainer.find('form');
			const $activeTab = $('.calculator-tab.active');
			
			// If form already exists, check if it matches the active tab
			if ($existingForm.length && $activeTab.length) {
				const formId = $existingForm.attr('id');
				const calcTypeMap = {
					'doviz_calc': 'doviz',
					'coin_calc': 'coin',
					'emtia_calc': 'emtia',
					'burc_calc': 'burc',
					'kredi_calc': 'kredi',
					'birikim_calc': 'birikim'
				};
				
				const existingCalcType = calcTypeMap[formId];
				const activeTabCalc = $activeTab.data('calculator');
				
				if (existingCalcType && existingCalcType === activeTabCalc) {
					// Calculator already loaded and matches active tab, just initialize it
					this.initCalculator(existingCalcType);
					// Continue to set up click handlers below
				}
			}
			
			// Handle calculator tab clicks
			$('.calculator-tab').on('click', function(e) {
				e.preventDefault();
				const $this = $(this);
				const calculatorType = $this.data('calculator');
				const $calculatorContainer = $('.kanews-calculator-container');
				const $currentForm = $calculatorContainer.find('form');
				
				// Update active state
				$('.calculator-tab').removeClass('active');
				$this.addClass('active');
				
				// Show loading state while keeping the current form
				const $loader = $('<div class="kanews-loader-2 kanews-loader-sm">Loading...</div>');
				$calculatorContainer.append($loader);
				
				// Load calculator content via AJAX
				$.ajax({
					url: kan_vars.ajax,
					type: 'POST',
					data: {
						action: 'kanews_load_calculator',
						calculator: calculatorType,
						nonce: kan_vars.nonce
					},
					success: function(response) {
						if (response.success) {
							// Remove loader and current form
							$loader.remove();
							$currentForm.remove();
							
							// Add new calculator content
							$calculatorContainer.html(response.data.html);
							
							// Initialize the new calculator
							switch(calculatorType) {
								case 'doviz':
									self.setupCurrencyCalculator();
									break;
								case 'coin':
									self.setupCryptoCalculator();
									break;
								case 'emtia':
									self.setupCommodityCalculator();
									break;
								case 'burc':
									self.setupHoroscopeCalculator();
									break;
								case 'vki':
									self.setupBMICalculator();
									break;
								case 'kredi':
									self.setupCreditCalculator();
									break;
								case 'birikim':
									self.setupSavingsCalculator();
									break;
								case 'vergi':
									self.setupTaxCalculator();
									break;
							}
							
							// Setup exchange icon handler for the new calculator
							self.setupExchangeIconHandler();
							
							// Update calculator info
							self.updateCalculatorInfo();
						} else {
							$loader.remove();
							$calculatorContainer.html('<div class="alert alert-danger">Hesaplayıcı yüklenirken bir hata oluştu.</div>');
						}
					},
					error: function() {
						$loader.remove();
						$calculatorContainer.html('<div class="alert alert-danger">Hesaplayıcı yüklenirken bir hata oluştu.</div>');
					}
				});
			});
		},

		updateCalculatorInfo() {
			// Currency calculator info update
			const updateCurrencyInfo = () => {
				const calc = $('#doviz_calc');
				if (!calc.length) return;

				const from = calc.find('.currency_switcher_x option:selected');
				const to = calc.find('.currency_switcher_2 option:selected');
				const amount = parseFloat(calc.find('.currency3value').val());
				const result = (amount * from.val() / to.val()).toLocaleString('tr-TR', {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				});

				// Format and display the selected value
				const selectedValue = parseFloat(from.val()).toFixed(2);
				const formattedValue = selectedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
				calc.find('.selected-value').text(formattedValue);
				
				// Add conversion info
				calc.find('.conversion-info').text(`${amount} ${from.text()} = ${result} ${to.text()}`);
			};

			// Crypto calculator info update
			const updateCryptoInfo = () => {
				const calc = $('#coin_calc');
				if (!calc.length) return;

				const crypto = calc.find('.currency_switcher_x option:selected');
				const currency = calc.find('.currency_switcher_3 option:selected');
				const amount = parseFloat(calc.find('.currency5value').val());
				const result = (amount * crypto.val() / currency.val()).toLocaleString('tr-TR', {
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				});
				
				// Format and display the selected value
				const selectedValue = parseFloat(crypto.val()).toFixed(2);
				const formattedValue = selectedValue.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
				calc.find('.selected-value').text(formattedValue);
				
				// Add conversion info
				calc.find('.conversion-info').text(`${amount} ${crypto.text()} = ${result} ${currency.text()}`);
			};

			// Commodity calculator info update
			const updateCommodityInfo = () => {
				const calc = $('#emtia_calc');
				if (!calc.length) return;

				const amount = parseFloat(calc.find('.currency3value').val().replace(/[^0-9.-]+/g, ''));
				const fromRate = parseFloat(calc.find('.currency_switcher_x').val());
				const toRate = parseFloat(calc.find('.currency_switcher_2').val());
				
				if (!isNaN(amount) && !isNaN(fromRate) && !isNaN(toRate)) {
					const result = (amount * fromRate / toRate).toLocaleString('tr-TR', {
						minimumFractionDigits: 2,
						maximumFractionDigits: 2
					});
					calc.find('.currency4value').val(result);
				}
			};

			// Initial update
			updateCurrencyInfo();
			updateCryptoInfo();
			updateCommodityInfo();

			// Update on select change
			$('.currency_switcher_x, .currency_switcher_2, .currency_switcher_3').on('change', function() {
				const form = $(this).closest('form');
				const formId = form.attr('id');
				
				if (formId === 'doviz_calc') {
					// Check if this is a commodity calculator
					const isCommodityCalc = form.find('[value="XAU"]').length > 0 || 
										   form.hasClass('commodity-calculator');
					
					if (isCommodityCalc) {
						updateCommodityInfo();
					} else {
						updateCurrencyInfo();
					}
				} else if (formId === 'coin_calc') {
					updateCryptoInfo();
				}
			});
			
			// Update on input change
			$('.currency3value, .currency5value').on('input', function() {
				const form = $(this).closest('form');
				const formId = form.attr('id');
				
				if (formId === 'doviz_calc') {
					// Check if this is a commodity calculator
					const isCommodityCalc = form.find('[value="XAU"]').length > 0 || 
										   form.hasClass('commodity-calculator');
					
					if (isCommodityCalc) {
						updateCommodityInfo();
					} else {
						updateCurrencyInfo();
					}
				} else if (formId === 'coin_calc') {
					updateCryptoInfo();
				}
			});

			// Auto update every minute
			setInterval(() => {
				updateCurrencyInfo();
				updateCryptoInfo();
				updateCommodityInfo();
			}, 60000);
		},

		setupCurrencyCalculator() {
			const calc = $('#doviz_calc');
			if (!calc.length) return;

			const updateValues = () => {
				const amount = parseFloat(calc.find('.currency3value').val());
				const fromRate = parseFloat(calc.find('.currency_switcher_x').val());
				const toRate = parseFloat(calc.find('.currency_switcher_2').val());
				
				if (!isNaN(amount) && !isNaN(fromRate) && !isNaN(toRate)) {
					const result = (amount * fromRate / toRate).toLocaleString('tr-TR', {
						minimumFractionDigits: 2,
						maximumFractionDigits: 2
					});
					calc.find('.currency4value').val(result);
				}
			};

			calc.on('input change', '.currency3value, .currency_switcher_x, .currency_switcher_2', updateValues);
			updateValues();
		},

		setupCryptoCalculator() {
			const calc = $('#coin_calc');
			if (!calc.length) return;

			const updateValues = () => {
				const amount = parseFloat(calc.find('.currency5value').val().replace(/\./g, '').replace(',', '.'));
				const fromRate = parseFloat(calc.find('.currency_switcher_x').val());
				const toRate = parseFloat(calc.find('.currency_switcher_3').val());
				
				if (!isNaN(amount) && !isNaN(fromRate) && !isNaN(toRate)) {
					const result = (amount * fromRate / toRate).toLocaleString('tr-TR', {
						minimumFractionDigits: 2,
						maximumFractionDigits: 2
					});
					calc.find('.currency6value').val(result);
				}
			};

			calc.on('input change', '.currency5value, .currency_switcher_x, .currency_switcher_3', updateValues);
			updateValues();
		},


		setupBMICalculator() {
			const form = $('form[name="BedenKitleEndeksi"]');
			if (!form.length) return;

			form.on('click', '[type="button"]', () => {
				const weight = parseFloat($('#kilosu').val());
				const height = parseFloat($('#boyu').val());

				if (!weight || !height || weight <= 0 || height <= 0) {
					alert('Lütfen geçerli boy ve kilo değerleri girin.');
					return;
				}

				const bmi = weight / ((height / 100) ** 2);
				const bmiValue = bmi.toFixed(2);

				let result;
				if (bmi < 18.5) result = 'Zayıf';
				else if (bmi < 25) result = 'İdeal Kilo';
				else if (bmi < 30) result = 'Fazla Kilolu';
				else if (bmi < 35) result = '1. Derece Obez';
				else if (bmi < 40) result = '2. Derece Obez';
				else result = '3. Derece Morbid Obez';

				// Update info area
				form.find('.bmi-value').text(bmiValue);
				form.find('.bmi-result').text(result);
			});

			form.on('reset', () => {
				form.find('.bmi-value').text('-');
				form.find('.bmi-result').text('-');
			});
		},

		setupExchangeIconHandler() {
			$('.exchange-icon').on('click', function() {
				const form = $(this).closest('form');
				const select1 = form.find('select').eq(0);
				const select2 = form.find('select').eq(1);
				
				// Make to currency equal from currency
				select2.val(select1.val());
				
				// Trigger change event to update calculation
				select2.trigger('change');
			});
		},

		setupHoroscopeCalculator() {
			const horoscopeCalc = document.getElementById('horoscope_calculate');
			if (!horoscopeCalc) return;
			
			horoscopeCalc.addEventListener('click', function() {
				const signSelect = document.getElementById('horoscope_sign');
				const periodSelect = document.getElementById('horoscope_period');
				
				if (!signSelect.value) {
					alert('Lütfen bir burç seçiniz.');
					return;
				}
				
				const horoscopeData = document.getElementById('horoscope-data');
				const signData = JSON.parse(horoscopeData.getAttribute('data-' + signSelect.value));
				const period = periodSelect.value;
				
				document.getElementById('horoscope_icon').src = signData.icon;
				document.getElementById('horoscope_title').textContent = signData.name;
				document.getElementById('horoscope_date').textContent = signData.date;
				document.getElementById('horoscope_text').textContent = signData[period];
				
				document.getElementById('horoscope_result').style.display = 'block';
				
				document.querySelector('.selected-value').textContent = signData.name;
				
				const periodLabels = {
					'gunluk': 'Günlük',
					'haftalik': 'Haftalık',
					'aylik': 'Aylık',
					'yillik': 'Yıllık'
				};
				document.querySelector('.conversion-info').textContent = periodLabels[period];
			});
		},

		setupCreditCalculator() {
			const form = $('#kredi_calc');
			if (!form.length) return;

			// Format currency function
			const formatCurrency = (value) => {
				return new Intl.NumberFormat('tr-TR', {
					style: 'currency',
					currency: 'TRY',
					minimumFractionDigits: 2,
					maximumFractionDigits: 2
				}).format(value);
			};

			// Calculate equal installment payment (PMT formula)
			const calculateEqualInstallmentPayment = (principal, rate, term) => {
				// Convert annual rate to monthly rate
				const monthlyRate = rate / 100 / 12;
				// Calculate monthly payment using PMT formula
				return principal * monthlyRate * Math.pow(1 + monthlyRate, term) / (Math.pow(1 + monthlyRate, term) - 1);
			};

			// Calculate equal principal payment
			const calculateEqualPrincipalPayment = (principal, rate, term) => {
				// Monthly principal payment
				const monthlyPrincipal = principal / term;
				// First month's interest
				const firstMonthInterest = principal * (rate / 100 / 12);
				// First month's total payment
				return monthlyPrincipal + firstMonthInterest;
			};

			// Calculate total payments
			const calculateTotalPayments = (principal, rate, term, paymentType) => {
				const monthlyRate = rate / 100 / 12;
				
				if (paymentType === 'esit_taksit') {
					// Equal installment: monthly payment is the same every month
					const monthlyPayment = calculateEqualInstallmentPayment(principal, rate, term);
					return monthlyPayment * term;
				} else {
					// Equal principal: interest decreases each month
					let totalPayment = 0;
					const monthlyPrincipal = principal / term;
					let remainingPrincipal = principal;
					
					for (let i = 0; i < term; i++) {
						const monthlyInterest = remainingPrincipal * monthlyRate;
						totalPayment += monthlyPrincipal + monthlyInterest;
						remainingPrincipal -= monthlyPrincipal;
					}
					
					return totalPayment;
				}
			};

			// Update form on calculate button click
			$('#kredi_calculate').on('click', function() {
				// Get input values
				const principal = parseFloat($('#kredi_amount').val().replace(/[^\d]/g, ''));
				const rate = parseFloat($('#kredi_interest').val().replace(/[^\d.]/g, ''));
				const term = parseInt($('#kredi_term').val());
				const paymentType = $('#kredi_type').val();
				
				// Validate inputs
				if (isNaN(principal) || isNaN(rate) || isNaN(term) || !term) {
					alert('Lütfen tüm alanları doğru formatta doldurunuz.');
					return;
				}
				
				let monthlyPayment;
				
				if (paymentType === 'esit_taksit') {
					// Equal installment payment (same amount every month)
					monthlyPayment = calculateEqualInstallmentPayment(principal, rate, term);
				} else {
					// Equal principal payment (first month's payment, decreases over time)
					monthlyPayment = calculateEqualPrincipalPayment(principal, rate, term);
				}
				
				// Calculate total payment and interest
				const totalPayment = calculateTotalPayments(principal, rate, term, paymentType);
				const totalInterest = totalPayment - principal;
				
				// Update result display
				form.find('.monthly-payment').text(formatCurrency(monthlyPayment));
				form.find('.total-payment').text(formatCurrency(totalPayment));
				form.find('.total-interest').text(formatCurrency(totalInterest));
				
				// Add note for equal principal payment
				if (paymentType === 'esit_anapara') {
					form.find('.monthly-payment').append(' <small>(ilk ay)</small>');
				}
			});
			
			// Format input fields
			$('#kredi_amount').on('input', function() {
				let value = $(this).val().replace(/[^\d]/g, '');
				if (value) {
					// Format as currency without decimals
					const numericValue = parseInt(value);
					if (!isNaN(numericValue)) {
						const formattedValue = new Intl.NumberFormat('tr-TR', {
							maximumFractionDigits: 0
						}).format(numericValue);
						$(this).val(formattedValue);
					}
				}
			});
			
			$('#kredi_interest').on('input', function() {
				let value = $(this).val().replace(/[^\d.]/g, '');
				if (value) {
					// Allow only one decimal point
					const parts = value.split('.');
					if (parts.length > 2) {
						value = parts[0] + '.' + parts.slice(1).join('');
					}
					
					// Limit to 2 decimal places if there's a decimal point
					if (value.includes('.')) {
						const decimalParts = value.split('.');
						value = decimalParts[0] + '.' + decimalParts[1].substring(0, 2);
					}
					
					$(this).val(value);
				}
			});
		},

		
		setupSavingsCalculator: function() {
			if (!document.getElementById('birikim_calc')) return;

			const calculateSavings = () => {
				const initialDeposit = parseFloat(document.getElementById('savings_initial').value.replace(/[^\d.]/g, '')) || 0;
				const monthlyContribution = parseFloat(document.getElementById('savings_monthly').value.replace(/[^\d.]/g, ''));
				const annualInterestRate = parseFloat(document.getElementById('savings_interest').value.replace(/[^\d.]/g, ''));
				const years = parseFloat(document.getElementById('savings_years').value.replace(/[^\d.]/g, ''));
				
				if (isNaN(monthlyContribution) || monthlyContribution <= 0) {
					alert('Lütfen geçerli bir aylık katkı tutarı giriniz.');
					return;
				}
				
				if (isNaN(annualInterestRate) || annualInterestRate <= 0) {
					alert('Lütfen geçerli bir faiz oranı giriniz.');
					return;
				}
				
				if (isNaN(years) || years <= 0) {
					alert('Lütfen geçerli bir birikim süresi giriniz.');
					return;
				}
				
				// Convert annual interest rate to monthly
				const monthlyRate = annualInterestRate / 100 / 12;
				const totalMonths = years * 12;
				
				// Formula for future value with regular contributions
				const futureValueOfDeposit = initialDeposit * Math.pow(1 + monthlyRate, totalMonths);
				const futureValueOfContributions = monthlyContribution * ((Math.pow(1 + monthlyRate, totalMonths) - 1) / monthlyRate);
				
				const totalFutureValue = futureValueOfDeposit + futureValueOfContributions;
				const totalContributions = initialDeposit + (monthlyContribution * totalMonths);
				const totalInterest = totalFutureValue - totalContributions;
				
				document.getElementById('total_savings_value').textContent = this.formatMoney(totalFutureValue.toFixed(2)) + ' TL';
				document.getElementById('total_contribution_value').textContent = this.formatMoney(totalContributions.toFixed(2)) + ' TL';
				document.getElementById('total_interest_value').textContent = this.formatMoney(totalInterest.toFixed(2)) + ' TL';
				
				// Show the results
				document.querySelector('.savings-breakdown').style.display = 'block';
			};

			document.getElementById('savings_calculate').addEventListener('click', calculateSavings);
		},
		


		formatMoney: function(value) {
			return new Intl.NumberFormat('tr-TR', {
				style: 'currency',
				currency: 'TRY',
				minimumFractionDigits: 2,
				maximumFractionDigits: 2
			}).format(value);
		},

		initCalculator(type) {
			switch(type) {
				case 'doviz':
					this.setupCurrencyCalculator();
					break;
				case 'coin':
					this.setupCryptoCalculator();
					break;
				case 'emtia':
					this.setupCommodityCalculator();
					break;
				case 'burc':
					this.setupHoroscopeCalculator();
					break;
				case 'vki':
					this.setupBMICalculator();
					break;
				case 'kredi':
					this.setupCreditCalculator();
					break;
				case 'birikim':
					this.setupSavingsCalculator();
					break;
				case 'birimcevir':
					this.setupUnitCalculator();
					break;
				case 'enflasyon':
					this.setupInflationCalculator();
					break;
				case 'vergi':
					this.setupTaxCalculator();
					break;
			}
			
			// Setup exchange icon handler for the new calculator
			this.setupExchangeIconHandler();
			
			// Update calculator info
			this.updateCalculatorInfo();
		},

		setupCommodityCalculator() {
			const $form = $('#emtia_calc');
			if (!$form.length) return;

			const updateValues = () => {
				const $fromSelect = $form.find('.currency_switcher_x');
				const $toSelect = $form.find('.currency_switcher_2');
				const $amountInput = $form.find('.currency3value');
				
				// Check if elements exist
				if (!$fromSelect.length || !$toSelect.length || !$amountInput.length) {
					return;
				}
				
				const fromValue = parseFloat($fromSelect.val());
				const toValue = parseFloat($toSelect.val());
				const amountStr = $amountInput.val() || '1';
				const amount = parseFloat(amountStr.replace(/[^0-9.-]+/g, '')) || 1;

				if (isNaN(fromValue) || isNaN(toValue) || isNaN(amount) || fromValue === 0 || toValue === 0) {
					$form.find('.currency4value').val('?');
					$form.find('.conversion-info').text('-');
					$form.find('.selected-value').text('0.00');
					return;
				}

				const result = (amount * fromValue) / toValue;
				$form.find('.currency4value').val(result.toFixed(2));

				// Update calculator info
				const fromCurrency = $fromSelect.find('option:selected').text().trim();
				const toCurrency = $toSelect.find('option:selected').text().trim();
				$form.find('.conversion-info').text(`${amount} ${fromCurrency} = ${(amount * fromValue).toFixed(2)} ${toCurrency}`);
				$form.find('.selected-value').text(fromValue.toFixed(2));
			};

			// Remove existing event handlers to prevent duplicates
			$form.find('.currency_switcher_x, .currency_switcher_2').off('change', updateValues);
			$form.find('.currency3value').off('input', updateValues);
			
			// Update on any change to the form inputs
			$form.find('.currency_switcher_x, .currency_switcher_2').on('change', updateValues);
			$form.find('.currency3value').on('input', updateValues);
			
			// Initial update - try multiple times to ensure DOM is ready
			const tryUpdate = (attempts = 0) => {
				if (attempts > 5) return; // Max 5 attempts
				
				const $fromSelect = $form.find('.currency_switcher_x');
				const $toSelect = $form.find('.currency_switcher_2');
				
				if ($fromSelect.length && $toSelect.length && $fromSelect.val() && $toSelect.val()) {
					updateValues();
				} else {
					setTimeout(() => tryUpdate(attempts + 1), 100);
				}
			};
			
			// Start trying to update
			setTimeout(() => tryUpdate(), 100);
		}
	};

	// Initialize calculators
	$(document).ready(() => {
		KanewsCalculator.init();
	});



})(jQuery);
