<?php
if (! defined('ABSPATH')) {
    exit;
} function puffergo_get_menu_icon_registry()
{
    static $cached = null;

    if (null !== $cached) {
        return $cached;
    } $cached = array();
    $json_file = PUFFERGO_PLUGIN_DIR . '/php/data/menu-icons.json';

    if (! file_exists($json_file)) {
        return $cached;
    } $decoded = json_decode((string) file_get_contents($json_file), true);

    if (! is_array($decoded)) {
        return $cached;
    }

foreach ($decoded as $slug => $icon) {
        $icon_slug = sanitize_key((string) $slug);

        if ('' === $icon_slug || ! is_array($icon)) {
            continue;
        } $label = isset($icon['label']) ? sanitize_text_field((string) $icon['label']) : '';
        $path = isset($icon['path']) ? sanitize_text_field((string) $icon['path']) : '';

        if ('' === $label || '' === $path) {
            continue;
        } $cached[ $icon_slug ] = array('label' => $label, 'path' => $path, );
    }

return $cached;
} function puffergo_get_menu_item_icon_slug($menu_item_id)
{
    $slug = sanitize_key((string) get_post_meta((int) $menu_item_id, '_puffergo_menu_icon', true));
    $registry = puffergo_get_menu_icon_registry();

    return isset($registry[ $slug ]) ? $slug : '';
} function puffergo_get_menu_icon_markup($slug, $class = 'size-5 shrink-0 text-neutral-400')
{
    $icon_slug = sanitize_key((string) $slug);
    $registry = puffergo_get_menu_icon_registry();

    if (! isset($registry[ $icon_slug ])) {
        return '';
    } $path_data = $registry[ $icon_slug ]['path'];

    if ('' === $path_data) {
        return '';
    }

return sprintf('<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="%1$s"><path d="%2$s" /></svg>', esc_attr($class), esc_attr($path_data));
} function puffergo_render_menu_item_icon_field($item_id, $item, $depth, $args, $id)
{
    unset($item, $depth, $args, $id);
    $current_icon = puffergo_get_menu_item_icon_slug((int) $item_id);
    $icons = puffergo_get_menu_icon_registry(); ?>
	<p class="field-puffergo-menu-icon description description-wide">
		<span class="description"><?php esc_html_e('PufferGo Submenu Icon', 'puffergo'); ?></span>
		<input
			type="hidden"
			id="edit-menu-item-puffergo-icon-<?php echo esc_attr($item_id); ?>"
			class="puffergo-menu-icon-picker-value"
			name="puffergo_menu_item_icon[<?php echo esc_attr($item_id); ?>]"
			value="<?php echo esc_attr($current_icon); ?>"
		/>
		<span class="puffergo-menu-icon-picker-dropdown">
			<span class="puffergo-menu-icon-picker-header">
				<button
					type="button"
					class="puffergo-menu-icon-picker-trigger"
					data-target="#edit-menu-item-puffergo-icon-<?php echo esc_attr($item_id); ?>"
					aria-expanded="false"
					aria-haspopup="listbox"
				>
					<span class="puffergo-menu-icon-picker-trigger-main">
						<?php if ('' === $current_icon) : ?>
							<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
						<?php else : ?>
							<?php
    echo puffergo_get_menu_icon_markup($current_icon, 'puffergo-menu-icon-picker-svg'); ?>
						<?php endif; ?>
						<span class="puffergo-menu-icon-picker-trigger-label"><?php esc_html_e('Choose icon', 'puffergo'); ?></span>
					</span>
					<span class="dashicons dashicons-arrow-down-alt2" aria-hidden="true"></span>
				</button>
				<button
					type="button"
					class="puffergo-menu-icon-picker-clear"
					data-target="#edit-menu-item-puffergo-icon-<?php echo esc_attr($item_id); ?>"
					title="<?php esc_attr_e('Clear icon', 'puffergo'); ?>"
					aria-label="<?php esc_attr_e('Clear icon', 'puffergo'); ?>"
				>
					<span class="dashicons dashicons-trash" aria-hidden="true"></span>
				</button>
			</span>
			<span class="puffergo-menu-icon-picker-panel" role="listbox" aria-label="<?php esc_attr_e('PufferGo submenu icon selector', 'puffergo'); ?>">
				<span class="puffergo-menu-icon-picker-grid">
					<?php foreach ($icons as $icon_slug => $icon_data) : ?>
						<button
							type="button"
							class="puffergo-menu-icon-picker-option <?php echo $current_icon === $icon_slug ? 'is-selected' : ''; ?>"
							data-target="#edit-menu-item-puffergo-icon-<?php echo esc_attr($item_id); ?>"
							data-value="<?php echo esc_attr($icon_slug); ?>"
							aria-selected="<?php echo $current_icon === $icon_slug ? 'true' : 'false'; ?>"
							title="<?php echo esc_attr($icon_data['label']); ?>"
						>
							<?php
    echo puffergo_get_menu_icon_markup($icon_slug, 'puffergo-menu-icon-picker-svg'); ?>
							<span class="screen-reader-text"><?php echo esc_html($icon_data['label']); ?></span>
						</button>
					<?php endforeach; ?>
				</span>
			</span>
		</span>
	</p>
	<?php
} function puffergo_print_menu_icon_picker_assets()
{ ?>
	<style>
		.puffergo-menu-icon-picker-dropdown{display:block;position:relative;margin-top:8px;max-width:320px}
		.puffergo-menu-icon-picker-header{display:flex;align-items:center;gap:8px}
		.puffergo-menu-icon-picker-trigger{display:flex;align-items:center;justify-content:space-between;gap:8px;width:100%;height:36px;padding:0 10px;border:1px solid #dcdcde;border-radius:6px;background:#fff;color:#1d2327;cursor:pointer}
		.puffergo-menu-icon-picker-clear{display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;border:1px solid #dcdcde;border-radius:6px;background:#fff;color:oklch(55.4% 0.046 257.417);cursor:pointer}
		.puffergo-menu-icon-picker-clear:hover{background:#fcf0f1}
		.puffergo-menu-icon-picker-trigger-main{display:flex;align-items:center;gap:8px;min-width:0}
		.puffergo-menu-icon-picker-trigger-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
		.puffergo-menu-icon-picker-panel{display:none;position:absolute;left:0;right:0;top:40px;z-index:999;width:100%;height:210px;overflow-y:auto;padding:6px;border:1px solid #dcdcde;border-radius:6px;background:#fff;box-shadow:0 8px 16px rgba(0,0,0,.12)}
		.puffergo-menu-icon-picker-dropdown.is-open .puffergo-menu-icon-picker-panel{display:block}
		.puffergo-menu-icon-picker-grid{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));column-gap:6px;row-gap:8px}
		.puffergo-menu-icon-picker-option{display:flex;align-items:center;justify-content:center;width:100%;height:32px;padding:0;border:1px solid #dcdcde;border-radius:6px;background:#fff;color:#50575e;cursor:pointer}
		.puffergo-menu-icon-picker-option:hover{border-color:#2271b1;color:#2271b1}
		.puffergo-menu-icon-picker-option.is-selected{border-color:#2271b1;background:#f0f6fc;color:#2271b1}
		.puffergo-menu-icon-picker-svg{width:18px;height:18px;display:block}
	</style>
	<script>
		(function(){
			if (window.puffergoMenuIconPickerBound) {
				return;
			}
			window.puffergoMenuIconPickerBound = true;
			document.addEventListener('click', function(event){
				document.querySelectorAll('.puffergo-menu-icon-picker-dropdown.is-open').forEach(function(dropdown){
					if (!dropdown.contains(event.target)) {
						dropdown.classList.remove('is-open');
						var dropdownTrigger = dropdown.querySelector('.puffergo-menu-icon-picker-trigger');
						if (dropdownTrigger) {
							dropdownTrigger.setAttribute('aria-expanded', 'false');
						}
					}
				});

				var trigger = event.target.closest('.puffergo-menu-icon-picker-trigger');
				if (trigger) {
					var triggerDropdown = trigger.closest('.puffergo-menu-icon-picker-dropdown');
					if (!triggerDropdown) {
						return;
					}
					var shouldOpen = !triggerDropdown.classList.contains('is-open');
					document.querySelectorAll('.puffergo-menu-icon-picker-dropdown.is-open').forEach(function(openDropdown){
						openDropdown.classList.remove('is-open');
						var openTrigger = openDropdown.querySelector('.puffergo-menu-icon-picker-trigger');
						if (openTrigger) {
							openTrigger.setAttribute('aria-expanded', 'false');
						}
					});
					triggerDropdown.classList.toggle('is-open', shouldOpen);
					trigger.setAttribute('aria-expanded', shouldOpen ? 'true' : 'false');
					return;
				}

				var clearButton = event.target.closest('.puffergo-menu-icon-picker-clear');
				if (clearButton) {
					var clearSelector = clearButton.getAttribute('data-target');
					var clearInput = clearSelector ? document.querySelector(clearSelector) : null;
					if (!clearInput) {
						return;
					}
					clearInput.value = '';
					var clearDropdown = clearButton.closest('.puffergo-menu-icon-picker-dropdown');
					if (!clearDropdown) {
						return;
					}
					clearDropdown.querySelectorAll('.puffergo-menu-icon-picker-option').forEach(function(option){
						option.classList.remove('is-selected');
						option.setAttribute('aria-selected', 'false');
					});
					var clearTrigger = clearDropdown.querySelector('.puffergo-menu-icon-picker-trigger');
					if (!clearTrigger) {
						return;
					}
					var oldClearIcon = clearTrigger.querySelector('.puffergo-menu-icon-picker-svg, .dashicons-no-alt');
					if (oldClearIcon) {
						oldClearIcon.remove();
					}
					var clearMain = clearTrigger.querySelector('.puffergo-menu-icon-picker-trigger-main');
					if (clearMain) {
						var noIcon = document.createElement('span');
						noIcon.className = 'dashicons dashicons-no-alt';
						noIcon.setAttribute('aria-hidden', 'true');
						clearMain.insertBefore(noIcon, clearMain.firstChild);
					}
					clearDropdown.classList.remove('is-open');
					clearTrigger.setAttribute('aria-expanded', 'false');
					return;
				}

				var button = event.target.closest('.puffergo-menu-icon-picker-option');
				if (!button) {
					return;
				}
				var selector = button.getAttribute('data-target');
				var input = selector ? document.querySelector(selector) : null;
				if (!input) {
					return;
				}
				input.value = button.getAttribute('data-value') || '';
				var panel = button.closest('.puffergo-menu-icon-picker-panel');
				if (!panel) {
					return;
				}
				panel.querySelectorAll('.puffergo-menu-icon-picker-option').forEach(function(option){
					var isSelected = option === button;
					option.classList.toggle('is-selected', isSelected);
					option.setAttribute('aria-selected', isSelected ? 'true' : 'false');
				});

				var dropdown = button.closest('.puffergo-menu-icon-picker-dropdown');
				if (!dropdown) {
					return;
				}
				var dropdownTrigger = dropdown.querySelector('.puffergo-menu-icon-picker-trigger');
				if (!dropdownTrigger) {
					return;
				}
				var oldIcon = dropdownTrigger.querySelector('.puffergo-menu-icon-picker-svg, .dashicons-no-alt');
				if (oldIcon) {
					oldIcon.remove();
				}
				var selectedIcon = button.querySelector('.puffergo-menu-icon-picker-svg, .dashicons-no-alt');
				if (selectedIcon) {
					var clonedIcon = selectedIcon.cloneNode(true);
					var triggerMain = dropdownTrigger.querySelector('.puffergo-menu-icon-picker-trigger-main');
					if (triggerMain) {
						triggerMain.insertBefore(clonedIcon, triggerMain.firstChild);
					}
				}
				dropdown.classList.remove('is-open');
				dropdownTrigger.setAttribute('aria-expanded', 'false');
			});
		})();
	</script>
	<?php
} function puffergo_save_menu_item_icon_field($menu_id, $menu_item_db_id, $args)
{
    unset($menu_id, $args);
    $submitted = isset($_POST['puffergo_menu_item_icon'][ $menu_item_db_id ]) ? sanitize_key(wp_unslash($_POST['puffergo_menu_item_icon'][ $menu_item_db_id ])) : '';
    $registry = puffergo_get_menu_icon_registry();

    if ('' === $submitted) {
        delete_post_meta((int) $menu_item_db_id, '_puffergo_menu_icon');

        return;
    }

if (isset($registry[ $submitted ])) {
        update_post_meta((int) $menu_item_db_id, '_puffergo_menu_icon', $submitted);

        return;
    } delete_post_meta((int) $menu_item_db_id, '_puffergo_menu_icon');
}

if (is_admin()) {
    add_action('wp_nav_menu_item_custom_fields', 'puffergo_render_menu_item_icon_field', 10, 5);
    add_action('wp_update_nav_menu_item', 'puffergo_save_menu_item_icon_field', 10, 3);
    add_action('admin_print_footer_scripts-nav-menus.php', 'puffergo_print_menu_icon_picker_assets');
}
