/**
 * SiteStaffr Settings Page — admin JS
 *
 * Handles all interactive behaviour for the Settings admin page:
 *   - Copy phone-number button
 *   - Guidance modal open/close/escape
 *   - Business-name inline validation + AJAX save (business settings)
 *   - Business description & custom greeting character counters
 *   - Greeting tone preview audio
 *   - Business phone formatting
 *   - Test email send
 *   - Notification settings AJAX save
 *   - Business hours editor (radio choice + custom schedule builder)
 *   - Generate Description from Website button
 *
 * All PHP-injected values are consumed via `window.sitestaffrSettingsPageData`
 * (aliased as `d`). That object is populated by wp_localize_script() in the
 * plugin's admin class before this file is enqueued.
 *
 * @package SiteStaffr
 * @since   1.3.0
 */

(function( $ ) {
	'use strict';

	var d = window.sitestaffrSettingsPageData || {};

	$( document ).ready( function() {

		// ── Copy Phone Number Button ─────────────────────────────────────────

		$( '#sitestaffr-copy-settings-number' ).on( 'click', function() {
			var $button      = $( this );
			var number       = $button.data( 'number' );
			var $text        = $button.find( '.sitestaffr-copy-text' );
			var originalText = $text.text();

			if ( navigator.clipboard && navigator.clipboard.writeText ) {
				navigator.clipboard.writeText( number ).then( function() {
					$button.addClass( 'sitestaffr-copied' );
					$text.text( d.i18n.copied );

					setTimeout( function() {
						$button.removeClass( 'sitestaffr-copied' );
						$text.text( originalText );
					}, 2000 );
				} ).catch( function( err ) {
					console.error( 'Failed to copy:', err );
					alert( d.i18n.copyFailed );
				} );
			} else {
				// Fallback for older browsers.
				var tempInput = $( '<input>' );
				$( 'body' ).append( tempInput );
				tempInput.val( number ).select();
				try {
					document.execCommand( 'copy' );
					$button.addClass( 'sitestaffr-copied' );
					$text.text( d.i18n.copied );

					setTimeout( function() {
						$button.removeClass( 'sitestaffr-copied' );
						$text.text( originalText );
					}, 2000 );
				} catch ( err ) {
					alert( d.i18n.copyFailed );
				}
				tempInput.remove();
			}
		} );

		// ── Guidance Modal ───────────────────────────────────────────────────

		var $guidanceModal = $( '[data-sitestaffr-guidance-modal]' );

		$( '[data-sitestaffr-guidance-open]' ).on( 'click', function() {
			$guidanceModal.removeAttr( 'hidden' ).addClass( 'is-open' );
			$( 'body' ).addClass( 'sitestaffr-modal-open' );
		} );

		$( '[data-sitestaffr-guidance-close]' ).on( 'click', function() {
			$guidanceModal.removeClass( 'is-open' ).attr( 'hidden', true );
			$( 'body' ).removeClass( 'sitestaffr-modal-open' );
		} );

		$( document ).on( 'keydown', function( event ) {
			if ( event.key === 'Escape' && $guidanceModal.hasClass( 'is-open' ) ) {
				$guidanceModal.removeClass( 'is-open' ).attr( 'hidden', true );
				$( 'body' ).removeClass( 'sitestaffr-modal-open' );
			}
		} );

		// Prevent accidental Enter-key form submission — trigger AJAX save instead.
		$( '.sitestaffr-settings-form' ).on( 'submit', function( e ) {
			e.preventDefault();
			$( '#sitestaffr-save-business-settings' ).trigger( 'click' );
		} );

		// ── Inline Business Name Validation ─────────────────────────────────

		var $businessNameField       = $( 'input[name="sitestaffr_settings\\[business_name\\]"]' );
		var $businessNameInlineError = null;
		var businessNameTouched      = false;

		if ( $businessNameField.length ) {
			$businessNameInlineError = $( '<p id="sitestaffr-business-name-inline-error" class="description" style="display:none;color:#dc3232;margin-top:6px;"></p>' );
			$businessNameField.after( $businessNameInlineError );
		}

		function validateBusinessNameInline( showFeedback ) {
			if ( ! $businessNameField.length ) {
				return true;
			}
			var value   = ( $businessNameField.val() || '' ).trim();
			var isValid = value.length > 0;

			if ( ! isValid ) {
				$businessNameField.attr( 'aria-invalid', 'true' );
				if ( showFeedback && $businessNameInlineError ) {
					$businessNameInlineError.text( d.i18n.businessNameRequired ).show();
				}
			} else {
				$businessNameField.removeAttr( 'aria-invalid' );
				if ( $businessNameInlineError ) {
					$businessNameInlineError.hide().text( '' );
				}
			}

			return isValid;
		}

		$businessNameField.on( 'blur', function() {
			businessNameTouched = true;
			validateBusinessNameInline( true );
		} );

		$businessNameField.on( 'input', function() {
			var value = ( $businessNameField.val() || '' ).trim();
			if ( businessNameTouched || value.length === 0 ) {
				validateBusinessNameInline( true );
			} else {
				validateBusinessNameInline( false );
			}
		} );

		// ── Save Business Settings (AJAX) ────────────────────────────────────

		$( '#sitestaffr-save-business-settings' ).on( 'click', function() {
			var $button     = $( this );
			var $buttonText = $button.find( '.sitestaffr-save-business-text' );
			var $icon       = $button.find( '.dashicons' );
			var $status     = $( '#sitestaffr-business-save-status' );
			var originalText = $buttonText.text();

			var businessName        = $( 'input[name="sitestaffr_settings\\[business_name\\]"]' ).val();
			var businessPhone       = $( 'input[name="sitestaffr_settings\\[business_phone\\]"]' ).val();
			var businessContext     = $( 'textarea[name="sitestaffr_settings\\[business_context\\]"]' ).val();
			var customGreeting      = $( 'input[name="sitestaffr_settings\\[custom_greeting\\]"]' ).val() || '';
			var customGreetingTone  = $( 'select[name="sitestaffr_settings\\[custom_greeting_tone\\]"]' ).val() || 'warm_neutral';
			var businessHours       = $( 'input[name="sitestaffr_settings\\[business_hours\\]"]' ).val();
			var aiVoice             = $( 'select[name="sitestaffr_settings\\[ai_voice\\]"]' ).val();

			businessName = ( businessName || '' ).trim();
			if ( ! validateBusinessNameInline( true ) ) {
				$status.html( '<span style="color: #dc3232;">' + d.i18n.businessNameRequired + '</span>' );
				$( 'input[name="sitestaffr_settings\\[business_name\\]"]' ).trigger( 'focus' );
				return;
			}

			customGreeting = customGreeting.replace( /[\r\n\t]+/g, ' ' );
			customGreeting = customGreeting.replace( /\s+/g, ' ' ).trim();
			customGreeting = customGreeting.replace( /[\u2600-\u27BF]|[\uD83C-\uDBFF][\uDC00-\uDFFF]|\u200D|\uFE0F/g, '' );
			if ( customGreeting.length > 250 ) {
				customGreeting = customGreeting.substring( 0, 250 );
			}
			$( 'input[name="sitestaffr_settings\\[custom_greeting\\]"]' ).val( customGreeting );

			// Show loading state.
			$button.prop( 'disabled', true );
			$icon.removeClass( 'dashicons-saved' ).addClass( 'dashicons-update spin' );
			$buttonText.text( d.i18n.saving );
			$status.html( '' );

			$.ajax( {
				url:  ajaxurl,
				type: 'POST',
				data: {
					action:               'sitestaffr_save_business_settings',
					nonce:                d.nonces.admin,
					business_name:        businessName,
					business_phone:       businessPhone,
					business_context:     businessContext,
					custom_greeting:      customGreeting,
					custom_greeting_tone: customGreetingTone,
					business_hours:       businessHours,
					ai_voice:             aiVoice
				},
				success: function( response ) {
					if ( response.success ) {
						$icon.removeClass( 'dashicons-update spin' ).addClass( 'dashicons-yes-alt' );
						$buttonText.text( d.i18n.saved );
						$status.html( '<span style="color: #46b450;"><span class="dashicons dashicons-yes" style="vertical-align: middle;"></span> ' + d.i18n.settingsSaved + '</span>' );
						setTimeout( function() {
							$icon.removeClass( 'dashicons-yes-alt' ).addClass( 'dashicons-saved' );
							$buttonText.text( originalText );
							$button.prop( 'disabled', false );
							$status.html( '' );
						}, 2500 );
					} else {
						$icon.removeClass( 'dashicons-update spin' ).addClass( 'dashicons-warning' );
						$buttonText.text( d.i18n.error );
						$status.html( '<span style="color: #dc3232;">' + ( response.data && response.data.message ? response.data.message : d.i18n.saveFailed ) + '</span>' );
						setTimeout( function() {
							$icon.removeClass( 'dashicons-warning' ).addClass( 'dashicons-saved' );
							$buttonText.text( originalText );
							$button.prop( 'disabled', false );
						}, 3000 );
					}
				},
				error: function() {
					$icon.removeClass( 'dashicons-update spin' ).addClass( 'dashicons-warning' );
					$buttonText.text( d.i18n.error );
					$status.html( '<span style="color: #dc3232;">' + d.i18n.networkError + '</span>' );
					setTimeout( function() {
						$icon.removeClass( 'dashicons-warning' ).addClass( 'dashicons-saved' );
						$buttonText.text( originalText );
						$button.prop( 'disabled', false );
					}, 3000 );
				}
			} );
		} );

		// ── Business Description Character Counter ───────────────────────────

		( function() {
			var $textarea = $( '#business_context' );
			var $counter  = $( '#sitestaffr-business-context-counter' );

			if ( ! $textarea.length || ! $counter.length ) {
				return;
			}

			var maxLength = parseInt( $counter.data( 'maxlength' ), 10 ) || 1200;

			function updateBusinessDescriptionCounter() {
				var value = $textarea.val() || '';

				// Hard clamp for defensive consistency on pasted content.
				if ( value.length > maxLength ) {
					value = value.substring( 0, maxLength );
					$textarea.val( value );
				}

				$counter.find( '.sitestaffr-char-current' ).text( value.length );
				$counter.toggleClass( 'warning', value.length > Math.floor( maxLength * 0.9 ) );
			}

			$textarea.on( 'input', updateBusinessDescriptionCounter );
			updateBusinessDescriptionCounter();
		} )();

		// ── Custom Greeting Character Counter ───────────────────────────────

		( function() {
			var $input   = $( '#custom_greeting' );
			var $counter = $( '#sitestaffr-custom-greeting-counter' );

			if ( ! $input.length || ! $counter.length ) {
				return;
			}

			var maxLength = parseInt( $counter.data( 'maxlength' ), 10 ) || 250;

			function sanitizeGreeting( value, trimEdges ) {
				var output = ( value || '' ).replace( /[\r\n\t]+/g, ' ' );
				output = output.replace( /\s+/g, ' ' );
				if ( trimEdges ) {
					output = output.trim();
				}
				output = output.replace( /[\u2600-\u27BF]|[\uD83C-\uDBFF][\uDC00-\uDFFF]|\u200D|\uFE0F/g, '' );
				if ( output.length > maxLength ) {
					output = output.substring( 0, maxLength );
				}
				return output;
			}

			function updateGreetingUi( trimEdges ) {
				var sanitized = sanitizeGreeting( $input.val(), !! trimEdges );
				if ( $input.val() !== sanitized ) {
					$input.val( sanitized );
				}

				$counter.find( '.sitestaffr-char-current' ).text( sanitized.length );
				$counter.toggleClass( 'warning', sanitized.length > Math.floor( maxLength * 0.9 ) );
			}

			$input.on( 'input', function() {
				updateGreetingUi( false );
			} );
			$input.on( 'blur', function() {
				updateGreetingUi( true );
			} );

			updateGreetingUi( false );
		} )();

		// ── Greeting Tone Preview ────────────────────────────────────────────

		( function() {
			var $toneSelect = $( '#custom_greeting_tone' );
			var $previewBtn = $( '#sitestaffr-greeting-tone-preview-btn' );

			if ( ! $toneSelect.length || ! $previewBtn.length ) {
				return;
			}

			var audio = window.sitestaffrTonePreviewAudio || new Audio();
			window.sitestaffrTonePreviewAudio = audio;

			function getToneSampleUrl( toneKey ) {
				return d.pluginUrl + 'assets/audio/greeting-tone-samples/' + toneKey + '.mp3?v=' + d.pluginVersion;
			}

			function setButtonState( isPlaying ) {
				var $icon = $previewBtn.find( '.dashicons' );
				var $text = $previewBtn.find( '.sitestaffr-greeting-tone-preview-text' );
				if ( isPlaying ) {
					$icon.removeClass( 'dashicons-controls-play' ).addClass( 'dashicons-controls-pause' );
					$text.text( d.i18n.stop );
					$previewBtn.addClass( 'is-playing' );
				} else {
					$icon.removeClass( 'dashicons-controls-pause' ).addClass( 'dashicons-controls-play' );
					$text.text( d.i18n.preview );
					$previewBtn.removeClass( 'is-playing' );
				}
			}

			function stopPlayback() {
				audio.pause();
				audio.currentTime = 0;
				setButtonState( false );
			}

			$toneSelect.on( 'change', function() {
				var tone = ( $toneSelect.val() || 'warm_neutral' ).toString();
				$previewBtn.attr( 'data-tone', tone );
				if ( ! audio.paused ) {
					stopPlayback();
				}
			} );

			$previewBtn.on( 'click', function() {
				var tone = ( $toneSelect.val() || 'warm_neutral' ).toString();
				var url  = getToneSampleUrl( tone );

				if ( ! audio.paused ) {
					stopPlayback();
					return;
				}

				audio.src = url;
				audio.play().then( function() {
					setButtonState( true );
				} ).catch( function() {
					setButtonState( false );
					alert( d.i18n.tonePreviewUnavailable );
				} );
			} );

			audio.addEventListener( 'ended', function() {
				setButtonState( false );
			} );
			audio.addEventListener( 'error', function() {
				setButtonState( false );
			} );

			setButtonState( false );
		} )();

		// ── Business Phone Formatting ────────────────────────────────────────

		$( document ).on( 'input', '#business_phone', function() {
			var value = this.value.replace( /\D/g, '' );

			if ( value.length > 0 ) {
				if ( value.length <= 3 ) {
					value = '(' + value;
				} else if ( value.length <= 6 ) {
					value = '(' + value.substring( 0, 3 ) + ') ' + value.substring( 3 );
				} else {
					value = '(' + value.substring( 0, 3 ) + ') ' + value.substring( 3, 6 ) + '-' + value.substring( 6, 10 );
				}
			}

			this.value = value;
		} );

		// ── Send Test Email ──────────────────────────────────────────────────

		$( '#sitestaffr-send-test-email' ).on( 'click', function() {
			var $button = $( this );
			var $status = $( '#sitestaffr-test-email-status' );

			$button.prop( 'disabled', true );
			$status.html( '<span style="color: #666;"><span class="dashicons dashicons-update spin" style="vertical-align: middle;"></span> ' + d.i18n.sending + '</span>' );

			$.ajax( {
				url:  ajaxurl,
				type: 'POST',
				data: {
					action: 'sitestaffr_send_test_email',
					nonce:  d.nonces.admin
				},
				success: function( response ) {
					if ( response.success ) {
						$status.html( '<span style="color: #46b450;"><span class="dashicons dashicons-yes" style="vertical-align: middle;"></span> ' + response.data.message + '</span>' );
					} else {
						$status.html( '<span style="color: #dc3232;"><span class="dashicons dashicons-no" style="vertical-align: middle;"></span> ' + ( response.data.message || d.i18n.testEmailError ) + '</span>' );
					}
				},
				error: function() {
					$status.html( '<span style="color: #dc3232;"><span class="dashicons dashicons-no" style="vertical-align: middle;"></span> ' + d.i18n.connectionError + '</span>' );
				},
				complete: function() {
					$button.prop( 'disabled', false );
				}
			} );
		} );

		// ── Save Notification Settings (AJAX) ────────────────────────────────

		$( '#sitestaffr-save-notification-settings' ).on( 'click', function() {
			var $button      = $( this );
			var $buttonText  = $button.find( '.sitestaffr-save-notif-text' );
			var $icon        = $button.find( '.dashicons' );
			var $status      = $( '#sitestaffr-notif-save-status' );
			var email        = $( '#sitestaffr_notification_email' ).val();
			var ccEmails     = $( '#sitestaffr_notification_cc_emails' ).val();
			var enabled      = $( '#sitestaffr_email_notifications_enabled' ).is( ':checked' ) ? 1 : 0;
			var originalText = $buttonText.text();

			// Validate email format.
			var emailRegex       = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
			var invalidCc        = [];
			var ccParts          = ( ccEmails || '' ).split( /[,;\n]+/ );
			var uniqueValidCc    = [];
			var uniqueValidCcMap = {};

			if ( email && ! emailRegex.test( email ) ) {
				alert( d.i18n.invalidEmail );
				return;
			}

			ccParts.forEach( function( part ) {
				var trimmed = ( part || '' ).trim();
				if ( ! trimmed ) {
					return;
				}
				if ( ! emailRegex.test( trimmed ) ) {
					invalidCc.push( trimmed );
					return;
				}
				var key = trimmed.toLowerCase();
				if ( ! uniqueValidCcMap[ key ] ) {
					uniqueValidCcMap[ key ] = true;
					uniqueValidCc.push( trimmed );
				}
			} );

			if ( invalidCc.length ) {
				alert( d.i18n.invalidCcEmails );
				return;
			}
			if ( uniqueValidCc.length > 5 ) {
				alert( d.i18n.tooManyCcEmails );
				return;
			}

			// Show loading state.
			$button.prop( 'disabled', true );
			$icon.removeClass( 'dashicons-saved' ).addClass( 'dashicons-update spin' );
			$buttonText.text( d.i18n.saving );
			$status.html( '' );

			$.ajax( {
				url:  ajaxurl,
				type: 'POST',
				data: {
					action:    'sitestaffr_save_notification_settings',
					nonce:     d.nonces.admin,
					email:     email,
					cc_emails: ccEmails,
					enabled:   enabled
				},
				success: function( response ) {
					if ( response.success ) {
						if ( response.data && typeof response.data.email !== 'undefined' ) {
							$( '#sitestaffr_notification_email' ).val( response.data.email );
						}
						if ( response.data && typeof response.data.cc_emails !== 'undefined' ) {
							$( '#sitestaffr_notification_cc_emails' ).val( response.data.cc_emails );
						}
						$icon.removeClass( 'dashicons-update spin' ).addClass( 'dashicons-yes-alt' );
						$buttonText.text( d.i18n.saved );
						$status.html( '<span style="color: #46b450;"><span class="dashicons dashicons-yes" style="vertical-align: middle;"></span> ' + d.i18n.settingsSaved + '</span>' );

						setTimeout( function() {
							$icon.removeClass( 'dashicons-yes-alt' ).addClass( 'dashicons-saved' );
							$buttonText.text( originalText );
							$button.prop( 'disabled', false );
							$status.html( '' );
						}, 2500 );
					} else {
						alert( response.data.message || d.i18n.errorSavingSettings );
						$icon.removeClass( 'dashicons-update spin' ).addClass( 'dashicons-saved' );
						$buttonText.text( originalText );
						$button.prop( 'disabled', false );
					}
				},
				error: function() {
					alert( d.i18n.connectionError );
					$icon.removeClass( 'dashicons-update spin' ).addClass( 'dashicons-saved' );
					$buttonText.text( originalText );
					$button.prop( 'disabled', false );
				}
			} );
		} );

		// ── Business Hours Editor ────────────────────────────────────────────

		( function() {
			var hiddenInput       = document.getElementById( 'business_hours' );
			var scheduleBuilder   = document.getElementById( 'settings-schedule-builder' );
			var hourChoiceInputs  = document.querySelectorAll( 'input[name="hours_choice"]' );

			if ( ! hiddenInput || ! scheduleBuilder || ! hourChoiceInputs.length ) {
				return; // Elements not found, skip initialization.
			}

			function generateTimeOptions() {
				var times = [];
				for ( var hour = 0; hour < 24; hour++ ) {
					for ( var min = 0; min < 60; min += 30 ) {
						var displayHour = hour === 0 ? 12 : ( hour > 12 ? hour - 12 : hour );
						var ampm        = hour < 12 ? 'AM' : 'PM';
						var displayMin  = min.toString().length === 1 ? '0' + min : min.toString();
						times.push( displayHour + ':' + displayMin + ' ' + ampm );
					}
				}
				return times;
			}

			function initScheduleBuilder() {
				var days  = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ];
				var times = generateTimeOptions();

				days.forEach( function( day, index ) {
					var startSelect = document.querySelector( '.start-time[data-day="' + day + '"]' );
					var endSelect   = document.querySelector( '.end-time[data-day="' + day + '"]' );

					if ( ! startSelect || ! endSelect ) {
						return;
					}

					// Clear existing options.
					startSelect.innerHTML = '';
					endSelect.innerHTML   = '';

					// Populate time dropdowns.
					times.forEach( function( time ) {
						startSelect.add( new Option( time, time ) );
						endSelect.add( new Option( time, time ) );
					} );

					// Set defaults.
					if ( index < 5 ) { // Weekdays.
						var toggle = document.querySelector( '.day-open-toggle[data-day="' + day + '"]' );
						if ( toggle ) {
							toggle.checked   = true;
							startSelect.value = '9:00 AM';
							endSelect.value   = '5:00 PM';
							toggleDayInputs( day, true );
						}
					} else { // Weekends.
						var toggle = document.querySelector( '.day-open-toggle[data-day="' + day + '"]' ); // jshint ignore:line
						if ( toggle ) {
							toggle.checked = false;
							toggleDayInputs( day, false );
						}
					}
				} );
			}

			function toggleDayInputs( day, isOpen ) {
				var timeInputs  = document.querySelector( '.sitestaffr-time-inputs[data-day="' + day + '"]' );
				var toggleLabel = document.querySelector( '.day-open-toggle[data-day="' + day + '"] + .toggle-label' );

				if ( timeInputs && toggleLabel ) {
					if ( isOpen ) {
						timeInputs.style.display  = 'flex';
						toggleLabel.textContent    = 'Open';
					} else {
						timeInputs.style.display  = 'none';
						toggleLabel.textContent    = 'Closed';
					}
				}
			}

			function parseAndPopulateSchedule( hoursString ) {
				// Parse saved hours and populate schedule builder.
				// Example: "Mon: 9:00 AM-5:00 PM, Tue: 9:00 AM-5:00 PM, ..."
				if ( ! hoursString || hoursString === '24/7' || hoursString === 'Mon-Fri 9am-5pm, Sat-Sun Closed' ) {
					return; // Use defaults.
				}

				var days    = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ];
				var dayAbbr = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ];

				dayAbbr.forEach( function( abbr, index ) {
					var day   = days[ index ];
					var regex = new RegExp( abbr + ':\\s*([^,]+)', 'i' );
					var match = hoursString.match( regex );

					if ( match ) {
						var timeStr = match[ 1 ].trim();
						var toggle  = document.querySelector( '.day-open-toggle[data-day="' + day + '"]' );

						if ( ! toggle ) {
							return;
						}

						if ( timeStr.toLowerCase() === 'closed' ) {
							toggle.checked = false;
							toggleDayInputs( day, false );
						} else {
							// Parse times: "9:00 AM-5:00 PM".
							var timeParts = timeStr.split( '-' );
							if ( timeParts.length === 2 ) {
								var startTime  = timeParts[ 0 ].trim();
								var endTime    = timeParts[ 1 ].trim();
								var startSelect = document.querySelector( '.start-time[data-day="' + day + '"]' );
								var endSelect   = document.querySelector( '.end-time[data-day="' + day + '"]' );

								toggle.checked = true;
								if ( startSelect && endSelect ) {
									startSelect.value = startTime;
									endSelect.value   = endTime;
								}
								toggleDayInputs( day, true );
							}
						}
					}
				} );
			}

			function determineSelectedRadio( hoursString ) {
				if ( hoursString === '24/7' ) {
					return '24/7';
				} else if ( hoursString === 'Mon-Fri 9am-5pm, Sat-Sun Closed' ) {
					return 'standard';
				} else {
					return 'custom';
				}
			}

			function collectScheduleData() {
				var schedule  = [];
				var days      = [ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ];
				var dayNames  = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ];

				days.forEach( function( day, index ) {
					var toggle = document.querySelector( '.day-open-toggle[data-day="' + day + '"]' );

					if ( toggle && toggle.checked ) {
						var start = document.querySelector( '.start-time[data-day="' + day + '"]' ).value;
						var end   = document.querySelector( '.end-time[data-day="' + day + '"]' ).value;
						schedule.push( dayNames[ index ] + ': ' + start + '-' + end );
					} else {
						schedule.push( dayNames[ index ] + ': Closed' );
					}
				} );

				return schedule.join( ', ' );
			}

			function updateBusinessHoursHiddenField() {
				var selectedRadio = document.querySelector( 'input[name="hours_choice"]:checked' );
				if ( ! selectedRadio ) {
					return;
				}

				var newValue;
				if ( selectedRadio.value === '24/7' ) {
					newValue = '24/7';
				} else if ( selectedRadio.value === 'standard' ) {
					newValue = 'Mon-Fri 9am-5pm, Sat-Sun Closed';
				} else {
					newValue = collectScheduleData();
				}

				hiddenInput.value = newValue;
			}

			function updateHoursUIForSelection( selectedValue ) {
				if ( selectedValue === 'custom' ) {
					scheduleBuilder.style.display = 'block';
				} else {
					scheduleBuilder.style.display = 'none';
				}
			}

			// Initialize schedule builder first so custom parsing can target populated dropdowns.
			initScheduleBuilder();

			// Pre-select based on saved value and hydrate custom schedule when needed.
			var selectedRadio = determineSelectedRadio( hiddenInput.value );
			var selectedInput = document.querySelector( 'input[name="hours_choice"][value="' + selectedRadio + '"]' );
			if ( selectedInput ) {
				selectedInput.checked = true;
			}
			if ( selectedRadio === 'custom' ) {
				parseAndPopulateSchedule( hiddenInput.value );
			}
			updateHoursUIForSelection( selectedRadio );
			updateBusinessHoursHiddenField();

			hourChoiceInputs.forEach( function( radio ) {
				radio.addEventListener( 'change', function() {
					updateHoursUIForSelection( this.value );
					updateBusinessHoursHiddenField();
				} );
			} );

			document.querySelectorAll( '.day-open-toggle' ).forEach( function( toggle ) {
				toggle.addEventListener( 'change', function() {
					toggleDayInputs( this.dataset.day, this.checked );
					updateBusinessHoursHiddenField();
				} );
			} );

			document.querySelectorAll( '.start-time, .end-time' ).forEach( function( selectEl ) {
				selectEl.addEventListener( 'change', function() {
					updateBusinessHoursHiddenField();
				} );
			} );
		} )();

		// ── Generate Description from Website ───────────────────────────────

		( function() {
			var $btn = $( '#btn-settings-generate-description' );
			if ( ! $btn.length ) {
				return;
			}

			var $card             = $btn.closest( '.sitestaffr-generate-card' );
			var $status           = $( '#sitestaffr-gen-status' );
			var $progress         = $card.find( '.sitestaffr-gen-progress' );
			var $textarea         = $( '#business_context' );
			var initialRemaining  = parseInt( $card.data( 'remaining-generations' ), 10 );
			var limitReached      = ! isNaN( initialRemaining ) && initialRemaining <= 0;
			var statusTimer       = null;

			function clearStatus() {
				if ( statusTimer ) {
					window.clearTimeout( statusTimer );
					statusTimer = null;
				}
				$status
					.removeClass( 'sitestaffr-gen-success sitestaffr-gen-error sitestaffr-gen-loading' )
					.hide()
					.text( '' );
			}

			function showStatus( type, message, timeoutMs ) {
				clearStatus();
				$status
					.removeClass( 'sitestaffr-gen-success sitestaffr-gen-error sitestaffr-gen-loading' )
					.addClass( 'sitestaffr-gen-' + type )
					.show()
					.text( message );

				if ( timeoutMs ) {
					statusTimer = window.setTimeout( function() {
						clearStatus();
					}, timeoutMs );
				}
			}

			function enableButton() {
				$btn.find( '.dashicons' ).removeClass( 'sitestaffr-spin' );
				$btn.prop( 'disabled', limitReached );
				$progress.removeClass( 'is-active' );
			}

			if ( limitReached ) {
				showStatus( 'error', d.i18n.dailyLimitReached, 0 );
			}

			$btn.on( 'click', function() {
				if ( $btn.prop( 'disabled' ) ) {
					return;
				}

				$btn.addClass( 'is-pressing' );
				window.setTimeout( function() {
					$btn.removeClass( 'is-pressing' );
				}, 260 );

				$btn.prop( 'disabled', true ).find( '.dashicons' ).addClass( 'sitestaffr-spin' );
				showStatus( 'loading', d.i18n.scanningWebsite, 0 );
				$progress.addClass( 'is-active' );

				// Progress messages while waiting for AI generation.
				var progressMsgs = [
					{ at: 5000,  text: 'Searching your website...' },
					{ at: 15000, text: 'Reading pages and extracting details...' },
					{ at: 40000, text: 'Analyzing pricing, services, and features...' },
					{ at: 90000, text: 'Writing your business description...' },
					{ at: 150000, text: 'Almost done — finalizing description...' }
				];
				var progressTimers = [];
				progressMsgs.forEach( function( msg ) {
					progressTimers.push( setTimeout( function() {
						showStatus( 'loading', msg.text, 0 );
					}, msg.at ) );
				} );

				function clearProgressTimers() {
					progressTimers.forEach( function( t ) { clearTimeout( t ); } );
					progressTimers = [];
				}

				function hideProgress() {
					$progress.removeClass( 'is-active' );
				}

				function showSuccessCheckmark( statusMsg ) {
					hideProgress();
					$status
						.removeClass( 'sitestaffr-gen-success sitestaffr-gen-error sitestaffr-gen-loading' )
						.addClass( 'sitestaffr-gen-success' )
						.show()
						.html(
							'<span class="sitestaffr-gen-checkmark">' +
							'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>' +
							'</span> ' + statusMsg
						);

					if ( statusTimer ) { clearTimeout( statusTimer ); }
					statusTimer = setTimeout( function() {
						clearStatus();
					}, 3000 );
				}

				var genStartedAt = Math.floor( Date.now() / 1000 );

				// Recovery: poll for a saved description after a connection timeout.
				// The server may complete and save despite the browser losing the connection.
				function pollForRecovery( attemptsLeft ) {
					if ( attemptsLeft <= 0 ) {
						hideProgress();
						$btn.find( '.dashicons' ).removeClass( 'sitestaffr-spin' );
						showStatus( 'error', d.i18n.networkError, 5000 );
						$btn.prop( 'disabled', limitReached );
						return;
					}
					$.ajax( {
						url: ajaxurl,
						type: 'POST',
						timeout: 10000,
						data: {
							action: 'sitestaffr_check_fresh_description',
							nonce:  d.nonces.generateDescription,
							since:  genStartedAt
						},
						success: function( resp ) {
							if ( resp.success && resp.data && resp.data.description ) {
								$btn.find( '.dashicons' ).removeClass( 'sitestaffr-spin' );
								$textarea.val( resp.data.description );
								$textarea.trigger( 'input' );
								showSuccessCheckmark( d.i18n.descriptionGenerated );
								if ( resp.data.remaining !== undefined && resp.data.remaining <= 0 ) {
									limitReached = true;
								}
								$btn.prop( 'disabled', limitReached );
							} else {
								setTimeout( function() { pollForRecovery( attemptsLeft - 1 ); }, 5000 );
							}
						},
						error: function() {
							setTimeout( function() { pollForRecovery( attemptsLeft - 1 ); }, 5000 );
						}
					} );
				}

				$.ajax( {
					url:  ajaxurl,
					type: 'POST',
					timeout: 300000,
					data: {
						action:      'sitestaffr_generate_business_description',
						nonce:       d.nonces.generateDescription
					},
					success: function( response ) {
						clearProgressTimers();
						$btn.find( '.dashicons' ).removeClass( 'sitestaffr-spin' );

						if ( response.success && response.data && response.data.description ) {
							$textarea.val( response.data.description );
							$textarea.trigger( 'input' );
							var statusMsg = d.i18n.descriptionGenerated;
							if ( response.data.extraction_chars ) {
								statusMsg += ' (' + response.data.extraction_chars.toLocaleString() + ' chars extracted)';
							}
							showSuccessCheckmark( statusMsg );

							if ( response.data.remaining !== undefined && response.data.remaining <= 0 ) {
								limitReached = true;
							}
							$btn.prop( 'disabled', limitReached );
						} else {
							hideProgress();
							var msg = ( response.data && response.data.message ) ? response.data.message : d.i18n.generationFailed;
							showStatus( 'error', msg, 5000 );
							$btn.prop( 'disabled', limitReached );
						}
					},
					error: function( xhr, textStatus, errorThrown ) {
						clearProgressTimers();

						console.error( 'SiteStaffr desc gen error:', textStatus, xhr ? xhr.status : 'no xhr', errorThrown );

						if ( xhr && xhr.status === 429 ) {
							hideProgress();
							$btn.find( '.dashicons' ).removeClass( 'sitestaffr-spin' );
							limitReached = true;
							var responseData = xhr.responseJSON && xhr.responseJSON.data ? xhr.responseJSON.data : null;
							showStatus( 'error', ( responseData && responseData.message ) ? responseData.message : d.i18n.dailyLimitReached, 0 );
							$btn.prop( 'disabled', true );
							return;
						}

						// Connection likely dropped while server is still processing.
						// Keep spinner going and poll for the saved result.
						showStatus( 'loading', 'Finalizing — checking for saved description...', 0 );
						pollForRecovery( 24 );
					}
				} );
			} );
		} )();

		// NOTE: Tooltip functionality is in admin/js/sitestaffr-tooltips.js
		// Global script handles tooltips for all admin pages.

	} );

} )( jQuery );
