<?php
/**
 * Plugin Name: BW Scroll Down
 * Plugin URI:  https://bowdenworks.com
 * Description: Adds a scroll-down indicator with animated SVG icons. Use shortcode [bw_scroll_down] or add CSS class to Kadence rows.
 * Version:     4.0.0
 * Author:      Bowden Works
 * Author URI:  https://bowdenworks.com
 * License:     GPL-2.0+
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: bw-scroll-down
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Available SVG icons.
 */
function bw_scroll_down_get_icons() {
	return array(
		'chevron' => array(
			'label' => 'Chevron',
			'svg'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>',
		),
		'chevron-double' => array(
			'label' => 'Double Chevron',
			'svg'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 6 12 12 18 6"></polyline><polyline points="6 12 12 18 18 12"></polyline></svg>',
		),
		'arrow' => array(
			'label' => 'Arrow',
			'svg'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><polyline points="19 12 12 19 5 12"></polyline></svg>',
		),
		'arrow-circle' => array(
			'label' => 'Circle Arrow',
			'svg'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="8 12 12 16 16 12"></polyline><line x1="12" y1="8" x2="12" y2="16"></line></svg>',
		),
		'mouse' => array(
			'label' => 'Mouse',
			'svg'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="3" width="12" height="18" rx="6"></rect><line x1="12" y1="7" x2="12" y2="11"></line></svg>',
		),
		'angle' => array(
			'label' => 'Angle',
			'svg'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="5 10 12 17 19 10"></polyline></svg>',
		),
	);
}

/**
 * Get default settings.
 */
function bw_scroll_down_get_defaults() {
	return array(
		'icon_type'      => 'chevron',
		'icon_size'      => 40,
		'icon_color'     => '#ffffff',
		'label_text'     => '',
		'bottom_offset'  => '5',
		'anchor_target'  => '#start',
		'trigger_class'  => 'has-scroll-down',
		'auto_target'    => true,
		'animate'        => true,
	);
}

/**
 * Register plugin settings.
 */
function bw_scroll_down_register_settings() {
	register_setting( 'bw_scroll_down_options', 'bw_scroll_down_settings', array(
		'type'              => 'array',
		'sanitize_callback' => 'bw_scroll_down_sanitize_settings',
		'default'           => bw_scroll_down_get_defaults(),
	) );
}
add_action( 'admin_init', 'bw_scroll_down_register_settings' );

/**
 * Sanitize settings.
 */
function bw_scroll_down_sanitize_settings( $input ) {
	$sanitized = array();
	$defaults = bw_scroll_down_get_defaults();
	$icons = bw_scroll_down_get_icons();

	$icon_type = sanitize_text_field( $input['icon_type'] ?? $defaults['icon_type'] );
	$sanitized['icon_type'] = isset( $icons[ $icon_type ] ) ? $icon_type : $defaults['icon_type'];

	$sanitized['icon_size'] = max( 20, min( 100, absint( $input['icon_size'] ?? $defaults['icon_size'] ) ) );
	$sanitized['icon_color'] = sanitize_hex_color( $input['icon_color'] ?? '' ) ?: $defaults['icon_color'];
	$sanitized['label_text'] = sanitize_text_field( $input['label_text'] ?? '' );

	$bottom_offset = sanitize_text_field( $input['bottom_offset'] ?? $defaults['bottom_offset'] );
	$sanitized['bottom_offset'] = preg_match( '/^[0-9]+(px|%)?$/', $bottom_offset ) ? $bottom_offset : $defaults['bottom_offset'];

	$anchor = sanitize_text_field( $input['anchor_target'] ?? $defaults['anchor_target'] );
	if ( ! empty( $anchor ) && strpos( $anchor, '#' ) !== 0 ) {
		$anchor = '#' . $anchor;
	}
	$sanitized['anchor_target'] = $anchor ?: $defaults['anchor_target'];

	$sanitized['trigger_class'] = sanitize_html_class( $input['trigger_class'] ?? '' ) ?: $defaults['trigger_class'];
	$sanitized['auto_target'] = ! empty( $input['auto_target'] );
	$sanitized['animate'] = ! empty( $input['animate'] );

	return $sanitized;
}

/**
 * Get plugin settings with defaults.
 */
function bw_scroll_down_get_settings() {
	$defaults = bw_scroll_down_get_defaults();
	$settings = get_option( 'bw_scroll_down_settings', $defaults );
	return wp_parse_args( $settings, $defaults );
}

/**
 * Get icon SVG.
 */
function bw_scroll_down_get_icon_svg( $icon_type, $size = 40, $color = '#ffffff' ) {
	$icons = bw_scroll_down_get_icons();
	$icon = isset( $icons[ $icon_type ] ) ? $icons[ $icon_type ] : $icons['chevron'];
	$svg = str_replace( '<svg ', '<svg width="' . intval( $size ) . '" height="' . intval( $size ) . '" style="color:' . esc_attr( $color ) . ';" ', $icon['svg'] );
	return $svg;
}

/**
 * Parse bottom offset value.
 */
function bw_scroll_down_parse_offset( $offset ) {
	if ( is_numeric( $offset ) ) {
		return $offset . '%';
	}
	return $offset;
}

/**
 * Add settings page.
 */
function bw_scroll_down_add_settings_page() {
	add_options_page(
		__( 'ScrollDown Config', 'bw-scroll-down' ),
		__( 'ScrollDown Config', 'bw-scroll-down' ),
		'manage_options',
		'bw-scroll-down',
		'bw_scroll_down_settings_page'
	);
}
add_action( 'admin_menu', 'bw_scroll_down_add_settings_page' );

/**
 * Render settings page.
 */
function bw_scroll_down_settings_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$settings = bw_scroll_down_get_settings();
	$icons = bw_scroll_down_get_icons();
	?>
	<div class="wrap">
		<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

		<form action="options.php" method="post">
			<?php settings_fields( 'bw_scroll_down_options' ); ?>

			<h2><?php esc_html_e( 'Icon Style', 'bw-scroll-down' ); ?></h2>
			<table class="form-table">
				<tr>
					<th scope="row"><label><?php esc_html_e( 'Select Icon', 'bw-scroll-down' ); ?></label></th>
					<td>
						<div style="display: flex; flex-wrap: wrap; gap: 12px;">
							<?php foreach ( $icons as $key => $icon ) : ?>
								<label style="display: flex; flex-direction: column; align-items: center; padding: 15px 20px; border: 2px solid <?php echo $settings['icon_type'] === $key ? '#2271b1' : '#ddd'; ?>; border-radius: 8px; cursor: pointer; background: #1a1a2e; min-width: 90px;">
									<input type="radio" name="bw_scroll_down_settings[icon_type]" value="<?php echo esc_attr( $key ); ?>" <?php checked( $settings['icon_type'], $key ); ?> class="bw-icon-radio" style="display: none;">
									<span style="color: #fff; width: 36px; height: 36px;"><?php echo $icon['svg']; ?></span>
									<span style="margin-top: 8px; font-size: 11px; color: #aaa;"><?php echo esc_html( $icon['label'] ); ?></span>
								</label>
							<?php endforeach; ?>
						</div>
					</td>
				</tr>
			</table>

			<h2><?php esc_html_e( 'Appearance', 'bw-scroll-down' ); ?></h2>
			<table class="form-table">
				<tr>
					<th scope="row"><label for="bw_icon_size"><?php esc_html_e( 'Icon Size', 'bw-scroll-down' ); ?></label></th>
					<td>
						<input type="number" id="bw_icon_size" name="bw_scroll_down_settings[icon_size]" value="<?php echo esc_attr( $settings['icon_size'] ); ?>" class="small-text" min="20" max="100"> px
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw_icon_color"><?php esc_html_e( 'Icon Color', 'bw-scroll-down' ); ?></label></th>
					<td>
						<input type="text" id="bw_icon_color" name="bw_scroll_down_settings[icon_color]" value="<?php echo esc_attr( $settings['icon_color'] ); ?>" class="bw-color-picker">
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw_label_text"><?php esc_html_e( 'Label Text', 'bw-scroll-down' ); ?></label></th>
					<td>
						<input type="text" id="bw_label_text" name="bw_scroll_down_settings[label_text]" value="<?php echo esc_attr( $settings['label_text'] ); ?>" class="regular-text" placeholder="SCROLL">
						<p class="description"><?php esc_html_e( 'Optional text above the icon.', 'bw-scroll-down' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw_bottom_offset"><?php esc_html_e( 'Bottom Offset', 'bw-scroll-down' ); ?></label></th>
					<td>
						<input type="text" id="bw_bottom_offset" name="bw_scroll_down_settings[bottom_offset]" value="<?php echo esc_attr( $settings['bottom_offset'] ); ?>" class="small-text" placeholder="5">
						<p class="description"><?php esc_html_e( 'Distance from bottom (number = %, or use "px").', 'bw-scroll-down' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Animation', 'bw-scroll-down' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="bw_scroll_down_settings[animate]" value="1" <?php checked( $settings['animate'], true ); ?>>
							<?php esc_html_e( 'Enable smooth floating animation', 'bw-scroll-down' ); ?>
						</label>
					</td>
				</tr>
			</table>

			<h2><?php esc_html_e( 'Behavior', 'bw-scroll-down' ); ?></h2>
			<table class="form-table">
				<tr>
					<th scope="row"><label for="bw_anchor_target"><?php esc_html_e( 'Anchor Target', 'bw-scroll-down' ); ?></label></th>
					<td>
						<input type="text" id="bw_anchor_target" name="bw_scroll_down_settings[anchor_target]" value="<?php echo esc_attr( $settings['anchor_target'] ); ?>" class="regular-text" placeholder="#start">
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw_trigger_class"><?php esc_html_e( 'Trigger Class', 'bw-scroll-down' ); ?></label></th>
					<td>
						<input type="text" id="bw_trigger_class" name="bw_scroll_down_settings[trigger_class]" value="<?php echo esc_attr( $settings['trigger_class'] ); ?>" class="regular-text">
						<p class="description"><?php esc_html_e( 'Add this class to any Kadence Row to auto-add the indicator.', 'bw-scroll-down' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Auto-Target', 'bw-scroll-down' ); ?></th>
					<td>
						<label>
							<input type="checkbox" name="bw_scroll_down_settings[auto_target]" value="1" <?php checked( $settings['auto_target'], true ); ?>>
							<?php esc_html_e( 'Scroll to next section instead of anchor target', 'bw-scroll-down' ); ?>
						</label>
					</td>
				</tr>
			</table>

			<h2><?php esc_html_e( 'Preview', 'bw-scroll-down' ); ?></h2>
			<div id="bw-preview-container" style="padding: 80px 40px; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); text-align: center; margin-bottom: 20px; position: relative; min-height: 200px; border-radius: 8px;">
				<p style="color: rgba(255,255,255,0.4); margin: 0 0 60px;">Hero Section Preview</p>
				<div id="bw-live-preview" style="position: absolute; bottom: <?php echo esc_attr( bw_scroll_down_parse_offset( $settings['bottom_offset'] ) ); ?>; left: 50%; transform: translateX(-50%);">
					<?php echo bw_scroll_down_shortcode(); ?>
				</div>
			</div>

			<h2><?php esc_html_e( 'Usage', 'bw-scroll-down' ); ?></h2>
			<p><strong><?php esc_html_e( 'Shortcode:', 'bw-scroll-down' ); ?></strong> <code>[bw_scroll_down]</code></p>
			<p><strong><?php esc_html_e( 'CSS Class:', 'bw-scroll-down' ); ?></strong> <?php printf( esc_html__( 'Add %s to any Kadence Row.', 'bw-scroll-down' ), '<code>' . esc_html( $settings['trigger_class'] ) . '</code>' ); ?></p>

			<?php submit_button(); ?>
		</form>
	</div>

	<script>
	jQuery(document).ready(function($) {
		// Icon selection
		$('.bw-icon-radio').on('change', function() {
			$('.bw-icon-radio').closest('label').css('border-color', '#ddd');
			$(this).closest('label').css('border-color', '#2271b1');
		});

		// Color picker
		$('.bw-color-picker').wpColorPicker();
	});
	</script>
	<?php
}

/**
 * Enqueue admin scripts.
 */
function bw_scroll_down_admin_scripts( $hook ) {
	if ( 'settings_page_bw-scroll-down' !== $hook ) {
		return;
	}
	wp_enqueue_style( 'wp-color-picker' );
	wp_enqueue_script( 'wp-color-picker' );
}
add_action( 'admin_enqueue_scripts', 'bw_scroll_down_admin_scripts' );

/**
 * Register shortcode.
 */
function bw_scroll_down_shortcode( $atts = array() ) {
	$settings = bw_scroll_down_get_settings();

	$atts = shortcode_atts( array(
		'anchor' => $settings['anchor_target'],
		'label'  => $settings['label_text'],
		'icon'   => $settings['icon_type'],
		'size'   => $settings['icon_size'],
		'color'  => $settings['icon_color'],
	), $atts, 'bw_scroll_down' );

	$anchor = esc_attr( $atts['anchor'] );
	$label  = esc_html( $atts['label'] );
	$size   = absint( $atts['size'] );
	$color  = esc_attr( $atts['color'] ) ?: '#ffffff';
	$animate_class = $settings['animate'] ? ' bw-scroll-down--animated' : '';

	$label_html = $label ? '<span class="bw-scroll-down__text" style="color:' . $color . ';">' . $label . '</span>' : '';
	$icon_svg = bw_scroll_down_get_icon_svg( $atts['icon'], $size, $color );

	$output = '<div class="bw-scroll-down bw-scroll-down--shortcode' . $animate_class . '">';
	$output .= $label_html;
	$output .= '<a href="' . $anchor . '" class="bw-scroll-down__link" style="color:' . $color . ';">';
	$output .= '<span class="bw-scroll-down__icon">' . $icon_svg . '</span>';
	$output .= '</a>';
	$output .= '</div>';

	return $output;
}
add_shortcode( 'bw_scroll_down', 'bw_scroll_down_shortcode' );

/**
 * Add CSS in wp_head.
 */
function bw_scroll_down_head_assets() {
	$settings = bw_scroll_down_get_settings();
	$bottom = bw_scroll_down_parse_offset( $settings['bottom_offset'] );
	?>
	<style id="bw-scroll-down-css">
		.bw-scroll-down {
			display: inline-block !important;
			text-align: center;
			visibility: visible !important;
			opacity: 1 !important;
		}
		.bw-scroll-down__text {
			display: block;
			font-size: 11px;
			font-weight: 500;
			letter-spacing: 3px;
			text-transform: uppercase;
			margin-bottom: 12px;
		}
		.bw-scroll-down__link {
			display: inline-flex;
			align-items: center;
			justify-content: center;
			text-decoration: none;
			transition: opacity 0.3s ease;
		}
		.bw-scroll-down__link:hover {
			opacity: 0.7;
		}
		.bw-scroll-down__icon {
			display: inline-flex;
			align-items: center;
			justify-content: center;
		}
		.bw-scroll-down__icon svg {
			display: block;
		}
		.bw-scroll-down--auto {
			position: absolute;
			bottom: <?php echo esc_attr( $bottom ); ?>;
			left: 50%;
			transform: translateX(-50%);
			z-index: 100;
		}
		.<?php echo esc_attr( $settings['trigger_class'] ); ?> {
			position: relative !important;
		}
		@keyframes bw-float {
			0%, 100% { transform: translateY(0); }
			50% { transform: translateY(8px); }
		}
		.bw-scroll-down--animated .bw-scroll-down__icon {
			animation: bw-float 2.5s ease-in-out infinite;
		}
		.bw-scroll-down--animated:hover .bw-scroll-down__icon {
			animation-play-state: paused;
		}
	</style>
	<?php
}
add_action( 'wp_head', 'bw_scroll_down_head_assets' );

/**
 * Add JS in footer.
 */
function bw_scroll_down_footer_script() {
	$settings = bw_scroll_down_get_settings();
	$color = esc_attr( $settings['icon_color'] ) ?: '#ffffff';
	$size = absint( $settings['icon_size'] );
	$icon_svg = bw_scroll_down_get_icon_svg( $settings['icon_type'], $size, $color );
	$animate_class = $settings['animate'] ? ' bw-scroll-down--animated' : '';
	?>
	<script id="bw-scroll-down-js">
	(function() {
		var settings = {
			anchorTarget: <?php echo wp_json_encode( $settings['anchor_target'] ); ?>,
			labelText: <?php echo wp_json_encode( $settings['label_text'] ); ?>,
			iconSvg: <?php echo wp_json_encode( $icon_svg ); ?>,
			iconColor: <?php echo wp_json_encode( $color ); ?>,
			triggerClass: <?php echo wp_json_encode( $settings['trigger_class'] ); ?>,
			autoTarget: <?php echo $settings['auto_target'] ? 'true' : 'false'; ?>,
			animateClass: <?php echo wp_json_encode( $animate_class ); ?>
		};

		function createIndicator() {
			var div = document.createElement('div');
			div.className = 'bw-scroll-down bw-scroll-down--auto' + settings.animateClass;
			var html = '';
			if (settings.labelText) {
				html += '<span class="bw-scroll-down__text" style="color:' + settings.iconColor + ';">' + settings.labelText + '</span>';
			}
			html += '<a href="' + settings.anchorTarget + '" class="bw-scroll-down__link" style="color:' + settings.iconColor + ';">';
			html += '<span class="bw-scroll-down__icon">' + settings.iconSvg + '</span>';
			html += '</a>';
			div.innerHTML = html;
			return div;
		}

		function getNextSection(el) {
			var next = el.nextElementSibling;
			while (next) {
				if (next.classList.contains('wp-block-kadence-rowlayout') ||
					next.classList.contains('kb-row-layout-wrap') ||
					next.tagName === 'SECTION') {
					return next;
				}
				next = next.nextElementSibling;
			}
			return null;
		}

		function smoothScroll(target) {
			if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
		}

		function init() {
			var triggers = document.querySelectorAll('.' + settings.triggerClass);
			triggers.forEach(function(el) {
				if (el.querySelector('.bw-scroll-down')) return;
				var indicator = createIndicator();
				el.appendChild(indicator);
				indicator.querySelector('.bw-scroll-down__link').addEventListener('click', function(e) {
					e.preventDefault();
					if (settings.autoTarget) {
						var next = getNextSection(el);
						if (next) smoothScroll(next);
					} else {
						var target = document.querySelector(settings.anchorTarget);
						if (target) smoothScroll(target);
					}
				});
			});

			document.querySelectorAll('.bw-scroll-down__link').forEach(function(link) {
				if (link.dataset.init) return;
				link.dataset.init = '1';
				link.addEventListener('click', function(e) {
					e.preventDefault();
					var href = link.getAttribute('href');
					if (href && href !== '#') {
						var target = document.querySelector(href);
						if (target) smoothScroll(target);
					}
				});
			});
		}

		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', init);
		} else {
			init();
		}
	})();
	</script>
	<?php
}
add_action( 'wp_footer', 'bw_scroll_down_footer_script' );

/**
 * Add settings link.
 */
function bw_scroll_down_settings_link( $links ) {
	$settings_link = '<a href="' . admin_url( 'options-general.php?page=bw-scroll-down' ) . '">' . __( 'Settings', 'bw-scroll-down' ) . '</a>';
	array_unshift( $links, $settings_link );
	return $links;
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'bw_scroll_down_settings_link' );
