/**
 * Admin Dashboard - Charts and Feedback Forms
 *
 * @package KarateClubManager
 */

(function($) {
	'use strict';

	var macmDashboard = {
		charts: {},

		/**
		 * Initialize
		 */
		init: function() {
			this.bindEvents();
			this.initCharts();
		},

		/**
		 * Initialize Charts
		 */
		initCharts: function() {
			var self = this;

			// Wait for Chart.js to be available
			if (typeof Chart === 'undefined') {
				setTimeout(function() {
					self.initCharts();
				}, 100);
				return;
			}

			// Check if we have chart data
			if (!macmDashboardData.chartData) {
				return;
			}

			var chartData = macmDashboardData.chartData;

			// Initialize Attendance Trends Chart (Bar Chart)
			this.initAttendanceChart(chartData.attendance);

			// Initialize Belt Distribution Chart (Doughnut)
			this.initBeltChart(chartData.belt);

			// Initialize Membership Distribution Chart (Pie)
			this.initMembershipChart(chartData.membership);
		},

		/**
		 * Initialize Attendance Trends Chart
		 */
		initAttendanceChart: function(data) {
			var ctx = document.getElementById('kcm-attendance-chart');
			if (!ctx) return;

			// Check if we have data
			if (!data.labels || data.labels.length === 0) {
				$(ctx).hide();
				$('#kcm-attendance-no-data').show();
				return;
			}

			this.charts.attendance = new Chart(ctx, {
				type: 'bar',
				data: {
					labels: data.labels,
					datasets: [{
						label: macmDashboardData.i18n.attendance,
						data: data.data,
						backgroundColor: 'rgba(79, 172, 254, 0.8)',
						borderColor: 'rgba(79, 172, 254, 1)',
						borderWidth: 1,
						borderRadius: 4,
						borderSkipped: false
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							display: false
						},
						tooltip: {
							backgroundColor: 'rgba(0, 0, 0, 0.8)',
							titleFont: { size: 14 },
							bodyFont: { size: 13 },
							padding: 12,
							cornerRadius: 6
						}
					},
					scales: {
						y: {
							beginAtZero: true,
							ticks: {
								stepSize: 1,
								font: { size: 11 }
							},
							grid: {
								color: 'rgba(0, 0, 0, 0.05)'
							}
						},
						x: {
							ticks: {
								font: { size: 11 }
							},
							grid: {
								display: false
							}
						}
					}
				}
			});
		},

		/**
		 * Initialize Belt Distribution Chart
		 */
		initBeltChart: function(data) {
			var ctx = document.getElementById('kcm-belt-chart');
			if (!ctx) return;

			// Check if we have data
			if (!data.labels || data.labels.length === 0) {
				$(ctx).hide();
				$('#kcm-belt-no-data').show();
				return;
			}

			this.charts.belt = new Chart(ctx, {
				type: 'doughnut',
				data: {
					labels: data.labels,
					datasets: [{
						data: data.data,
						backgroundColor: data.colors,
						borderColor: '#fff',
						borderWidth: 2,
						hoverOffset: 8
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							position: 'right',
							labels: {
								padding: 15,
								usePointStyle: true,
								pointStyle: 'circle',
								font: { size: 11 }
							}
						},
						tooltip: {
							backgroundColor: 'rgba(0, 0, 0, 0.8)',
							titleFont: { size: 14 },
							bodyFont: { size: 13 },
							padding: 12,
							cornerRadius: 6,
							callbacks: {
								label: function(context) {
									var total = context.dataset.data.reduce(function(a, b) { return a + b; }, 0);
									var percentage = Math.round((context.raw / total) * 100);
									return context.label + ': ' + context.raw + ' (' + percentage + '%)';
								}
							}
						}
					},
					cutout: '60%'
				}
			});
		},

		/**
		 * Initialize Membership Distribution Chart
		 */
		initMembershipChart: function(data) {
			var ctx = document.getElementById('kcm-membership-chart');
			if (!ctx) return;

			// Check if we have data
			if (!data.labels || data.labels.length === 0 || data.data.every(function(v) { return v === 0; })) {
				$(ctx).hide();
				$('#kcm-membership-no-data').show();
				return;
			}

			this.charts.membership = new Chart(ctx, {
				type: 'pie',
				data: {
					labels: data.labels,
					datasets: [{
						data: data.data,
						backgroundColor: data.colors,
						borderColor: '#fff',
						borderWidth: 2,
						hoverOffset: 8
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							position: 'right',
							labels: {
								padding: 15,
								usePointStyle: true,
								pointStyle: 'circle',
								font: { size: 11 }
							}
						},
						tooltip: {
							backgroundColor: 'rgba(0, 0, 0, 0.8)',
							titleFont: { size: 14 },
							bodyFont: { size: 13 },
							padding: 12,
							cornerRadius: 6,
							callbacks: {
								label: function(context) {
									var total = context.dataset.data.reduce(function(a, b) { return a + b; }, 0);
									var percentage = Math.round((context.raw / total) * 100);
									return context.label + ': ' + context.raw + ' (' + percentage + '%)';
								}
							}
						}
					}
				}
			});
		},

		/**
		 * Bind events
		 */
		bindEvents: function() {
			var self = this;

			// Open modals
			$('#kcm-request-feature-btn').on('click', function(e) {
				e.preventDefault();
				self.openModal('#kcm-feature-request-modal');
			});

			$('#kcm-report-bug-btn').on('click', function(e) {
				e.preventDefault();
				self.openModal('#kcm-bug-report-modal');
			});

			// Close modals
			$('.kcm-modal-close, .kcm-modal-close-btn').on('click', function() {
				self.closeModals();
			});

			// Close modal when clicking outside
			$('.kcm-modal').on('click', function(e) {
				if ($(e.target).hasClass('kcm-modal')) {
					self.closeModals();
				}
			});

			// Form submissions
			$('#kcm-feature-request-form').on('submit', function(e) {
				e.preventDefault();
				self.submitFeatureRequest(this);
			});

			$('#kcm-bug-report-form').on('submit', function(e) {
				e.preventDefault();
				self.submitBugReport(this);
			});

			// Limit screenshot uploads to 3
			$('#bug-screenshots').on('change', function() {
				if (this.files.length > 3) {
					alert('You can only upload up to 3 screenshots.');
					this.value = '';
				}
			});
		},

		/**
		 * Open modal
		 */
		openModal: function(modalId) {
			$(modalId).fadeIn(200);
		},

		/**
		 * Close all modals
		 */
		closeModals: function() {
			$('.kcm-modal').fadeOut(200);
			// Reset forms
			$('#kcm-feature-request-form')[0].reset();
			$('#kcm-bug-report-form')[0].reset();
		},

		/**
		 * Submit feature request
		 */
		submitFeatureRequest: function(form) {
			var self = this;
			var $form = $(form);
			var $submitBtn = $form.find('button[type="submit"]');
			var originalText = $submitBtn.text();

			// Get form data
			var data = {
				action: 'macm_submit_feature_request',
				nonce: macmDashboardData.nonce,
				name: $('#feature-name').val(),
				email: $('#feature-email').val(),
				explanation: $('#feature-explanation').val()
			};

			// Disable button and show loading
			$submitBtn.prop('disabled', true).text('Submitting...');

			// Submit via AJAX
			$.ajax({
				url: ajaxurl,
				type: 'POST',
				data: data,
				success: function(response) {
					if (response.success) {
						alert('Thank you! Your feature request has been submitted successfully.');
						self.closeModals();
					} else {
						alert('Error: ' + (response.data.message || 'Failed to submit feature request.'));
					}
				},
				error: function() {
					alert('An error occurred. Please try again.');
				},
				complete: function() {
					$submitBtn.prop('disabled', false).text(originalText);
				}
			});
		},

		/**
		 * Submit bug report
		 */
		submitBugReport: function(form) {
			var self = this;
			var $form = $(form);
			var $submitBtn = $form.find('button[type="submit"]');
			var originalText = $submitBtn.text();

			// Prepare FormData for file uploads
			var formData = new FormData();
			formData.append('action', 'macm_submit_bug_report');
			formData.append('nonce', macmDashboardData.nonce);
			formData.append('url', $('#bug-url').val());
			formData.append('page', $('#bug-page').val());
			formData.append('description', $('#bug-description').val());

			// Add screenshots
			var files = $('#bug-screenshots')[0].files;
			for (var i = 0; i < files.length && i < 3; i++) {
				formData.append('screenshots[]', files[i]);
			}

			// Disable button and show loading
			$submitBtn.prop('disabled', true).text('Submitting...');

			// Submit via AJAX
			$.ajax({
				url: ajaxurl,
				type: 'POST',
				data: formData,
				processData: false,
				contentType: false,
				success: function(response) {
					if (response.success) {
						alert('Thank you! Your bug report has been submitted successfully.');
						self.closeModals();
					} else {
						alert('Error: ' + (response.data.message || 'Failed to submit bug report.'));
					}
				},
				error: function() {
					alert('An error occurred. Please try again.');
				},
				complete: function() {
					$submitBtn.prop('disabled', false).text(originalText);
				}
			});
		}
	};

	// Initialize on document ready
	$(document).ready(function() {
		macmDashboard.init();
	});

})(jQuery);
