<?php
/**
 * Plugin Name: Wave Access
 * Plugin URI: https://wavetools.io
 * Description: Lightweight frontend accessibility widget plus backend audit tools — helps you meet WCAG 2.1 AA, the European Accessibility Act (EAA) and Germany's BFSG.
 * Version: 2.3.4
 * Author: Wave Tools
 * Author URI: https://wavetools.io
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: wave-access
 * Domain Path: /languages
 * Requires at least: 5.0
 * Requires PHP: 7.4
 */

// Sicherheit: Direkten Zugriff verhindern
if (!defined('ABSPATH')) {
	exit;
}

// Plugin-Konstanten definieren
define('WAVE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WAVE_PLUGIN_URL', plugin_dir_url(__FILE__));
define('WAVE_VERSION', '2.3.4');

/* --- Updates über den Wave-Tools-Update-Server (nur Pro-Build; die Free-Version
       von wordpress.org wird dort aktualisiert und enthält diese Datei nicht) --- */
if ( file_exists( plugin_dir_path(__FILE__) . 'class-klopkom-updater.php' ) ) {
	require_once plugin_dir_path(__FILE__) . 'class-klopkom-updater.php';
	$wave_updater = new KlopKom_Updater(
		'https://wavetools.io/api/wave-update/v1/info/wave-access',
		__FILE__,
		'wave-access'
	);
	$wave_updater->set_query_args_callback( function ( $args ) {
		// Läuft erst bei Update-Checks — Wave_License ist dann längst geladen.
		$args['license_key'] = class_exists( 'Wave_License' ) ? (string) Wave_License::key() : '';
		$args['site_url']    = home_url();
		$args['version']     = WAVE_VERSION;
		return $args;
	} );
}

/* --- Module --- */
require_once WAVE_PLUGIN_DIR . 'includes/wave-icons.php';
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-license.php';      // Lizenzierung (Pro/Pro AI/Agency)
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-ai-client.php';    // KI-Proxy (serv01)
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-alt-text.php';     // KI-Alt-Texte
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-statement.php';    // Barrierefreiheitserklärung (Pro)
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-report-pdf.php';   // PDF-Prüfbericht (Pro)
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-integrations.php'; // Elementor & WPBakery
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-tts.php';          // Vorlesen (Pro AI)
require_once WAVE_PLUGIN_DIR . 'includes/class-wave-easy-language.php'; // Leichte Sprache (Pro AI)
if ( file_exists( WAVE_PLUGIN_DIR . 'includes/class-wave-banner.php' ) ) {
	require_once WAVE_PLUGIN_DIR . 'includes/class-wave-banner.php';    // Backend-Banner (nur Pro-Build; auf wordpress.org nicht erlaubt)
}

/* WP-Rocket-Kompatibilität: „Remove Unused CSS" entfernt sonst Klassen,
   die erst zur Laufzeit per JS gesetzt werden (Karaoke, Modi, Panel). */
add_filter( 'rocket_rucss_safelist', function ( $list ) {
	return array_merge( (array) $list, array(
		'.wave-tts-word-now', '.wave-tts-playing', '.wave-tts-loading', '.wave-tts-w',
		'.wave-easy-on', '.wave-easy-view', '.wave-easy-note', '.wave-easy-content', '.wave-easy-loading',
		'.wave-sr-mode', '.wave-sr-active', '.wave-panel-foot', '.wave-brand',
		'(.*)wave-widget(.*)', '(.*)wave-feature-btn(.*)', '(.*)wave-panel(.*)', '(.*)wave-slider(.*)',
	) );
} );
Wave_License::instance();
Wave_Statement::instance();
Wave_Report_PDF::instance();

/**
 * Hauptklasse des Plugins
 */
class Wave_Access {
	
	private static $instance = null;
	private $options;
	
	/**
	 * Singleton Instance
	 */
	public static function get_instance() {
		if (null === self::$instance) {
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Konstruktor
	 */
	private function __construct() {
		// Gespeicherte Optionen IMMER mit den Defaults verschmelzen –
		// sonst fehlen nach Updates neu hinzugekommene Schlüssel
		// (z. B. show_admin_bar, widget_position) und empty()-Guards
		// blenden Funktionen fälschlich aus.
		$this->options = wp_parse_args( get_option('wave_options', array()), $this->get_default_options() );
		$this->init_hooks();
	}
	
	/**
	 * Standard-Optionen
	 */
	private function get_default_options() {
		return array(
			'enable_grayscale' => true,
			'enable_skip_links' => true,
			'enable_focus_indicator' => true,
			'enable_image_checker' => true,
			'enable_heading_checker' => true,
			'enable_aria_labels' => true,
			'enable_contrast_toggle' => true,
			'enable_font_resizer' => true,
			'enable_keyboard_nav' => true,
			'enable_screen_reader_text' => true,
			'enable_lang_attributes' => true,
			'enable_tab_order' => true,
			'enable_tab_visualizer' => false,
			'enable_floating_widget' => true,
			'enable_underline_links' => true,
			'enable_inherit_font' => false,
			'email_notifications' => false,
			'custom_focus_color' => '#0073aa',
			'widget_accent_color' => '#4a4a4a',
			'min_contrast_ratio' => '4.5',
			// Widget 2.0 – Darstellung
			'widget_position'    => 'br',      // br | bl | tr | tl
			'widget_offset'      => 24,        // Randabstand in px
			'widget_size'        => 'm',       // s | m | l
			'widget_radius'      => 24,        // Panel-Rundung in px
			'widget_icon'        => 'person',  // person | wheelchair | sliders | custom
			'widget_icon_custom' => '',        // Attachment-URL bei custom
			'panel_theme'        => 'light',   // light | dark | custom
			'panel_bg_var'       => '',        // CSS-Variable für Hintergrund (custom)
			'panel_text_var'     => '',        // CSS-Variable für Text (custom)
			'show_branding'      => true,      // "powered by Wave Tools" (abschaltbar ab Pro)
			// Backend-Integration
			'show_dashboard_widget' => true,   // Status-Widget im WP-Dashboard
			'show_admin_bar'        => true    // Eintrag in der Admin-Leiste
		);
	}
	
	/**
	 * Hooks initialisieren
	 */
	private function init_hooks() {
		// Admin Hooks
		add_action('admin_menu', array($this, 'add_admin_menu'));
		add_filter('plugin_action_links_' . plugin_basename(WAVE_PLUGIN_DIR . 'wave-access.php'), array($this, 'plugin_action_links'));
		add_action('admin_init', array($this, 'register_settings'));
		add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
		add_action('wp_dashboard_setup', array($this, 'add_dashboard_widget'));
		add_action('admin_notices', array($this, 'show_admin_notices'));
		add_action('admin_bar_menu', array($this, 'add_admin_bar_menu'), 100);
		
		// Frontend Hooks
		add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
		add_action('wp_body_open', array($this, 'add_skip_links'));
		add_action('wp_footer', array($this, 'add_accessibility_toolbar'));

		// Gutenberg-Block: Eingabehilfen-Panel direkt im Inhalt
		add_action('init', array($this, 'register_block'));

		// Shortcode [wave_access]: Panel an beliebiger Stelle ohne Floating-Button
		add_shortcode('wave_access', array($this, 'render_shortcode'));
		
		// Content Filter
		add_filter('the_content', array($this, 'check_content_accessibility'));
		add_filter('wp_get_attachment_image_attributes', array($this, 'check_image_alt'), 10, 3);
		
		// HTML Lang und Dir Attribute
		add_filter('language_attributes', array($this, 'add_language_attributes'), 10, 2);
		
		// Media Upload Hook für Alt-Text Warnung
		add_action('add_attachment', array($this, 'check_new_image_alt'));
		add_action('edit_attachment', array($this, 'check_updated_image_alt'));
		
		// AJAX Handlers
		add_action('wp_ajax_wave_save_preferences', array($this, 'ajax_save_preferences'));
		add_action('wp_ajax_nopriv_wave_save_preferences', array($this, 'ajax_save_preferences'));
		add_action('wp_ajax_wave_dismiss_notice', array($this, 'ajax_dismiss_notice'));
		add_action('wp_ajax_wave_save_checklist', array($this, 'ajax_save_checklist'));
	}
	
	/**
	 * „Einstellungen"-Link in der Plugin-Liste
	 */
	public function plugin_action_links( $links ) {
		array_unshift( $links, '<a href="' . esc_url( admin_url('options-general.php?page=wave-access') ) . '">' . __('Einstellungen', 'wave-access') . '</a>' );
		return $links;
	}

	/**
	 * Admin-Menü hinzufügen
	 */
	public function add_admin_menu() {
		// Eine einzige Seite unter „Einstellungen" – Inhalte über drei Haupt-Reiter.
		add_options_page(
			__('Barrierefreiheit', 'wave-access'),
			__('Barrierefreiheit', 'wave-access'),
			'manage_options',
			'wave-access',
			array($this, 'settings_page')
		);
	}

	/**
	 * Sammel-Einstellungsseite (unter „Einstellungen") mit drei Haupt-Reitern:
	 * Einstellungen, Prüfbericht, Tab-Reihenfolge.
	 */
	public function settings_page() {
		// CSV-Export VOR jeglicher HTML-Ausgabe verarbeiten (sonst „headers already sent").
		if ( isset($_GET['export']) && $_GET['export'] === 'csv'
			&& isset($_GET['_wpnonce'])
			&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'export_report' ) ) {
			$this->export_csv_report();
			return;
		}

		$tabs = array(
			'settings'  => array( 'label' => __('Allgemein', 'wave-access'),         'icon' => 'gear',                'pro' => false ),
			'widget'    => array( 'label' => __('Widget', 'wave-access'),            'icon' => 'universal-access',    'pro' => false ),
			'ki'        => array( 'label' => __('KI-Funktionen', 'wave-access'),      'icon' => 'wand-magic-sparkles', 'pro' => true ),
			'statement' => array( 'label' => __('Erklärung', 'wave-access'),          'icon' => 'file-lines',          'pro' => true ),
			'report'    => array( 'label' => __('Prüfbericht', 'wave-access'),        'icon' => 'list-check',          'pro' => false ),
			'tab-order' => array( 'label' => __('Tab-Reihenfolge', 'wave-access'),    'icon' => 'keyboard',            'pro' => false ),
			'license'   => array( 'label' => __('Lizenz', 'wave-access'),             'icon' => 'key',                 'pro' => false ),
		);
		$maintab = isset($_GET['maintab']) ? sanitize_text_field( wp_unslash( $_GET['maintab'] ) ) : 'settings';
		if ( ! isset($tabs[$maintab]) ) {
			$maintab = 'settings';
		}
		?>
		<div class="wrap wave-admin">
			<?php /* Anker für WordPress-Admin-Notices: sammelt sie GANZ OBEN,
			         statt sie per JS hinter die erste Überschrift zu schieben. */ ?>
			<hr class="wp-header-end" style="display:none">
			<div class="wave-head">
				<img class="wave-head-logo" src="<?php echo esc_url( WAVE_PLUGIN_URL . 'assets/wave-access-icon.svg' ); ?>" alt="" width="46" height="46">
				<div>
					<h1><?php esc_html_e('Barrierefreiheit', 'wave-access'); ?></h1>
					<p><?php esc_html_e('Eingabehilfen, KI-Funktionen und Prüfwerkzeuge – BFSG / WCAG 2.1 AA', 'wave-access'); ?></p>
				</div>
			</div>

			<nav class="wave-tabs">
				<?php foreach ( $tabs as $key => $t ) : ?>
					<a href="<?php echo esc_url( admin_url('options-general.php?page=wave-access&maintab=' . $key) ); ?>" class="wave-tab <?php echo $maintab === $key ? 'is-active' : ''; ?>">
						<?php echo wave_icon( $t['icon'], 16 ); ?>
						<span><?php echo esc_html( $t['label'] ); ?></span>
						<?php if ( $t['pro'] ) : ?><span class="wave-pill wave-pill-pro"><?php echo wave_icon('sparkles', 10); ?>Pro</span><?php endif; ?>
					</a>
				<?php endforeach; ?>
			</nav>

			<div class="wave-maintab-content">
				<?php
				switch ( $maintab ) {
					case 'widget':
						$this->widget_tab();
						break;
					case 'ki':
						if ( class_exists('WAVE_Alt_Text') ) {
							WAVE_Alt_Text::instance()->render_settings_tab();
						}
						break;
					case 'statement':
						Wave_Statement::instance()->render_tab();
						break;
					case 'report':
						$this->report_page();
						break;
					case 'tab-order':
						$this->tab_order_page();
						break;
					case 'license':
						Wave_License::instance()->render_tab();
						break;
					default:
						$this->admin_page();
						break;
				}
				?>
			</div>
		</div>
		<?php
	}

	/**
	 * Hilfsfunktion: eine Switch-Zeile (Label + Beschreibung + Toggle) rendern.
	 */
	private function render_switch_row( $option, $label, $desc = '', $icon = '', $default = false ) {
		$checked = isset( $this->options[ $option ] ) ? (bool) $this->options[ $option ] : (bool) $default;
		?>
		<div class="wave-row">
			<div class="wave-row-main">
				<?php if ( $icon ) : ?><span class="wave-row-ic"><?php echo wave_icon( $icon, 18 ); ?></span><?php endif; ?>
				<div>
					<div class="wave-row-label"><?php echo esc_html( $label ); ?></div>
					<?php if ( $desc ) : ?><div class="wave-row-desc"><?php echo esc_html( $desc ); ?></div><?php endif; ?>
				</div>
			</div>
			<div class="wave-row-control">
				<label class="wave-switch">
					<input type="checkbox" name="wave_options[<?php echo esc_attr( $option ); ?>]" value="1" <?php checked( $checked ); ?> />
					<span class="wave-slider"></span>
				</label>
			</div>
		</div>
		<?php
	}
	
	/**
	 * Einstellungen registrieren
	 */
	public function register_settings() {
		register_setting('wave_settings_group', 'wave_options', array($this, 'sanitize_options'));
	}
	
	/**
	 * Optionen bereinigen
	 */
	public function sanitize_options($options) {
		$defaults = $this->get_default_options();
		$existing = wp_parse_args( get_option('wave_options', array()), $defaults );

		// Die Einstellungen verteilen sich auf zwei Formulare (Allgemein / Widget).
		// Nur die Schlüssel des absendenden Formulars anfassen, Rest unverändert lassen.
		$widget_keys = array('enable_grayscale','enable_contrast_toggle','enable_font_resizer','enable_underline_links',
			'enable_floating_widget','widget_accent_color','widget_position','widget_offset','widget_size','widget_radius',
			'widget_icon','widget_icon_custom','panel_theme','panel_bg_var','panel_text_var','show_branding');
		$form = isset($options['_form']) && 'widget' === $options['_form'] ? 'widget' : 'general';
		unset($options['_form']);
		$scope = ('widget' === $form)
			? $widget_keys
			: array_diff( array_keys($defaults), $widget_keys );

		$clean_options = $existing;

		// Farb-Felder (Hex oder CSS-Variable)
		$color_fields = array('custom_focus_color', 'widget_accent_color');
		$enums = array(
			'widget_position' => array('br','bl','tr','tl'),
			'widget_size'     => array('s','m','l'),
			'widget_icon'     => array('person','wheelchair','sliders','custom'),
			'panel_theme'     => array('light','dark','custom'),
		);
		$int_fields = array('widget_offset' => array(8, 80), 'widget_radius' => array(4, 40));
		$var_fields = array('panel_bg_var', 'panel_text_var');

		foreach ($scope as $key) {
			$default_value = $defaults[$key];
			$raw = isset($options[$key]) ? $options[$key] : null;
			if (is_bool($default_value)) {
				$clean_options[$key] = (bool) $raw;
			} elseif (in_array($key, $color_fields, true)) {
				$clean_options[$key] = self::sanitize_color_value( (string) $raw, $default_value );
			} elseif (isset($enums[$key])) {
				$clean_options[$key] = in_array($raw, $enums[$key], true) ? $raw : $default_value;
			} elseif (isset($int_fields[$key])) {
				$clean_options[$key] = max($int_fields[$key][0], min($int_fields[$key][1], (int) $raw));
			} elseif (in_array($key, $var_fields, true)) {
				$clean_options[$key] = preg_match('/^--[a-zA-Z0-9_-]+$/', trim((string) $raw)) ? trim($raw) : '';
			} elseif ('widget_icon_custom' === $key) {
				$clean_options[$key] = esc_url_raw((string) $raw);
			} else {
				$clean_options[$key] = null !== $raw ? sanitize_text_field($raw) : $default_value;
			}
		}

		// Branding-Abschaltung ist Pro-Funktion
		if ( ! Wave_License::is_pro() ) {
			$clean_options['show_branding'] = true;
		}

		return $clean_options;
	}

	/**
	 * Farbwert bereinigen: erlaubt Hex-Farben ODER CSS-Custom-Properties.
	 * "--primary" und "var(--primary)" werden zu "var(--primary)" normalisiert.
	 */
	public static function sanitize_color_value( $raw, $default ) {
		$raw = trim( (string) $raw );
		$hex = sanitize_hex_color( $raw );
		if ( ! empty( $hex ) ) {
			return $hex;
		}
		if ( preg_match( '/^(?:var\(\s*)?(--[a-zA-Z0-9_-]+)\s*\)?$/', $raw, $m ) ) {
			return 'var(' . $m[1] . ')';
		}
		return $default;
	}

	/** Sicheren CSS-Farbausdruck liefern (Hex oder var(--…)). */
	private function css_color( $key, $default ) {
		$v = isset( $this->options[ $key ] ) ? $this->options[ $key ] : '';
		return self::sanitize_color_value( $v, $default );
	}
	
	/**
	 * Admin-Seite
	 */
	public function admin_page() {
		$accent = isset($this->options['widget_accent_color']) ? $this->options['widget_accent_color'] : '#4a4a4a';
		$focus  = isset($this->options['custom_focus_color']) ? $this->options['custom_focus_color'] : '#0073aa';
		?>
		<form method="post" action="options.php">
			<?php settings_fields('wave_settings_group'); ?>
			<input type="hidden" name="wave_options[_form]" value="general">

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('gear', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Automatische Optimierung', 'wave-access'); ?></h2>
						<p class="wave-card-desc"><?php esc_html_e('Wirkt unsichtbar im Hintergrund – ohne Zutun der Besucher.', 'wave-access'); ?></p>
					</div>
				</div>
				<div class="wave-rows">
					<?php
					$this->render_switch_row('enable_skip_links', __('Sprungmarken (Skip-Links)', 'wave-access'), __('Schneller Sprung zu Inhalt und Navigation', 'wave-access'), 'link', true);
					$this->render_switch_row('enable_focus_indicator', __('Fokus-Indikator verbessern', 'wave-access'), __('Deutlich sichtbarer Tastaturfokus', 'wave-access'), 'eye-low-vision', true);
					$this->render_switch_row('enable_aria_labels', __('ARIA-Auszeichnung', 'wave-access'), __('Automatische Landmarks für Screenreader', 'wave-access'), 'universal-access', true);
					$this->render_switch_row('enable_lang_attributes', __('Sprach- & Richtungsattribute', 'wave-access'), __('Setzt lang und dir im HTML-Tag', 'wave-access'), 'font', true);
					$this->render_switch_row('enable_heading_checker', __('Überschriften-Hierarchie prüfen', 'wave-access'), __('Warnt bei übersprungenen Ebenen', 'wave-access'), 'heading', true);
					$this->render_switch_row('enable_image_checker', __('Alt-Text-Prüfung', 'wave-access'), __('Warnt im Backend bei fehlenden Alt-Texten', 'wave-access'), 'image', true);
					?>
					<div class="wave-row">
						<div class="wave-row-main">
							<span class="wave-row-ic"><?php echo wave_icon('palette', 18); ?></span>
							<div>
								<div class="wave-row-label"><?php esc_html_e('Fokus-Farbe', 'wave-access'); ?></div>
								<div class="wave-row-desc"><?php esc_html_e('Hex-Farbe oder CSS-Variable (z. B. var(--focus-color))', 'wave-access'); ?></div>
							</div>
						</div>
						<div class="wave-row-control">
							<div class="wave-colorctl">
								<input type="color" value="<?php echo esc_attr( 0 === strpos($focus, '#') ? $focus : '#0073aa' ); ?>" data-wave-sync="focus" aria-label="<?php esc_attr_e('Farbe wählen', 'wave-access'); ?>" />
								<input type="text" class="wave-field" id="wave-color-focus" name="wave_options[custom_focus_color]" value="<?php echo esc_attr($focus); ?>" placeholder="#0073aa oder var(--focus)" />
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('keyboard', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Tastatur-Navigation', 'wave-access'); ?></h2>
						<p class="wave-card-desc"><?php esc_html_e('Reihenfolge und Prüfwerkzeuge für die Tastaturbedienung.', 'wave-access'); ?></p>
					</div>
				</div>
				<div class="wave-rows">
					<?php
					$this->render_switch_row('enable_tab_order', __('Tab-Reihenfolge optimieren', 'wave-access'), __('Automatische Optimierung der Reihenfolge', 'wave-access'), 'keyboard', true);
					$this->render_switch_row('enable_tab_visualizer', __('Tab-Reihenfolge visualisieren', 'wave-access'), __('Zeigt die Reihenfolge mit Nummern an (nur für Admins)', 'wave-access'), 'eye', false);
					?>
				</div>
			</div>

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('gauge-high', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Backend-Integration', 'wave-access'); ?></h2>
						<p class="wave-card-desc"><?php esc_html_e('Sichtbarkeit von Wave Access im WordPress-Backend.', 'wave-access'); ?></p>
					</div>
				</div>
				<div class="wave-rows">
					<?php
					$this->render_switch_row('show_dashboard_widget', __('Dashboard-Widget anzeigen', 'wave-access'), __('Status-Übersicht auf dem WP-Dashboard', 'wave-access'), 'gauge-high', true);
					$this->render_switch_row('show_admin_bar', __('Eintrag in der Admin-Leiste', 'wave-access'), __('Schnellzugriff „Barrierefreiheit" in der oberen Admin-Leiste', 'wave-access'), 'list-check', true);
					?>
				</div>
			</div>

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('triangle-exclamation', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Benachrichtigungen', 'wave-access'); ?></h2>
					</div>
				</div>
				<div class="wave-rows">
					<?php $this->render_switch_row('email_notifications', __('E-Mail bei fehlendem Alt-Text', 'wave-access'), __('Hinweis-Mail, wenn ein Bild ohne Alt-Text hochgeladen wird', 'wave-access'), 'triangle-exclamation', false); ?>
				</div>
				<div class="wave-actions">
					<button type="submit" class="wave-btn wave-btn-primary"><?php echo wave_icon('circle-check', 16); ?> <?php esc_html_e('Änderungen speichern', 'wave-access'); ?></button>
				</div>
			<script>
			document.querySelectorAll('[data-wave-sync]').forEach(function(picker){
				var text = document.getElementById('wave-color-' + picker.dataset.waveSync);
				picker.addEventListener('input', function(){ text.value = picker.value; });
				text.addEventListener('input', function(){
					if (/^#[0-9a-fA-F]{6}$/.test(text.value.trim())) { picker.value = text.value.trim(); }
				});
			});
			</script>
			</div>
		</form>
		<?php
	}


	/**
	 * Eingebaute Widget-Button-Icons (gefüllt, currentColor).
	 */
	public static function fab_icons() {
		return array(
			'person'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="m13.4338078 4.18678c.102.47196-.1979.93728-.6698 1.03933l-2.7185.58777c-.46018001.09951-.78864001.50657-.78864001.97742v.87968c0 .9559.17132 1.90408.50584 2.79952l1.62460001 4.349c.169.4523-.0607.956-.5131 1.125-.4523.169-.95600001-.0608-1.12490001-.5131l-1.5541-4.1601c-.16189-.4334-.77488-.4334-.93677 0l-1.55407 4.1601c-.16898.4523-.67265.6821-1.12498.5131s-.68204-.6727-.51306-1.125l1.62465-4.3491c.33452-.89544.50584-1.84362.50584-2.79952v-.87959c0-.47085-.32846-.87791-.78867-.97741l-2.71843-.58777c-.47196-.10205-.77183-.56737-.66979-1.03933.10205-.47195.56737-.77183 1.03933-.66978l3.82226.82644c.55712.12045 1.13355.12045 1.69067 0l3.82222001-.82644c.472-.10205.9373.19783 1.0394.66978zm-5.75039001-4.18678c.96572511 0 1.7486.78287489 1.7486 1.7486s-.78287489 1.7486-1.7486 1.7486c-.96572512 0-1.7486-.78287489-1.7486-1.7486s.78287488-1.7486 1.7486-1.7486z"/></svg>',
			'wheelchair' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" fill="currentColor" aria-hidden="true"><path d="M519.9 319.8L507 477.1C503.7 517.8 443.1 512.2 446.4 472.2L456.4 349.7L415.3 352C425.4 372.7 431.1 395.9 431.1 420.5C431.1 461.7 415 499.2 388.8 527L349.5 487.7C407.4 424 362.6 320.5 275.5 320.5C249.6 320.5 226 330.4 208.3 346.5L169 307.2C191 286.5 219.1 272.1 250.4 267L325.7 181.3L283.1 156.5L231.5 202.5C201.5 229.3 160.9 184 191 157.1L259 96.4C268.8 87.6 283.1 86.2 294.5 92.8C294.5 92.8 433.8 173.7 434 173.9C450.2 184 454.7 209.9 440.1 226.5L381.7 293L487.8 287.1C506.3 286 521.4 301.5 519.9 319.8zM455 165.8C483.1 165.8 505.9 143 505.9 114.9C505.9 86.8 483.1 64 455 64C426.9 64 404.1 86.8 404.1 114.9C404.1 143 426.9 165.8 455 165.8zM275.6 520.5C195 520.5 148.2 429.9 192.9 364.4L153.2 324.7C132.4 351 120 384.3 120 420.4C120 551.1 270.7 621.8 371.4 542.9L331.7 503.2C315.7 514.1 296.4 520.5 275.6 520.5z"/></svg>',
			'sliders'    => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" fill="currentColor" aria-hidden="true"><path d="M4 10.5h14.3a4 4 0 007.4 0H32a1.5 1.5 0 000-3h-6.3a4 4 0 00-7.4 0H4a1.5 1.5 0 000 3zM32 25.5H17.7a4 4 0 00-7.4 0H4a1.5 1.5 0 000 3h6.3a4 4 0 007.4 0H32a1.5 1.5 0 000-3zM32 16.5H13.7a4 4 0 00-7.4 0H4a1.5 1.5 0 000 3h2.3a4 4 0 007.4 0H32a1.5 1.5 0 000-3z"/></svg>',
		);
	}

	/** Markup des gewählten Widget-Button-Icons. */
	private function fab_icon_markup() {
		$icons = self::fab_icons();
		$choice = isset($this->options['widget_icon']) ? $this->options['widget_icon'] : 'person';
		if ( 'custom' === $choice && ! empty($this->options['widget_icon_custom']) ) {
			return '<img src="' . esc_url($this->options['widget_icon_custom']) . '" alt="" aria-hidden="true" />';
		}
		return isset($icons[$choice]) ? $icons[$choice] : $icons['person'];
	}

	/**
	 * Reiter "Widget" – alle Darstellungs-Einstellungen des Frontend-Widgets.
	 */
	public function widget_tab() {
		$o = $this->options;
		$accent = self::sanitize_color_value( isset($o['widget_accent_color']) ? $o['widget_accent_color'] : '', '#4a4a4a' );
		$is_pro = Wave_License::is_pro();
		$seg = function( $name, $value, $choices ) {
			echo '<div class="wave-seg">';
			foreach ( $choices as $val => $label ) {
				printf('<label class="%s"><input type="radio" name="wave_options[%s]" value="%s" %s>%s</label>',
					$value === $val ? 'is-on' : '', esc_attr($name), esc_attr($val), checked($value, $val, false), esc_html($label));
			}
			echo '</div>';
		};
		?>
		<form method="post" action="options.php">
			<?php settings_fields('wave_settings_group'); ?>
			<input type="hidden" name="wave_options[_form]" value="widget">

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('eye', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Eingabehilfen im Widget', 'wave-access'); ?></h2>
						<p class="wave-card-desc"><?php esc_html_e('Funktionen, die deine Besucher im Bedienfeld selbst nutzen können.', 'wave-access'); ?></p>
					</div>
				</div>
				<div class="wave-rows">
					<?php
					$this->render_switch_row('enable_grayscale', __('Grauskala & Monochrom', 'wave-access'), __('Graustufen-Ansicht für bessere Lesbarkeit', 'wave-access'), 'droplet', true);
					$this->render_switch_row('enable_contrast_toggle', __('Kontrast-Modi', 'wave-access'), __('Dunkler und heller Hochkontrast', 'wave-access'), 'circle-half-stroke', true);
					$this->render_switch_row('enable_font_resizer', __('Schrift & Skalierung', 'wave-access'), __('Schriftgröße, Zeilenhöhe und Zeichenabstand anpassbar', 'wave-access'), 'text-size', true);
					$this->render_switch_row('enable_underline_links', __('Links unterstreichen', 'wave-access'), __('Bessere Erkennbarkeit von Links', 'wave-access'), 'link', true);
					?>
				</div>
			</div>

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('universal-access', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Schwebender Button', 'wave-access'); ?></h2>
						<p class="wave-card-desc"><?php esc_html_e('Position, Größe und Icon des Öffnen-Buttons.', 'wave-access'); ?></p>
					</div>
				</div>
				<div class="wave-rows">
					<?php $this->render_switch_row('enable_floating_widget', __('Schwebenden Button anzeigen', 'wave-access'), __('Ausschalten, wenn du das Panel selbst platzierst – die Alternativen stehen unten.', 'wave-access'), 'universal-access', true); ?>
					<div class="wave-row">
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('Position', 'wave-access'); ?></div>
							<div class="wave-row-desc"><?php esc_html_e('Ecke, in der Button und Panel erscheinen', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control"><?php $seg('widget_position', $o['widget_position'], array('tl' => '↖', 'tr' => '↗', 'bl' => '↙', 'br' => '↘')); ?></div>
					</div>
					<div class="wave-row">
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('Rand-Abstand', 'wave-access'); ?></div>
							<div class="wave-row-desc"><?php esc_html_e('Abstand zum Seitenrand in Pixeln (8–80)', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control"><input type="number" class="wave-field" style="width:80px" min="8" max="80" name="wave_options[widget_offset]" value="<?php echo (int) $o['widget_offset']; ?>"> px</div>
					</div>
					<div class="wave-row">
						<div class="wave-row-main"><div><div class="wave-row-label"><?php esc_html_e('Button-Größe', 'wave-access'); ?></div></div></div>
						<div class="wave-row-control"><?php $seg('widget_size', $o['widget_size'], array('s' => 'S', 'm' => 'M', 'l' => 'L')); ?></div>
					</div>
					<div class="wave-row">
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('Button-Icon', 'wave-access'); ?></div>
							<div class="wave-row-desc"><?php esc_html_e('Drei eingebaute Icons – oder ein eigenes aus der Mediathek', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control">
							<div class="wave-iconpick">
								<?php foreach ( self::fab_icons() as $key => $svg ) : ?>
									<label class="<?php echo $o['widget_icon'] === $key ? 'is-on' : ''; ?>"><input type="radio" name="wave_options[widget_icon]" value="<?php echo esc_attr($key); ?>" <?php checked($o['widget_icon'], $key); ?>><?php echo $svg; ?></label>
								<?php endforeach; ?>
								<label class="wave-iconpick-custom <?php echo 'custom' === $o['widget_icon'] ? 'is-on' : ''; ?>">
									<input type="radio" name="wave_options[widget_icon]" value="custom" <?php checked($o['widget_icon'], 'custom'); ?>>
									<?php if ( $o['widget_icon_custom'] ) : ?><img src="<?php echo esc_url($o['widget_icon_custom']); ?>" alt=""><?php else : ?>＋<?php endif; ?>
								</label>
							</div>
							<input type="hidden" id="wave-icon-custom-url" name="wave_options[widget_icon_custom]" value="<?php echo esc_url($o['widget_icon_custom']); ?>">
							<button type="button" class="wave-btn" id="wave-icon-media" style="margin-top:8px"><?php esc_html_e('Aus Mediathek wählen…', 'wave-access'); ?></button>
						</div>
					</div>
				</div>
			</div>

			<div class="wave-card">
				<div class="wave-card-head">
					<span class="wave-card-ic"><?php echo wave_icon('palette', 20); ?></span>
					<div>
						<h2 class="wave-card-title"><?php esc_html_e('Aussehen des Panels', 'wave-access'); ?></h2>
						<p class="wave-card-desc"><?php esc_html_e('Farben, Rundung und Theme – auf Wunsch gekoppelt an dein Website-Design.', 'wave-access'); ?></p>
					</div>
				</div>
				<div class="wave-rows">
					<div class="wave-row">
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('Akzentfarbe', 'wave-access'); ?></div>
							<div class="wave-row-desc"><?php esc_html_e('Hex per Picker oder CSS-Variable (z. B. var(--primary))', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control">
							<div class="wave-colorctl">
								<input type="color" value="<?php echo esc_attr( 0 === strpos($accent, '#') ? $accent : '#4a4a4a' ); ?>" data-wave-sync="accent" aria-label="<?php esc_attr_e('Farbe wählen', 'wave-access'); ?>" />
								<input type="text" class="wave-field" id="wave-color-accent" name="wave_options[widget_accent_color]" value="<?php echo esc_attr($accent); ?>" placeholder="#4a4a4a oder var(--primary)" />
							</div>
						</div>
					</div>
					<div class="wave-row">
						<div class="wave-row-main"><div><div class="wave-row-label"><?php esc_html_e('Panel-Rundung', 'wave-access'); ?></div></div></div>
						<div class="wave-row-control"><input type="number" class="wave-field" style="width:80px" min="4" max="40" name="wave_options[widget_radius]" value="<?php echo (int) $o['widget_radius']; ?>"> px</div>
					</div>
					<div class="wave-row">
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('Panel-Theme', 'wave-access'); ?></div>
							<div class="wave-row-desc"><?php esc_html_e('„Eigene Variablen" koppelt das Panel an CSS-Custom-Properties deines Themes', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control"><?php $seg('panel_theme', $o['panel_theme'], array('light' => __('Hell', 'wave-access'), 'dark' => __('Dunkel', 'wave-access'), 'custom' => __('Eigene Variablen', 'wave-access'))); ?></div>
					</div>
					<div class="wave-row wave-theme-vars" <?php if ('custom' !== $o['panel_theme']) echo 'style="display:none"'; ?>>
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('CSS-Variablen', 'wave-access'); ?></div>
							<div class="wave-row-desc"><?php esc_html_e('Trage die Variablennamen ein, die dein Theme definiert (z. B. --site-bg / --site-text). Das Panel übernimmt Hintergrund und Textfarbe daraus und leitet alle Sekundärfarben automatisch ab. Wechselt deine Website in den Dark-Mode, zieht das Widget ohne weitere Konfiguration mit.', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control" style="display:flex;flex-direction:column;gap:6px">
							<input type="text" class="wave-field" style="width:170px" name="wave_options[panel_bg_var]" value="<?php echo esc_attr($o['panel_bg_var']); ?>" placeholder="--site-bg">
							<input type="text" class="wave-field" style="width:170px" name="wave_options[panel_text_var]" value="<?php echo esc_attr($o['panel_text_var']); ?>" placeholder="--site-text">
						</div>
					</div>
					<div class="wave-row">
						<div class="wave-row-main"><div>
							<div class="wave-row-label"><?php esc_html_e('„powered by Wave Tools" anzeigen', 'wave-access'); ?>
								<?php if ( ! $is_pro ) : ?><span class="wave-pill wave-pill-pro"><?php echo wave_icon('sparkles', 10); ?>Pro</span><?php endif; ?>
							</div>
							<div class="wave-row-desc"><?php esc_html_e('Kleiner Link im Panel-Fuß. Abschaltbar ab Pro (White-Label ab Agency).', 'wave-access'); ?></div>
						</div></div>
						<div class="wave-row-control">
							<label class="wave-switch">
								<input type="checkbox" name="wave_options[show_branding]" value="1" <?php checked( ! empty($o['show_branding']) ); ?> <?php disabled( ! $is_pro ); ?> />
								<span class="wave-slider"></span>
							</label>
						</div>
					</div>
				</div>
				<div class="wave-actions">
					<button type="submit" class="wave-btn wave-btn-primary"><?php echo wave_icon('circle-check', 16); ?> <?php esc_html_e('Änderungen speichern', 'wave-access'); ?></button>
				</div>
			</div>
		</form>

		<div class="wave-card">
			<div class="wave-card-head">
				<span class="wave-card-ic"><?php echo wave_icon('list-check', 20); ?></span>
				<div>
					<h2 class="wave-card-title"><?php esc_html_e('Panel ohne schwebenden Button einbinden', 'wave-access'); ?></h2>
					<p class="wave-card-desc"><?php esc_html_e('Vier Wege, das Eingabehilfen-Panel an beliebiger Stelle zu platzieren:', 'wave-access'); ?></p>
				</div>
			</div>
			<div class="wave-rows">
				<div class="wave-row"><div class="wave-row-main"><div>
					<div class="wave-row-label"><?php esc_html_e('Gutenberg-Block', 'wave-access'); ?></div>
					<div class="wave-row-desc"><?php esc_html_e('Im Editor nach „Eingabehilfen-Panel" suchen (Kategorie Widgets) – ideal für Footer, Popups oder eigene Seiten.', 'wave-access'); ?></div>
				</div></div></div>
				<div class="wave-row"><div class="wave-row-main"><div>
					<div class="wave-row-label"><?php esc_html_e('Shortcode', 'wave-access'); ?></div>
					<div class="wave-row-desc"><code>[wave_access]</code> — <?php esc_html_e('optional mit', 'wave-access'); ?> <code>title="…" show_title="0/1" show_reset="0/1"</code></div>
				</div></div></div>
				<div class="wave-row"><div class="wave-row-main"><div>
					<div class="wave-row-label">Elementor</div>
					<div class="wave-row-desc"><?php esc_html_e('Widget „Wave Access – Eingabehilfen" per Drag & Drop (erscheint automatisch, wenn Elementor aktiv ist).', 'wave-access'); ?></div>
				</div></div></div>
				<div class="wave-row"><div class="wave-row-main"><div>
					<div class="wave-row-label">WPBakery</div>
					<div class="wave-row-desc"><?php esc_html_e('Element „Wave Access – Eingabehilfen" im Element-Katalog (erscheint automatisch, wenn WPBakery aktiv ist).', 'wave-access'); ?></div>
				</div></div></div>
			</div>
		</div>

		<script>
		// Picker↔Text-Sync (Akzentfarbe)
		document.querySelectorAll('[data-wave-sync]').forEach(function(picker){
			var text = document.getElementById('wave-color-' + picker.dataset.waveSync);
			picker.addEventListener('input', function(){ text.value = picker.value; });
			text.addEventListener('input', function(){
				if (/^#[0-9a-fA-F]{6}$/.test(text.value.trim())) { picker.value = text.value.trim(); }
			});
		});
		// Theme-Variablen-Zeile ein-/ausblenden
		document.querySelectorAll('input[name="wave_options[panel_theme]"]').forEach(function(r){
			r.addEventListener('change', function(){
				document.querySelector('.wave-theme-vars').style.display = ('custom' === this.value) ? '' : 'none';
			});
		});
		// Segment-Optik
		document.querySelectorAll('.wave-seg input, .wave-iconpick input').forEach(function(r){
			r.addEventListener('change', function(){
				this.closest('.wave-seg, .wave-iconpick').querySelectorAll('label').forEach(function(l){ l.classList.remove('is-on'); });
				this.closest('label').classList.add('is-on');
			});
		});
		// Mediathek-Auswahl fürs eigene Icon
		document.getElementById('wave-icon-media').addEventListener('click', function(e){
			e.preventDefault();
			var frame = wp.media({ title: '<?php echo esc_js(__('Widget-Icon wählen', 'wave-access')); ?>', library: { type: 'image' }, multiple: false });
			frame.on('select', function(){
				var att = frame.state().get('selection').first().toJSON();
				document.getElementById('wave-icon-custom-url').value = att.url;
				var custom = document.querySelector('.wave-iconpick-custom');
				custom.innerHTML = '<input type="radio" name="wave_options[widget_icon]" value="custom" checked><img src="' + att.url + '" alt="">';
				document.querySelectorAll('.wave-iconpick label').forEach(function(l){ l.classList.remove('is-on'); });
				custom.classList.add('is-on');
			});
			frame.open();
		});
		</script>
		<?php
	}

	/**
	 * Prüfbericht-Seite (Inhalt des Reiters „Prüfbericht")
	 */
	public function report_page() {
		// Unter-Tab-Navigation des Prüfberichts
		$active_tab = isset($_GET['tab']) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : 'overview';

		$issues = $this->run_accessibility_check();
		$images_without_alt = $this->get_images_without_alt_details();
		$is_pro = Wave_License::is_pro();

		// Free-Version: Detailliste auf 50 Bilder begrenzt (Pro: unbegrenzt)
		$free_limit    = 50;
		$total_missing = count( $images_without_alt );
		if ( ! $is_pro && $total_missing > $free_limit ) {
			$images_without_alt = array_slice( $images_without_alt, 0, $free_limit );
		}
		?>
			<h2><?php echo esc_html__('Barrierefreiheits-Prüfbericht', 'wave-access'); ?></h2>

			<!-- Unter-Tab-Navigation -->
			<nav class="nav-tab-wrapper">
				<a href="?page=wave-access&maintab=report&tab=overview" class="nav-tab <?php echo $active_tab === 'overview' ? 'nav-tab-active' : ''; ?>">
					<?php esc_html_e('Übersicht', 'wave-access'); ?>
				</a>
				<a href="?page=wave-access&maintab=report&tab=images" class="nav-tab <?php echo $active_tab === 'images' ? 'nav-tab-active' : ''; ?>">
					<?php esc_html_e('Bilder-Analyse', 'wave-access'); ?>
				</a>
				<a href="?page=wave-access&maintab=report&tab=checklist" class="nav-tab <?php echo $active_tab === 'checklist' ? 'nav-tab-active' : ''; ?>">
					<?php esc_html_e('BFSG-Checkliste', 'wave-access'); ?>
				</a>
			</nav>
			
			<?php if ($active_tab === 'overview'): ?>
				<!-- Übersichts-Tab -->
				<div class="wave-note">
					<p><?php esc_html_e('Dieser Bericht zeigt potenzielle Barrierefreiheitsprobleme auf Ihrer Website.', 'wave-access'); ?></p>
				</div>

				<div class="wave-actions" style="margin:16px 0">
					<?php if ( $is_pro ) : ?>
						<a class="wave-btn wave-btn-primary" target="_blank"
						   href="<?php echo esc_url( wp_nonce_url( admin_url('admin-post.php?action=wave_report_pdf'), 'wave_report_pdf' ) ); ?>">
							<?php echo wave_icon('file-lines', 15); ?> <?php esc_html_e('PDF-Prüfbericht erstellen', 'wave-access'); ?>
						</a>
					<?php else : ?>
						<span class="wave-btn is-locked"><?php echo wave_icon('file-lines', 15); ?> <?php esc_html_e('PDF-Prüfbericht erstellen', 'wave-access'); ?>
							<span class="wave-pill wave-pill-pro"><?php echo wave_icon('sparkles', 10); ?>Pro</span></span>
						<a class="wave-btn" href="https://wavetools.io/#pricing" target="_blank" rel="noopener"><?php esc_html_e('Mit Pro freischalten', 'wave-access'); ?></a>
					<?php endif; ?>
				</div>
				
				<!-- Statistik-Karten -->
				<div class="info-cards">
					<div class="info-card">
						<h3><span class="dashicons dashicons-format-image"></span> <?php esc_html_e('Bilder', 'wave-access'); ?></h3>
						<div class="number"><?php echo count($images_without_alt); ?></div>
						<div class="description"><?php esc_html_e('Bilder ohne Alt-Text', 'wave-access'); ?></div>
					</div>
					
					<div class="info-card">
						<h3><span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Checkliste', 'wave-access'); ?></h3>
						<div class="number">
							<?php 
							$checklist_progress = $this->get_checklist_progress();
							echo $checklist_progress . '%';
							?>
						</div>
						<div class="description"><?php esc_html_e('Fortschritt der BFSG-Checkliste', 'wave-access'); ?></div>
					</div>
					
					<div class="info-card">
						<h3><span class="dashicons dashicons-awards"></span> <?php esc_html_e('Status', 'wave-access'); ?></h3>
						<div class="number">
							<?php 
							$status = count($images_without_alt) === 0 ? __('Gut', 'wave-access') : __('Verbesserung nötig', 'wave-access');
							echo esc_html($status);
							?>
						</div>
						<div class="description"><?php esc_html_e('Gesamtstatus der Barrierefreiheit', 'wave-access'); ?></div>
					</div>
				</div>
				
				<?php if (!empty($issues)): ?>
					<h2><?php esc_html_e('Zusammenfassung der Probleme', 'wave-access'); ?></h2>
					<table class="wp-list-table widefat fixed striped">
						<thead>
							<tr>
								<th><?php esc_html_e('Problem', 'wave-access'); ?></th>
								<th><?php esc_html_e('Schweregrad', 'wave-access'); ?></th>
								<th><?php esc_html_e('Betroffene Seiten', 'wave-access'); ?></th>
								<th><?php esc_html_e('Empfehlung', 'wave-access'); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($issues as $issue): ?>
								<tr>
									<td><?php echo esc_html($issue['problem']); ?></td>
									<td>
										<span class="badge badge-<?php echo esc_attr($issue['severity']); ?>">
											<?php echo esc_html($issue['severity']); ?>
										</span>
									</td>
									<td><?php echo esc_html($issue['pages']); ?></td>
									<td><?php echo esc_html($issue['recommendation']); ?></td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
				<?php else: ?>
					<div class="notice notice-success">
						<p><?php esc_html_e('Keine automatisch erkennbaren Probleme gefunden. Prüfen Sie die manuelle Checkliste für weitere Optimierungen.', 'wave-access'); ?></p>
					</div>
				<?php endif; ?>
				
			<?php elseif ($active_tab === 'images'): ?>
				<!-- Bilder-Tab -->
				<?php if (!empty($images_without_alt)): ?>
					<h2><?php esc_html_e('Bilder ohne Alt-Text - Detaillierte Liste', 'wave-access'); ?></h2>
					<div class="notice notice-warning">
						<p><?php esc_html_e('Alt-Texte sind essentiell für Screenreader-Nutzer. Bitte fügen Sie beschreibende Alt-Texte hinzu.', 'wave-access'); ?></p>
					</div>
					
					<table class="wp-list-table widefat fixed striped">
						<thead>
							<tr>
								<th style="width: 100px;"><?php esc_html_e('Vorschau', 'wave-access'); ?></th>
								<th><?php esc_html_e('Dateiname', 'wave-access'); ?></th>
								<th><?php esc_html_e('Verwendet in', 'wave-access'); ?></th>
								<th><?php esc_html_e('Hochgeladen', 'wave-access'); ?></th>
								<th><?php esc_html_e('Aktionen', 'wave-access'); ?></th>
							</tr>
						</thead>
						<tbody>
							<?php foreach ($images_without_alt as $image): ?>
								<tr>
									<td>
										<?php 
										$thumbnail = wp_get_attachment_image_src($image->ID, 'thumbnail');
										if ($thumbnail): ?>
											<img src="<?php echo esc_url($thumbnail[0]); ?>" 
												 alt="<?php esc_attr_e('Vorschau', 'wave-access'); ?>" 
												 style="max-width: 80px; height: auto;">
										<?php else: ?>
											<span class="dashicons dashicons-format-image" style="font-size: 40px; color: #ccc;"></span>
										<?php endif; ?>
									</td>
									<td>
										<strong><?php echo esc_html(basename($image->guid)); ?></strong><br>
										<small><?php echo esc_html($image->post_title); ?></small>
									</td>
									<td>
										<?php 
										$used_in = $this->get_posts_using_image($image->ID);
										if (!empty($used_in)): 
											foreach (array_slice($used_in, 0, 3) as $post_id):
												$post = get_post($post_id);
												if ($post): ?>
													<a href="<?php echo get_permalink($post_id); ?>" target="_blank">
														<?php echo esc_html($post->post_title); ?>
													</a><br>
												<?php endif;
											endforeach;
											if (count($used_in) > 3): ?>
												<small><?php printf(__('... und %d weitere', 'wave-access'), count($used_in) - 3); ?></small>
											<?php endif;
										else: ?>
											<em><?php esc_html_e('Nicht verwendet', 'wave-access'); ?></em>
										<?php endif; ?>
									</td>
									<td><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($image->post_date))); ?></td>
									<td>
										<a href="<?php echo admin_url('post.php?post=' . $image->ID . '&action=edit'); ?>" 
										   class="button button-small" 
										   target="_blank">
											<?php esc_html_e('Alt-Text hinzufügen', 'wave-access'); ?>
										</a>
									</td>
								</tr>
							<?php endforeach; ?>
						</tbody>
					</table>
					
					<?php if ( ! $is_pro && $total_missing > $free_limit ) : ?>
						<div class="wave-note is-warn">
							<?php echo wave_icon('sparkles', 16); ?>
							<?php printf( esc_html__( 'Die Free-Version zeigt die ersten %1$d von %2$d Bildern. Pro prüft unbegrenzt und exportiert als CSV.', 'wave-access' ), $free_limit, $total_missing ); ?>
							<a href="https://wavetools.io/#pricing" target="_blank" rel="noopener"><?php esc_html_e('Jetzt upgraden', 'wave-access'); ?></a>
						</div>
					<?php endif; ?>
					<div class="wave-actions">
						<a href="<?php echo admin_url('upload.php'); ?>" class="wave-btn">
							<?php esc_html_e('Zur Mediathek', 'wave-access'); ?>
						</a>
						<?php if ( $is_pro ) : ?>
							<a href="<?php echo wp_nonce_url(admin_url('options-general.php?page=wave-access&maintab=report&export=csv'), 'export_report'); ?>" class="wave-btn">
								<?php echo wave_icon('list-check', 14); ?> <?php esc_html_e('Als CSV exportieren', 'wave-access'); ?>
							</a>
						<?php else : ?>
							<span class="wave-btn is-locked" title="<?php esc_attr_e('Pro-Funktion', 'wave-access'); ?>">
								<?php esc_html_e('Als CSV exportieren', 'wave-access'); ?> <span class="wave-pill wave-pill-pro"><?php echo wave_icon('sparkles', 10); ?>Pro</span>
							</span>
						<?php endif; ?>
					</div>
				<?php else: ?>
					<div class="notice notice-success">
						<h2><?php esc_html_e('Gratulation! 🎉', 'wave-access'); ?></h2>
						<p><?php esc_html_e('Alle Bilder haben Alt-Texte. Ihre Website ist in diesem Bereich barrierefrei!', 'wave-access'); ?></p>
					</div>
				<?php endif; ?>
				
			<?php elseif ($active_tab === 'checklist'): ?>
				<!-- Checkliste-Tab -->
				<?php $this->render_checklist(); ?>
			<?php endif; ?>
			
			<div style="margin-top: 30px; padding: 20px; background: #f0f0f0; border-radius: 5px;">
				<h3><?php esc_html_e('Tipp: Automatische Überwachung', 'wave-access'); ?></h3>
				<p><?php esc_html_e('Aktivieren Sie E-Mail-Benachrichtigungen in den Plugin-Einstellungen, um automatisch über neue Bilder ohne Alt-Text informiert zu werden.', 'wave-access'); ?></p>
				<p>
					<a href="<?php echo admin_url('options-general.php?page=wave-access'); ?>" class="button">
						<?php esc_html_e('Zu den Einstellungen', 'wave-access'); ?>
					</a>
				</p>
			</div>
		<?php
	}

	/**
	 * BFSG-Checkliste rendern
	 */
	private function render_checklist() {
		// Gespeicherte Checkliste laden
		$checklist_data = get_option('wave_checklist', array());
		
		// Checkliste-Struktur
		$checklist = $this->get_checklist_items();
		
		?>
		<div class="wave-checklist-container">
			<h2><?php esc_html_e('BFSG / WCAG 2.1 AA Checkliste', 'wave-access'); ?></h2>
			
			<div class="notice notice-info">
				<p><?php esc_html_e('Diese Checkliste hilft Ihnen dabei, alle wichtigen Barrierefreiheitsanforderungen gemäß BFSG und WCAG 2.1 Level AA zu erfüllen. Klicken Sie auf die Checkboxen, um Ihren Fortschritt zu speichern.', 'wave-access'); ?></p>
			</div>
			
			<!-- Fortschrittsbalken -->
			<div class="checklist-progress">
				<div class="progress-bar">
					<div class="progress-fill" style="width: <?php echo $this->get_checklist_progress(); ?>%;">
						<span><?php echo $this->get_checklist_progress(); ?>%</span>
					</div>
				</div>
				<p class="progress-text">
					<?php 
					$completed = count(array_filter($checklist_data));
					$total = $this->count_checklist_items();
					printf(__('%d von %d Kriterien erfüllt', 'wave-access'), $completed, $total);
					?>
				</p>
			</div>
			
			<!-- Checkliste -->
			<form id="wave-checklist-form">
				<?php wp_nonce_field('wave_checklist_nonce', 'wave_checklist_nonce'); ?>
				
				<?php foreach ($checklist as $category => $items): ?>
					<div class="checklist-category">
						<h3>
							<span class="dashicons <?php echo esc_attr($items['icon']); ?>"></span>
							<?php echo esc_html($items['title']); ?>
						</h3>
						<p class="category-description"><?php echo esc_html($items['description']); ?></p>
						
						<div class="checklist-items">
							<?php foreach ($items['items'] as $item_id => $item): ?>
								<div class="checklist-item">
									<label>
										<input type="checkbox" 
											   name="checklist[<?php echo esc_attr($item_id); ?>]" 
											   value="1"
											   <?php checked(isset($checklist_data[$item_id]) && $checklist_data[$item_id]); ?>
											   class="wave-checklist-checkbox"
											   data-item-id="<?php echo esc_attr($item_id); ?>">
										<span class="item-title"><?php echo esc_html($item['title']); ?></span>
									</label>
									<p class="item-description"><?php echo esc_html($item['description']); ?></p>
									<?php if (isset($item['help'])): ?>
										<p class="item-help">
											<span class="dashicons dashicons-info"></span>
											<?php echo esc_html($item['help']); ?>
										</p>
									<?php endif; ?>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
				<?php endforeach; ?>
			</form>
			
			<div class="checklist-actions">
				<button type="button" class="button button-primary" id="save-checklist">
					<?php esc_html_e('Fortschritt speichern', 'wave-access'); ?>
				</button>
				<button type="button" class="button" id="reset-checklist">
					<?php esc_html_e('Checkliste zurücksetzen', 'wave-access'); ?>
				</button>
				<button type="button" class="button" id="print-checklist">
					<?php esc_html_e('Checkliste drucken', 'wave-access'); ?>
				</button>
			</div>
		</div>
		
		
		<script>
		jQuery(document).ready(function($) {
			// Checkbox-Änderung erkennen
			$('.wave-checklist-checkbox').on('change', function() {
				var $item = $(this).closest('.checklist-item');
				if ($(this).is(':checked')) {
					$item.addClass('completed');
				} else {
					$item.removeClass('completed');
				}
				updateProgress();
			});
			
			// Initial completed items markieren
			$('.wave-checklist-checkbox:checked').each(function() {
				$(this).closest('.checklist-item').addClass('completed');
			});
			
			// Fortschritt aktualisieren
			function updateProgress() {
				var total = $('.wave-checklist-checkbox').length;
				var checked = $('.wave-checklist-checkbox:checked').length;
				var percentage = Math.round((checked / total) * 100);
				
				$('.progress-fill').css('width', percentage + '%');
				$('.progress-fill span').text(percentage + '%');
				$('.progress-text').text(checked + ' von ' + total + ' Kriterien erfüllt');
			}
			
			// Speichern
			$('#save-checklist').on('click', function() {
				var $button = $(this);
				$button.prop('disabled', true).text('Speichert...');
				
				var checklist = {};
				$('.wave-checklist-checkbox').each(function() {
					if ($(this).is(':checked')) {
						checklist[$(this).data('item-id')] = 1;
					}
				});
				
				$.post(ajaxurl, {
					action: 'wave_save_checklist',
					checklist: checklist,
					nonce: $('#wave_checklist_nonce').val()
				}, function(response) {
					if (response.success) {
						$button.text('✓ Gespeichert');
						setTimeout(function() {
							$button.prop('disabled', false).text('Fortschritt speichern');
						}, 2000);
					}
				});
			});
			
			// Zurücksetzen
			$('#reset-checklist').on('click', function() {
				if (confirm('Möchten Sie die komplette Checkliste zurücksetzen?')) {
					$('.wave-checklist-checkbox').prop('checked', false);
					$('.checklist-item').removeClass('completed');
					updateProgress();
				}
			});
			
			// Drucken
			$('#print-checklist').on('click', function() {
				window.print();
			});
		});
		</script>
		<?php
	}
	
	/**
	 * Checkliste-Items definieren
	 */
	private function get_checklist_items() {
		return array(
			'perceivable' => array(
				'title' => __('1. Wahrnehmbar', 'wave-access'),
				'description' => __('Informationen und Bestandteile der Benutzeroberfläche müssen für alle wahrnehmbar sein.', 'wave-access'),
				'icon' => 'dashicons-visibility',
				'items' => array(
					'alt_texts' => array(
						'title' => __('Alt-Texte für alle Bilder', 'wave-access'),
						'description' => __('Alle informativen Bilder haben beschreibende Alt-Texte.', 'wave-access'),
						'help' => __('Dekorative Bilder sollten leere Alt-Attribute (alt="") haben.', 'wave-access')
					),
					'captions' => array(
						'title' => __('Untertitel für Videos', 'wave-access'),
						'description' => __('Alle Videos haben Untertitel oder Transkripte.', 'wave-access')
					),
					'audio_description' => array(
						'title' => __('Audiodeskription', 'wave-access'),
						'description' => __('Videos mit wichtigen visuellen Informationen haben Audiodeskriptionen.', 'wave-access')
					),
					'color_contrast' => array(
						'title' => __('Ausreichender Farbkontrast', 'wave-access'),
						'description' => __('Text hat ein Kontrastverhältnis von mindestens 4.5:1 (3:1 für großen Text).', 'wave-access'),
						'help' => __('Nutzen Sie Tools wie den WebAIM Contrast Checker zur Überprüfung.', 'wave-access')
					),
					'no_color_only' => array(
						'title' => __('Nicht nur Farbe zur Informationsvermittlung', 'wave-access'),
						'description' => __('Informationen werden nicht ausschließlich durch Farbe vermittelt.', 'wave-access')
					),
					'text_resize' => array(
						'title' => __('Text bis 200% vergrößerbar', 'wave-access'),
						'description' => __('Text kann auf 200% vergrößert werden ohne Funktionsverlust.', 'wave-access')
					)
				)
			),
			'operable' => array(
				'title' => __('2. Bedienbar', 'wave-access'),
				'description' => __('Alle Funktionen müssen per Tastatur bedienbar sein.', 'wave-access'),
				'icon' => 'dashicons-universal-access',
				'items' => array(
					'keyboard_accessible' => array(
						'title' => __('Vollständige Tastaturbedienbarkeit', 'wave-access'),
						'description' => __('Alle interaktiven Elemente sind per Tastatur erreichbar.', 'wave-access')
					),
					'no_keyboard_trap' => array(
						'title' => __('Keine Tastaturfallen', 'wave-access'),
						'description' => __('Nutzer können mit der Tastatur zu allen Elementen navigieren und diese wieder verlassen.', 'wave-access')
					),
					'skip_links' => array(
						'title' => __('Skip-Links vorhanden', 'wave-access'),
						'description' => __('Skip-Links ermöglichen das Überspringen von sich wiederholenden Inhalten.', 'wave-access')
					),
					'focus_visible' => array(
						'title' => __('Fokus-Indikator sichtbar', 'wave-access'),
						'description' => __('Der Tastaturfokus ist immer deutlich sichtbar.', 'wave-access')
					),
					'timing_adjustable' => array(
						'title' => __('Zeitlimits anpassbar', 'wave-access'),
						'description' => __('Zeitlimits können verlängert oder deaktiviert werden.', 'wave-access')
					),
					'no_seizures' => array(
						'title' => __('Keine Inhalte die Anfälle auslösen', 'wave-access'),
						'description' => __('Keine Inhalte blinken mehr als 3 mal pro Sekunde.', 'wave-access')
					)
				)
			),
			'understandable' => array(
				'title' => __('3. Verständlich', 'wave-access'),
				'description' => __('Informationen und Bedienung müssen verständlich sein.', 'wave-access'),
				'icon' => 'dashicons-book',
				'items' => array(
					'language_defined' => array(
						'title' => __('Sprache der Seite definiert', 'wave-access'),
						'description' => __('Die Hauptsprache der Seite ist im HTML-Tag definiert.', 'wave-access'),
						'help' => __('Verwenden Sie das lang-Attribut im html-Tag.', 'wave-access')
					),
					'page_titled' => array(
						'title' => __('Aussagekräftige Seitentitel', 'wave-access'),
						'description' => __('Jede Seite hat einen eindeutigen und beschreibenden Titel.', 'wave-access')
					),
					'headings_structure' => array(
						'title' => __('Logische Überschriften-Hierarchie', 'wave-access'),
						'description' => __('Überschriften folgen einer logischen Hierarchie (h1-h6).', 'wave-access')
					),
					'labels_instructions' => array(
						'title' => __('Labels und Anleitungen', 'wave-access'),
						'description' => __('Alle Formularfelder haben beschreibende Labels oder Anleitungen.', 'wave-access')
					),
					'error_identification' => array(
						'title' => __('Fehler-Identifikation', 'wave-access'),
						'description' => __('Eingabefehler werden automatisch erkannt und beschrieben.', 'wave-access')
					),
					'consistent_navigation' => array(
						'title' => __('Konsistente Navigation', 'wave-access'),
						'description' => __('Navigation ist auf allen Seiten konsistent.', 'wave-access')
					)
				)
			),
			'robust' => array(
				'title' => __('4. Robust', 'wave-access'),
				'description' => __('Inhalte müssen robust genug sein für verschiedene Assistive Technologien.', 'wave-access'),
				'icon' => 'dashicons-admin-tools',
				'items' => array(
					'valid_html' => array(
						'title' => __('Valides HTML', 'wave-access'),
						'description' => __('HTML-Code ist valide und wohlgeformt.', 'wave-access'),
						'help' => __('Nutzen Sie den W3C Validator zur Überprüfung.', 'wave-access')
					),
					'aria_correct' => array(
						'title' => __('ARIA korrekt verwendet', 'wave-access'),
						'description' => __('ARIA-Attribute werden korrekt und nur wenn nötig verwendet.', 'wave-access')
					),
					'name_role_value' => array(
						'title' => __('Name, Rolle, Wert', 'wave-access'),
						'description' => __('Alle UI-Komponenten haben Name, Rolle und Wert programmatisch bestimmbar.', 'wave-access')
					),
					'status_messages' => array(
						'title' => __('Status-Nachrichten', 'wave-access'),
						'description' => __('Statusmeldungen werden Screenreadern mitgeteilt ohne Fokus zu erhalten.', 'wave-access')
					)
				)
			),
			'additional' => array(
				'title' => __('5. Zusätzliche BFSG-Anforderungen', 'wave-access'),
				'description' => __('Spezifische Anforderungen gemäß BFSG für öffentliche Stellen.', 'wave-access'),
				'icon' => 'dashicons-clipboard',
				'items' => array(
					'accessibility_statement' => array(
						'title' => __('Barrierefreiheitserklärung', 'wave-access'),
						'description' => __('Eine Barrierefreiheitserklärung ist vorhanden und aktuell.', 'wave-access'),
						'help' => __('Pflicht für öffentliche Stellen gemäß BFSG.', 'wave-access')
					),
					'feedback_mechanism' => array(
						'title' => __('Feedback-Mechanismus', 'wave-access'),
						'description' => __('Ein Feedback-Mechanismus für Barrierefreiheitsprobleme ist vorhanden.', 'wave-access')
					),
					'mobile_accessible' => array(
						'title' => __('Mobile Barrierefreiheit', 'wave-access'),
						'description' => __('Die Website ist auch auf mobilen Geräten barrierefrei.', 'wave-access')
					),
					'pdf_accessible' => array(
						'title' => __('Barrierefreie PDFs', 'wave-access'),
						'description' => __('Alle PDF-Dokumente sind barrierefrei.', 'wave-access'),
						'help' => __('PDFs sollten getaggt und durchsuchbar sein.', 'wave-access')
					),
					'contact_accessible' => array(
						'title' => __('Barrierefreie Kontaktmöglichkeiten', 'wave-access'),
						'description' => __('Mindestens zwei barrierefreie Kontaktmöglichkeiten vorhanden.', 'wave-access')
					)
				)
			)
		);
	}
	
	/**
	 * Checkliste-Items zählen
	 */
	private function count_checklist_items() {
		$count = 0;
		$checklist = $this->get_checklist_items();
		foreach ($checklist as $category) {
			$count += count($category['items']);
		}
		return $count;
	}
	
	/**
	 * Checkliste-Fortschritt berechnen
	 */
	private function get_checklist_progress() {
		$checklist_data = get_option('wave_checklist', array());
		
		// Vereinfachte Berechnung für Dashboard
		if (!method_exists($this, 'get_checklist_items')) {
			// Fallback: Wenn keine Checklist items definiert sind, verwende feste Anzahl
			$total = 31; // Anzahl der Standard-Checklist-Items
		} else {
			$total = $this->count_checklist_items();
		}
		
		$completed = count(array_filter($checklist_data));

		if ($total === 0) return 0;
		return round(($completed / $total) * 100);
	}

	/**
	 * Gesammelte Berichtsdaten (für PDF-Bericht und Dashboard).
	 */
	public function get_report_data() {
		$checklist_data = get_option('wave_checklist', array());
		$rows = array();
		foreach ( $this->get_checklist_items() as $category ) {
			foreach ( $category['items'] as $item_id => $item ) {
				$rows[] = array(
					'title'    => $item['title'],
					'category' => $category['title'],
					'done'     => ! empty( $checklist_data[ $item_id ] ),
				);
			}
		}
		return array(
			'images_missing'     => $this->check_images_without_alt(),
			'images'             => $this->get_images_without_alt_details(),
			'checklist'          => $rows,
			'checklist_progress' => $this->get_checklist_progress(),
		);
	}
	
	/**
	 * Barrierefreiheitsprüfung durchführen
	 */
	private function run_accessibility_check() {
		$issues = array();
		
		// Prüfung auf fehlende Alt-Texte
		$images_without_alt = $this->check_images_without_alt();
		if ($images_without_alt > 0) {
			$issues[] = array(
				'problem' => sprintf(__('%d Bilder ohne Alt-Text gefunden', 'wave-access'), $images_without_alt),
				'severity' => 'high',
				'pages' => __('Verschiedene', 'wave-access'),
				'recommendation' => __('Fügen Sie beschreibende Alt-Texte zu allen informativen Bildern hinzu', 'wave-access')
			);
		}
		
		return $issues;
	}
	
	/**
	 * Bilder ohne Alt-Text zählen
	 */
	private function check_images_without_alt() {
		global $wpdb;
		
		$count = $wpdb->get_var("
			SELECT COUNT(*) 
			FROM {$wpdb->posts} p
			LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_wp_attachment_image_alt'
			WHERE p.post_type = 'attachment'
			AND p.post_mime_type LIKE 'image/%'
			AND (pm.meta_value IS NULL OR pm.meta_value = '')
		");
		
		return intval($count);
	}
	
	/**
	 * Detaillierte Liste der Bilder ohne Alt-Text
	 */
	private function get_images_without_alt_details() {
		global $wpdb;
		
		$images = $wpdb->get_results("
			SELECT p.* 
			FROM {$wpdb->posts} p
			LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_wp_attachment_image_alt'
			WHERE p.post_type = 'attachment'
			AND p.post_mime_type LIKE 'image/%'
			AND (pm.meta_value IS NULL OR pm.meta_value = '')
			ORDER BY p.post_date DESC
			LIMIT 100
		");
		
		return $images;
	}
	
	/**
	 * Posts finden, die ein bestimmtes Bild verwenden
	 */
	private function get_posts_using_image($attachment_id) {
		global $wpdb;
		
		$attachment_url = wp_get_attachment_url($attachment_id);
		if (!$attachment_url) {
			return array();
		}
		
		// Suche in Post-Content
		$posts = $wpdb->get_col($wpdb->prepare("
			SELECT DISTINCT post_id 
			FROM {$wpdb->posts} 
			WHERE post_content LIKE %s
			AND post_status = 'publish'
			AND post_type IN ('post', 'page')
			LIMIT 10
		", '%' . $wpdb->esc_like($attachment_url) . '%'));
		
		// Suche auch in Featured Images
		$featured = $wpdb->get_col($wpdb->prepare("
			SELECT post_id 
			FROM {$wpdb->postmeta}
			WHERE meta_key = '_thumbnail_id'
			AND meta_value = %d
		", $attachment_id));
		
		return array_unique(array_merge($posts, $featured));
	}
	
	/**
	 * Admin-Scripts einbinden
	 */
	public function enqueue_admin_scripts($hook) {
		// Nur auf unserer Einstellungsseite (Hook: settings_page_wave-access)
		if (strpos($hook, 'wave-access') === false) {
			return;
		}
		
		wp_enqueue_style('wave-admin', WAVE_PLUGIN_URL . 'assets/admin.css', array(), WAVE_VERSION);
		wp_enqueue_media(); // Mediathek-Auswahl für das Widget-Icon
	}
	
	/**
	 * Frontend-Scripts einbinden
	 */
	public function enqueue_frontend_scripts() {
		wp_enqueue_style('wave-frontend', WAVE_PLUGIN_URL . 'assets/frontend.css', array(), WAVE_VERSION);
		wp_enqueue_script('wave-frontend', WAVE_PLUGIN_URL . 'assets/frontend.js', array('jquery'), WAVE_VERSION, true);
		if ( class_exists( 'Wave_TTS' ) && Wave_TTS::available() ) {
			wp_enqueue_script( 'wave-tts', WAVE_PLUGIN_URL . 'assets/wave-tts.js', array(), WAVE_VERSION, true );
			wp_localize_script( 'wave-tts', 'waveTTS', array( 'endpoint' => esc_url_raw( rest_url( 'wave/v1/tts' ) ) ) );
		}
		if ( class_exists( 'Wave_Easy_Language' ) && Wave_Easy_Language::available() && is_singular() ) {
			wp_enqueue_script( 'wave-easy-lang', WAVE_PLUGIN_URL . 'assets/wave-easy-lang.js', array(), WAVE_VERSION, true );
			wp_localize_script( 'wave-easy-lang', 'waveEasyLang', array(
				'endpoint' => esc_url_raw( rest_url( 'wave/v1/easy-language' ) ),
				'postId'   => (int) get_queried_object_id(),
				'i18n'     => array(
					'note'  => __( 'Leichte Sprache – vereinfachte Fassung dieser Seite.', 'wave-access' ),
					'on'    => __( 'Leichte Sprache aktiviert', 'wave-access' ),
					'off'   => __( 'Leichte Sprache deaktiviert', 'wave-access' ),
					'error' => __( 'Leichte Sprache ist gerade nicht verfügbar.', 'wave-access' ),
				),
			) );
		}
		
		// Lokalisierung für AJAX, Optionen und i18n-Strings
		$localize_data = array(
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce'    => wp_create_nonce('wave_nonce'),
			'options'  => array(
				'enable_tab_order'     => isset($this->options['enable_tab_order']) ? $this->options['enable_tab_order'] : true,
				'enable_tab_visualizer' => (isset($this->options['enable_tab_visualizer']) && current_user_can('manage_options')) ? $this->options['enable_tab_visualizer'] : false,
				'is_admin'             => current_user_can('manage_options')
			),
			// Übersetzbare Strings fürs Frontend-JS
			'i18n' => array(
				'speech_unavailable'   => __('Sprach-Synthese in diesem Browser nicht verfügbar', 'wave-access'),
				'sr_activated_speak'   => __('Bildschirmleser aktiviert. Markieren Sie Text mit dem Cursor oder klicken Sie auf einen Absatz.', 'wave-access'),
				'sr_activated_announce' => __('Bildschirmleser aktiv. Markieren Sie Text mit dem Cursor oder klicken Sie auf einen Absatz.', 'wave-access'),
				'all_reset'            => __('Alle Eingabehilfen zurückgesetzt', 'wave-access'),
				'feature_activated'    => __('%s aktiviert', 'wave-access'),
				'feature_deactivated'  => __('%s deaktiviert', 'wave-access'),
				'feature_labels'       => array(
					'invert-colors'      => __('Farben umkehren', 'wave-access'),
					'monochrome'         => __('Monochrom', 'wave-access'),
					'dark-contrast'      => __('Dunkler Kontrast', 'wave-access'),
					'light-contrast'     => __('Heller Kontrast', 'wave-access'),
					'low-saturation'     => __('Niedrige Sättigung', 'wave-access'),
					'high-saturation'    => __('Hohe Sättigung', 'wave-access'),
					'highlight-links'    => __('Links hervorheben', 'wave-access'),
					'highlight-headings' => __('Überschriften hervorheben', 'wave-access'),
					'screen-reader'      => __('Bildschirmleser', 'wave-access'),
					'reading-mode'       => __('Lesemodus', 'wave-access')
				)
			)
		);

		wp_localize_script('wave-frontend', 'wave_ajax', $localize_data);

		// Widget-2.0-Variablen: Akzent, Größe, Abstand, Rundung, Panel-Theme
		$accent = $this->css_color('widget_accent_color', '#4a4a4a');
		$sizes  = array('s' => 48, 'm' => 56, 'l' => 64);
		$size   = isset($sizes[$this->options['widget_size']]) ? $sizes[$this->options['widget_size']] : 56;
		$offset = max(8, min(80, (int) $this->options['widget_offset']));
		$radius = max(4, min(40, (int) $this->options['widget_radius']));
		switch ($this->options['panel_theme']) {
			case 'dark':
				$panel_bg = '#1d1d1f'; $panel_tx = '#fafafa';
				break;
			case 'custom':
				$bgv = preg_match('/^--[a-zA-Z0-9_-]+$/', $this->options['panel_bg_var']) ? $this->options['panel_bg_var'] : '';
				$txv = preg_match('/^--[a-zA-Z0-9_-]+$/', $this->options['panel_text_var']) ? $this->options['panel_text_var'] : '';
				$panel_bg = $bgv ? "var({$bgv}, #ffffff)" : '#ffffff';
				$panel_tx = $txv ? "var({$txv}, #1d1d1f)" : '#1d1d1f';
				break;
			default:
				$panel_bg = '#ffffff'; $panel_tx = '#1d1d1f';
		}
		$accent_css = ":root { --wave-accent: {$accent}; --wave-size: {$size}px; --wave-offset: {$offset}px; --wave-radius: {$radius}px; --wave-panel-bg: {$panel_bg}; --wave-panel-text: {$panel_tx}; }";
		wp_add_inline_style('wave-frontend', $accent_css);

		// Inline CSS für Fokus-Indikator
		if (isset($this->options['enable_focus_indicator']) && $this->options['enable_focus_indicator']) {
			$focus_color = $this->css_color('custom_focus_color', '#0073aa');
			$focus_css = "
				*:focus {
					outline: 3px solid {$focus_color} !important;
					outline-offset: 2px !important;
				}
			";
			wp_add_inline_style('wave-frontend', $focus_css);
		}
		
		// Tab-Optimierung Klasse zum Body hinzufügen
		if (isset($this->options['enable_tab_order']) && $this->options['enable_tab_order']) {
			add_filter('body_class', function($classes) {
				$classes[] = 'wave-tab-optimized';
				return $classes;
			});
		}
		
		// Tab-Visualisierer aktivieren
		if (isset($this->options['enable_tab_visualizer']) && $this->options['enable_tab_visualizer'] && current_user_can('manage_options')) {
			add_action('wp_footer', array($this, 'add_tab_visualizer_data'));
		}
	}
	
	/**
	 * Skip-Links hinzufügen
	 */
	public function add_skip_links() {
		if (!$this->options['enable_skip_links']) {
			return;
		}
		?>
		<nav class="wave-skip-links screen-reader-text" aria-label="<?php esc_attr_e('Skip Links', 'wave-access'); ?>">
			<a href="#main" class="skip-link"><?php esc_html_e('Zum Hauptinhalt springen', 'wave-access'); ?></a>
			<a href="#nav" class="skip-link"><?php esc_html_e('Zur Navigation springen', 'wave-access'); ?></a>
			<a href="#footer" class="skip-link"><?php esc_html_e('Zum Footer springen', 'wave-access'); ?></a>
		</nav>
		<?php
	}
	
	/**
	 * Barrierefreiheits-Toolbar hinzufügen
	 *
	 * Neues erweitertes Widget gemäß BFSG-Standard:
	 * - 10 Funktions-Buttons (Farben umkehren, Monochrom, Dunkler/Heller Kontrast,
	 *   Niedrige/Hohe Sättigung, Links/Überschriften hervorheben, Bildschirmleser, Lesemodus)
	 * - 4 Slider (Inhaltsskalierung, Schriftgröße, Zeilenhöhe, Buchstabenabstand)
	 */
	public function add_accessibility_toolbar() {
		// Schwebendes Widget kann in den Einstellungen global deaktiviert werden
		if ( isset( $this->options['enable_floating_widget'] ) && ! $this->options['enable_floating_widget'] ) {
			return;
		}
		?>
		<div id="wave-toolbar" class="wave-toolbar wave-pos-<?php echo esc_attr( in_array($this->options['widget_position'], array('br','bl','tr','tl'), true) ? $this->options['widget_position'] : 'br' ); ?>" role="toolbar" aria-label="<?php esc_attr_e('Barrierefreiheits-Werkzeuge', 'wave-access'); ?>">
			<!-- Floating Action Button (Person/Accessibility Icon) -->
			<button class="wave-toggle" aria-label="<?php esc_attr_e('Eingabehilfen öffnen', 'wave-access'); ?>" aria-expanded="false">
				<?php echo $this->fab_icon_markup(); ?>
			</button>

			<!-- Panel-Inhalt -->
			<div class="wave-toolbar-content" id="wave-panel" role="dialog" aria-modal="false" aria-label="<?php esc_attr_e('Eingabehilfen', 'wave-access'); ?>" hidden>

				<?php $this->render_panel_inner( array( 'show_header' => true, 'show_title' => true, 'show_reset' => true, 'show_close' => true, 'title' => __( 'Eingabehilfen öffnen', 'wave-access' ) ) ); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Gemeinsamer Panel-Inhalt (Header + Funktions-Buttons + Slider).
	 * Wird vom schwebenden Widget UND vom Gutenberg-Block genutzt.
	 *
	 * @param array $args show_header, show_title, show_reset, show_close, title
	 */
	public function render_panel_inner( $args = array() ) {
		$args = wp_parse_args( $args, array(
			'show_header' => true,
			'show_title'  => true,
			'show_reset'  => true,
			'show_close'  => false,
			'title'       => __( 'Eingabehilfen', 'wave-access' ),
		) );
		?>
			<?php if ( $args['show_header'] ) : ?>
			<div class="wave-panel-header">
				<?php if ( $args['show_title'] ) : ?>
				<h2 class="wave-panel-title"><?php echo esc_html( $args['title'] ); ?></h2>
				<?php endif; ?>
				<div class="wave-panel-header-actions">
					<?php if ( $args['show_reset'] ) : ?>
					<button type="button" class="wave-reset-all" aria-label="<?php esc_attr_e('Alle Eingabehilfen zurücksetzen', 'wave-access'); ?>" title="<?php esc_attr_e('Zurücksetzen', 'wave-access'); ?>"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="20" height="20" fill="currentColor" aria-hidden="true">
								<path d="m480 256c0 123.5-100.4 223.9-223.9 223.9-69.41 0-133.9-31.3-176.7-86.05-5.438-6.938-4.203-17 2.75-22.44 6.984-5.531 17.03-4.25 22.47 2.75 36.68 46.94 91.88 73.84 151.38 73.84 105.9 0 192-86.13 192-192s-86.13-192-192-192c-68.9 0-131.5 36.7-165.85 96h85.85c8.8 0 16 7.2 16 16s-7.2 16-16 16h-128c-8.84 0-16-7.2-16-16v-128c0-8.84 7.16-16 16-16s16 7.16 16 16v93.56c40.4-67.69 112.6-109.45 192.1-109.45 123.5 0 223.9 100.39 223.9 223.89z"/>
							</svg></button>
					<?php endif; ?>
					<?php if ( $args['show_close'] ) : ?>
					<button type="button" class="wave-close" aria-label="<?php esc_attr_e('Eingabehilfen schließen', 'wave-access'); ?>"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
								<line x1="18" y1="6" x2="6" y2="18"/>
								<line x1="6" y1="6" x2="18" y2="18"/>
							</svg></button>
					<?php endif; ?>
				</div>
			</div>
			<?php endif; ?>

				<!-- Funktions-Buttons im 2-Spalten-Grid -->
				<div class="wave-feature-grid" role="group" aria-label="<?php esc_attr_e('Anzeige-Optionen', 'wave-access'); ?>">

					<!-- Farben umkehren -->
					<button type="button" class="wave-feature-btn" data-feature="invert-colors" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m18.38 2.31c-8.83 0-16 7.16-16 16s7.16 16 16 16 16-7.16 16-16-7.16-16-16-16zm0 30.5v-13.29h-6.84l2.69 2.69c.47.47.47 1.24 0 1.72-.23.23-.53.36-.86.36s-.63-.13-.86-.36l-4.77-4.77c-.11-.11-.2-.25-.26-.39-.12-.3-.12-.63 0-.93.06-.15.15-.28.26-.4l4.77-4.76c.46-.46 1.26-.46 1.72 0 .47.47.47 1.24 0 1.72l-2.69 2.69h6.84v-13.28c8 0 14.5 6.5 14.5 14.5s-6.5 14.5-14.5 14.5zm7.58-13.29h-7.57v-2.43h7.57c.67 0 1.21.54 1.21 1.21s-.54 1.21-1.21 1.21z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Farben umkehren', 'wave-access'); ?></span>
					</button>

					<!-- Monochrom -->
					<button type="button" class="wave-feature-btn" data-feature="monochrome" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m18.38 2.31c-8.83 0-16 7.16-16 16s7.16 16 16 16 16-7.16 16-16-7.16-16-16-16zm0 30.5v-29c8 0 14.5 6.5 14.5 14.5s-6.5 14.5-14.5 14.5z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Monochrom', 'wave-access'); ?></span>
					</button>

					<!-- Dunkler Kontrast -->
					<button type="button" class="wave-feature-btn" data-feature="dark-contrast" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m20.34 3.86c-7.98 0-14.45 6.47-14.45 14.45s6.47 14.45 14.45 14.45c3.88 0 7.41-1.54 10.01-4.03.41-.4.53-1.01.3-1.53s-.77-.84-1.34-.8c-.28.02-.55.03-.84.03-5.73 0-10.39-4.65-10.39-10.39 0-4.07 2.34-7.6 5.76-9.3.51-.25.81-.81.74-1.38s-.49-1.03-1.04-1.16c-1.03-.23-2.11-.36-3.2-.36z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Dunkler Kontrast', 'wave-access'); ?></span>
					</button>

					<!-- Heller Kontrast -->
					<button type="button" class="wave-feature-btn" data-feature="light-contrast" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m18 26.23c-4.54 0-8.23-3.69-8.23-8.23s3.69-8.23 8.23-8.23 8.23 3.69 8.23 8.23-3.69 8.23-8.23 8.23zm0-14.29c-3.34 0-6.06 2.72-6.06 6.06s2.72 6.06 6.06 6.06 6.06-2.72 6.06-6.06-2.72-6.06-6.06-6.06zm1-5.49v-4.95c0-.55-.45-1-1-1s-1 .45-1 1v4.95c0 .55.45 1 1 1s1-.45 1-1zm0 28.05v-4.95c0-.55-.45-1-1-1s-1 .45-1 1v4.95c0 .55.45 1 1 1s1-.45 1-1zm-11.55-16.5c0-.55-.45-1-1-1h-4.95c-.55 0-1 .45-1 1s.45 1 1 1h4.95c.55 0 1-.45 1-1zm28.05 0c0-.55-.45-1-1-1h-4.95c-.55 0-1 .45-1 1s.45 1 1 1h4.95c.55 0 1-.45 1-1zm-24.96-7.46c.39-.39.39-1.02 0-1.41l-3.5-3.5c-.39-.39-1.02-.39-1.41 0s-.39 1.02 0 1.41l3.5 3.5c.2.2.45.29.71.29s.51-.1.71-.29zm19.83 19.83c.39-.39.39-1.02 0-1.41l-3.5-3.5c-.39-.39-1.02-.39-1.41 0s-.39 1.02 0 1.41l3.5 3.5c.2.2.45.29.71.29s.51-.1.71-.29zm-23.33 0 3.5-3.5c.39-.39.39-1.02 0-1.41s-1.02-.39-1.41 0l-3.5 3.5c-.39.39-.39 1.02 0 1.41.2.2.45.29.71.29s.51-.1.71-.29zm19.84-19.83 3.5-3.5c.39-.39.39-1.02 0-1.41s-1.02-.39-1.41 0l-3.5 3.5c-.39.39-.39 1.02 0 1.41.2.2.45.29.71.29s.51-.1.71-.29z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Heller Kontrast', 'wave-access'); ?></span>
					</button>

					<!-- Niedrige Sättigung -->
					<button type="button" class="wave-feature-btn" data-feature="low-saturation" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m23.62 17.93c.23.23.36.53.36.86s-.13.63-.36.86l-4.76 4.76c-.11.11-.24.2-.39.26s-.31.09-.46.09-.32-.03-.46-.09c-.15-.06-.29-.15-.4-.27l-4.76-4.76c-.23-.23-.36-.53-.36-.86s.13-.63.36-.86c.47-.47 1.25-.47 1.72 0l2.69 2.69v-8.2c0-.67.54-1.21 1.21-1.21s1.21.54 1.21 1.21v8.2l2.69-2.69c.46-.46 1.26-.46 1.72 0zm6.44 10.56s-.08.08-.11.13c-.36.41-.74.8-1.15 1.16-.1.09-.2.19-.31.28-.2.17-.4.34-.6.5-.16.12-.32.24-.48.36-.29.21-.58.41-.88.6-.21.13-.42.26-.64.39-.17.1-.35.19-.52.29-.31.16-.62.31-.94.45-.15.06-.3.13-.44.19-.33.14-.67.26-1.02.37-.14.05-.28.09-.42.13-.43.13-.86.24-1.3.33-.04 0-.07.01-.11.02-.43.09-.88.15-1.32.2-.12.01-.25.03-.37.04-.48.04-.96.07-1.45.07s-.97-.03-1.45-.07c-.12-.01-.25-.02-.37-.04-.45-.05-.89-.11-1.32-.2-.04 0-.07-.01-.11-.02-.44-.09-.87-.21-1.3-.33-.14-.04-.28-.09-.42-.13-.34-.11-.68-.24-1.02-.37-.15-.06-.3-.12-.44-.19-.32-.14-.63-.29-.94-.45-.18-.09-.35-.19-.52-.29-.22-.12-.43-.25-.64-.39-.3-.19-.59-.39-.88-.6-.16-.12-.32-.23-.48-.36-.21-.16-.41-.33-.6-.5-.1-.09-.21-.19-.31-.28-.4-.37-.78-.76-1.15-1.16-.04-.04-.08-.08-.11-.13-.2-.23-.4-.48-.59-.72-.04-.05-.08-.11-.12-.16-.39-.51-.74-1.05-1.07-1.6-1.36-2.36-2.16-5.08-2.16-8 0-8.85 7.16-16.01 16-16.01s16 7.16 16 16c0 2.92-.79 5.64-2.16 8s0 0 0 0c-.32.56-.68 1.09-1.07 1.6-.04.05-.08.11-.12.16-.19.25-.39.49-.59.72zm-24.14-2.49h24.16c1.52-2.3 2.42-5.04 2.42-8 0-8-6.5-14.5-14.5-14.5s-14.5 6.5-14.5 14.5c0 2.96.89 5.7 2.42 8z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Niedrige Sättigung', 'wave-access'); ?></span>
					</button>

					<!-- Hohe Sättigung -->
					<button type="button" class="wave-feature-btn" data-feature="high-saturation" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m33.93 16.53c-.01-.15-.03-.29-.05-.44-.04-.35-.09-.7-.16-1.04-.03-.15-.05-.3-.09-.44-.09-.42-.2-.84-.32-1.25-.01-.04-.02-.09-.04-.13-.14-.44-.3-.87-.47-1.29-.06-.15-.13-.29-.19-.43-.13-.29-.27-.57-.41-.85-.08-.15-.15-.29-.23-.44-.18-.33-.38-.64-.58-.95-.05-.07-.09-.15-.14-.23-2.88-4.24-7.73-7.02-13.24-7.02s-10.36 2.78-13.24 7.02 0 0 0 0c-.05.07-.09.15-.14.23-.2.31-.4.63-.58.95-.08.14-.16.29-.23.44-.15.28-.28.56-.41.85-.06.14-.13.29-.19.43-.17.42-.34.85-.47 1.29-.01.04-.02.09-.04.13-.12.41-.23.83-.32 1.25-.03.15-.06.29-.09.44-.06.34-.12.69-.16 1.04-.02.15-.04.29-.05.44-.04.49-.07.98-.07 1.47 0 8.84 7.16 16 16 16s16-7.16 16-16c0-.5-.03-.99-.07-1.47zm-10.3 1.21c-.47.47-1.24.47-1.72 0l-2.69-2.69v8.2c0 .67-.54 1.21-1.21 1.21s-1.21-.54-1.21-1.21v-8.2l-2.69 2.69c-.47.47-1.24.47-1.72 0-.23-.23-.36-.53-.36-.86s.13-.63.36-.86l4.77-4.77c.11-.11.25-.2.4-.26.29-.12.63-.12.93 0 .15.06.28.15.4.27l4.76 4.76c.47.47.47 1.24 0 1.72zm-16.99-8.72c2.66-3.36 6.76-5.52 11.36-5.52s8.71 2.16 11.36 5.52z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Hohe Sättigung', 'wave-access'); ?></span>
					</button>

					<!-- Links hervorheben -->
					<button type="button" class="wave-feature-btn" data-feature="highlight-links" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m10.69 29.9c-4.49 0-8.14-3.65-8.14-8.14 0-2.14.87-4.24 2.38-5.76l3.95-3.95c1.51-1.51 3.61-2.38 5.76-2.38 4.49 0 8.14 3.66 8.14 8.17v.22c-.01.66-.56 1.18-1.23 1.18-.7-.02-1.24-.58-1.23-1.26v-.14c0-1.88-.95-3.66-2.49-4.72v-.07l-.34-.15c-.06-.03-.13-.07-.2-.11-.86-.45-1.76-.67-2.66-.67-1.52 0-2.95.59-4.02 1.67l-3.95 3.95c-1.06 1.06-1.67 2.52-1.67 4.02 0 3.14 2.55 5.69 5.69 5.69.87 0 1.72-.2 2.5-.58.65.61 1.36 1.15 2.12 1.6-1.36.93-2.97 1.44-4.62 1.44zm10.67-3.57c-4.49 0-8.14-3.65-8.14-8.15 0-.07 0-.15 0-.22.02-.69.56-1.21 1.23-1.21.37 0 .67.15.9.38.22.24.34.55.33.88v.16c0 3.14 2.55 5.69 5.69 5.69 1.52 0 2.95-.59 4.02-1.67l3.95-3.95c1.06-1.06 1.67-2.52 1.67-4.02 0-3.14-2.55-5.69-5.69-5.69h-.24l-.02.02c-.78.03-1.55.23-2.26.58-.65-.61-1.36-1.15-2.12-1.6 1.35-.93 2.96-1.44 4.62-1.44 4.49 0 8.14 3.65 8.14 8.15 0 2.14-.87 4.24-2.38 5.76l-3.95 3.95c-1.52 1.51-3.61 2.38-5.76 2.38z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Links hervorheben', 'wave-access'); ?></span>
					</button>

					<!-- Überschriften hervorheben -->
					<button type="button" class="wave-feature-btn" data-feature="highlight-headings" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m7.67 32.76c-2.06 0-3.74-1.68-3.74-3.74v-21.43c0-2.06 1.68-3.74 3.74-3.74h21.43c2.06 0 3.74 1.68 3.74 3.74v21.43c0 2.06-1.68 3.74-3.74 3.74zm0-26.79c-.89 0-1.62.73-1.62 1.62v21.43c0 .89.73 1.62 1.62 1.62h21.43c.89 0 1.62-.73 1.62-1.62v-21.43c0-.89-.73-1.62-1.62-1.62zm16.61 20.36c-.58 0-1.06-.47-1.06-1.06v-5.91h-9.67v5.91c0 .58-.47 1.06-1.06 1.06s-1.06-.47-1.06-1.06v-13.93c0-.58.47-1.06 1.06-1.06s1.06.47 1.06 1.06v5.91h9.67v-5.91c0-.58.47-1.06 1.06-1.06s1.06.47 1.06 1.06v13.93c0 .58-.47 1.06-1.06 1.06z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Überschriften hervorheben', 'wave-access'); ?></span>
					</button>

					<!-- Bildschirmleser -->
					<button type="button" class="wave-feature-btn" data-feature="screen-reader" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m4.99 21.48c-.55 0-1-.45-1-1v-4.95c0-.55.45-1 1-1s1 .45 1 1v4.95c0 .55-.45 1-1 1zm27.02-1v-4.95c0-.55-.45-1-1-1s-1 .45-1 1v4.95c0 .55.45 1 1 1s1-.45 1-1zm-20.82 6v-17.96c0-.55-.45-1-1-1s-1 .45-1 1v17.95c0 .55.45 1 1 1s1-.45 1-1zm10.41-1v-14.95c0-.55-.45-1-1-1s-1 .45-1 1v14.95c0 .55.45 1 1 1s1-.45 1-1zm-5.2 7v-28.96c0-.55-.45-1-1-1s-1 .45-1 1v28.95c0 .55.45 1 1 1s1-.45 1-1zm10.41-3v-22.96c0-.55-.45-1-1-1s-1 .45-1 1v22.95c0 .55.45 1 1 1s1-.45 1-1z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Bildschirmleser', 'wave-access'); ?></span>
					</button>

					<!-- Lesemodus -->
					<button type="button" class="wave-feature-btn" data-feature="reading-mode" aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="24" height="24" fill="currentColor"><path d="m5.52 7.88c0-.55.45-1 1-1h22.95c.55 0 1 .45 1 1s-.45 1-1 1h-22.95c-.55 0-1-.45-1-1zm1 6.06h22.95c.55 0 1-.45 1-1s-.45-1-1-1h-22.95c-.55 0-1 .45-1 1s.45 1 1 1zm0 5.06h22.95c.55 0 1-.45 1-1s-.45-1-1-1h-22.95c-.55 0-1 .45-1 1s.45 1 1 1zm0 5.06h22.95c.55 0 1-.45 1-1s-.45-1-1-1h-22.95c-.55 0-1 .45-1 1s.45 1 1 1zm0 5.06h9.95c.55 0 1-.45 1-1s-.45-1-1-1h-9.95c-.55 0-1 .45-1 1s.45 1 1 1z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Lesemodus', 'wave-access'); ?></span>
					</button>

					<?php if ( class_exists( 'Wave_Easy_Language' ) && Wave_Easy_Language::available() && is_singular() ) : ?>
					<!-- Leichte Sprache (Pro AI) -->
					<button type="button" class="wave-feature-btn" data-wave-easy-toggle aria-pressed="false">
						<span class="wave-feature-icon" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640" width="24" height="24" fill="currentColor"><path d="M320 96C326.4 96 332.2 99.8 334.7 105.8L506.6 512L544 512C552.8 512 560 519.2 560 528C560 536.8 552.8 544 544 544L432 544C423.2 544 416 536.8 416 528C416 519.2 423.2 512 432 512L471.9 512L431.3 416L208.8 416L168.2 512L208.1 512C216.9 512 224.1 519.2 224.1 528C224.1 536.8 216.9 544 208.1 544L96 544C87.2 544 80 536.8 80 528C80 519.2 87.2 512 96 512L133.4 512L305.3 105.8C307.8 99.9 313.6 96 320 96zM222.3 384L417.7 384L320 153.1L222.3 384z"/></svg>
						</span>
						<span class="wave-feature-label"><?php esc_html_e('Leichte Sprache', 'wave-access'); ?></span>
					</button>
					<?php endif; ?>

				</div>

				<!-- Slider-Bereich -->
				<div class="wave-sliders" role="group" aria-label="<?php esc_attr_e('Anpassungen', 'wave-access'); ?>">

					<!-- Inhaltsskalierung -->
					<div class="wave-slider-row" data-slider="content-scale">
						<label class="wave-slider-label" for="wave-slider-content-scale"><?php esc_html_e('Inhaltsskalierung', 'wave-access'); ?></label>
						<input type="range" id="wave-slider-content-scale" class="wave-slider" min="80" max="200" step="10" value="100" aria-valuemin="80" aria-valuemax="200" aria-valuenow="100">
						<span class="wave-slider-value" aria-live="polite">100%</span>
						<button type="button" class="wave-slider-btn wave-slider-decrease" data-target="content-scale" aria-label="<?php esc_attr_e('Inhaltsskalierung verringern', 'wave-access'); ?>">−</button>
						<button type="button" class="wave-slider-btn wave-slider-increase" data-target="content-scale" aria-label="<?php esc_attr_e('Inhaltsskalierung erhöhen', 'wave-access'); ?>">+</button>
					</div>

					<!-- Schriftgröße -->
					<div class="wave-slider-row" data-slider="font-size">
						<label class="wave-slider-label" for="wave-slider-font-size"><?php esc_html_e('Schriftgröße', 'wave-access'); ?></label>
						<input type="range" id="wave-slider-font-size" class="wave-slider" min="80" max="200" step="10" value="100" aria-valuemin="80" aria-valuemax="200" aria-valuenow="100">
						<span class="wave-slider-value" aria-live="polite">100%</span>
						<button type="button" class="wave-slider-btn wave-slider-decrease" data-target="font-size" aria-label="<?php esc_attr_e('Schriftgröße verringern', 'wave-access'); ?>">−</button>
						<button type="button" class="wave-slider-btn wave-slider-increase" data-target="font-size" aria-label="<?php esc_attr_e('Schriftgröße erhöhen', 'wave-access'); ?>">+</button>
					</div>

					<!-- Zeilenhöhe -->
					<div class="wave-slider-row" data-slider="line-height">
						<label class="wave-slider-label" for="wave-slider-line-height"><?php esc_html_e('Zeilenhöhe', 'wave-access'); ?></label>
						<input type="range" id="wave-slider-line-height" class="wave-slider" min="80" max="200" step="10" value="100" aria-valuemin="80" aria-valuemax="200" aria-valuenow="100">
						<span class="wave-slider-value" aria-live="polite">100%</span>
						<button type="button" class="wave-slider-btn wave-slider-decrease" data-target="line-height" aria-label="<?php esc_attr_e('Zeilenhöhe verringern', 'wave-access'); ?>">−</button>
						<button type="button" class="wave-slider-btn wave-slider-increase" data-target="line-height" aria-label="<?php esc_attr_e('Zeilenhöhe erhöhen', 'wave-access'); ?>">+</button>
					</div>

					<!-- Zeichenabstand -->
					<div class="wave-slider-row" data-slider="letter-spacing">
						<label class="wave-slider-label" for="wave-slider-letter-spacing"><?php esc_html_e('Zeichenabstand', 'wave-access'); ?></label>
						<input type="range" id="wave-slider-letter-spacing" class="wave-slider" min="80" max="200" step="10" value="100" aria-valuemin="80" aria-valuemax="200" aria-valuenow="100">
						<span class="wave-slider-value" aria-live="polite">100%</span>
						<button type="button" class="wave-slider-btn wave-slider-decrease" data-target="letter-spacing" aria-label="<?php esc_attr_e('Zeichenabstand verringern', 'wave-access'); ?>">−</button>
						<button type="button" class="wave-slider-btn wave-slider-increase" data-target="letter-spacing" aria-label="<?php esc_attr_e('Zeichenabstand erhöhen', 'wave-access'); ?>">+</button>
					</div>

				</div>

				<?php if ( ! empty( $this->options['show_branding'] ) || ! Wave_License::is_pro() ) : ?>
				<div class="wave-panel-foot">
					<a class="wave-brand" href="https://wavetools.io" target="_blank" rel="noopener nofollow">powered by <b>Wave&nbsp;Tools</b></a>
				</div>
				<?php endif; ?>
		<?php
	}

	
	/**
	 * Gutenberg-Block registrieren (serverseitig gerendert).
	 *
	 * Block "wave/accessibility-panel" zeigt dasselbe Bedienfeld wie das
	 * schwebende Widget – jedoch direkt im Inhalt, ohne Toggle-Button.
	 * Ideal zum Einbetten in Popups, Seiten oder Footer.
	 */
	public function register_block() {
		if ( ! function_exists( 'register_block_type' ) ) {
			return;
		}

		// Editor-Skript (ohne Build-Step, nutzt window.wp.*)
		wp_register_script(
			'wave-block',
			WAVE_PLUGIN_URL . 'assets/block.js',
			array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-server-side-render' ),
			WAVE_VERSION,
			true
		);

		// Editor-only Stylesheet: nur die Block-Vorschau, vollständig unter
		// .wave-inline-widget gescopt. Bewusst NICHT frontend.css, damit keine
		// globalen Regeln (z. B. *:focus-visible) in den Gutenberg-Editor lecken.
		wp_register_style(
			'wave-block-editor',
			WAVE_PLUGIN_URL . 'assets/editor.css',
			array(),
			WAVE_VERSION
		);

		register_block_type( 'wave/accessibility-panel', array(
			'api_version'     => 2,
			'editor_script'   => 'wave-block',
			'editor_style'    => 'wave-block-editor',
			'render_callback' => array( $this, 'render_accessibility_block' ),
			'attributes'      => array(
				'showTitle' => array( 'type' => 'boolean', 'default' => true ),
				'showReset' => array( 'type' => 'boolean', 'default' => true ),
				'title'     => array( 'type' => 'string',  'default' => '' ),
				'className' => array( 'type' => 'string',  'default' => '' ),
			),
		) );
	}

	/**
	 * Render-Callback für den Block "wave/accessibility-panel".
	 *
	 * @param array $attributes Block-Attribute
	 * @return string HTML des Inline-Panels
	 */
	public function render_accessibility_block( $attributes = array() ) {
		$attributes = wp_parse_args( $attributes, array(
			'showTitle' => true,
			'showReset' => true,
			'title'     => '',
			'className' => '',
		) );

		$show_title = (bool) $attributes['showTitle'];
		$show_reset = (bool) $attributes['showReset'];
		$title      = ( '' !== trim( (string) $attributes['title'] ) )
			? $attributes['title']
			: __( 'Eingabehilfen', 'wave-access' );

		// Sicherstellen, dass die Frontend-Assets geladen sind. Auf normalen
		// Frontend-Seiten passiert das bereits global; hier als Absicherung,
		// falls der Block in einem späten/REST-Kontext gerendert wird.
		if ( ! is_admin() && ! wp_script_is( 'wave-frontend', 'enqueued' ) ) {
			$this->enqueue_frontend_scripts();
		}

		$wrapper_classes = 'wave-inline-widget';
		if ( ! empty( $attributes['className'] ) ) {
			$wrapper_classes .= ' ' . sanitize_html_class( $attributes['className'] );
		}

		ob_start();
		?>
		<div class="<?php echo esc_attr( $wrapper_classes ); ?>">
			<div class="wave-inline-panel" role="group" aria-label="<?php esc_attr_e( 'Eingabehilfen', 'wave-access' ); ?>">
				<?php
				$this->render_panel_inner( array(
					'show_header' => ( $show_title || $show_reset ),
					'show_title'  => $show_title,
					'show_reset'  => $show_reset,
					'show_close'  => false,
					'title'       => $title,
				) );
				?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Shortcode [wave_access] – rendert dasselbe Panel wie der Gutenberg-Block.
	 * Attribute: title="…", show_title="0|1", show_reset="0|1"
	 */
	public function render_shortcode( $atts = array() ) {
		$atts = shortcode_atts( array(
			'title'      => '',
			'show_title' => '1',
			'show_reset' => '1',
		), $atts, 'wave_access' );
		$truthy = function( $v ) { return ! in_array( strtolower( (string) $v ), array( '0', 'false', 'no', 'off' ), true ); };
		return $this->render_accessibility_block( array(
			'showTitle' => $truthy( $atts['show_title'] ),
			'showReset' => $truthy( $atts['show_reset'] ),
			'title'     => $atts['title'],
		) );
	}

	/**
	 * Content auf Barrierefreiheit prüfen
	 */
	public function check_content_accessibility($content) {
		if (!is_admin() && current_user_can('edit_posts')) {
			$warnings = array();
			
			// Prüfung auf leere Links
			if (preg_match_all('/<a[^>]*?>\s*<\/a>/i', $content, $matches)) {
				$warnings[] = __('Leere Links gefunden', 'wave-access');
			}
			
			// Prüfung auf Überschriften-Hierarchie
			if ($this->options['enable_heading_checker']) {
				$heading_issues = $this->check_heading_hierarchy($content);
				if ($heading_issues) {
					$warnings[] = $heading_issues;
				}
			}
			
			if (!empty($warnings)) {
				$warning_html = '<div class="wave-content-warnings" style="background: #fff3cd; border: 1px solid #ffc107; padding: 10px; margin: 10px 0;">';
				$warning_html .= '<strong>' . __('Barrierefreiheits-Hinweise:', 'wave-access') . '</strong><ul>';
				foreach ($warnings as $warning) {
					$warning_html .= '<li>' . esc_html($warning) . '</li>';
				}
				$warning_html .= '</ul></div>';
				$content = $warning_html . $content;
			}
		}
		
		// ARIA-Labels automatisch hinzufügen
		if ($this->options['enable_aria_labels']) {
			$content = $this->add_aria_labels($content);
		}
		
		return $content;
	}
	
	/**
	 * Überschriften-Hierarchie prüfen
	 */
	private function check_heading_hierarchy($content) {
		preg_match_all('/<h([1-6])[^>]*>/i', $content, $matches);
		
		if (empty($matches[1])) {
			return false;
		}
		
		$headings = array_map('intval', $matches[1]);
		$prev = 0;
		
		foreach ($headings as $level) {
			if ($prev > 0 && $level > $prev + 1) {
				return sprintf(__('Überschriften-Hierarchie übersprungen (H%d zu H%d)', 'wave-access'), $prev, $level);
			}
			$prev = $level;
		}
		
		return false;
	}
	
	/**
	 * ARIA-Labels hinzufügen
	 */
	private function add_aria_labels($content) {
		// Navigations-Landmarks
		$content = preg_replace('/<nav(?![^>]*role)/i', '<nav role="navigation"', $content);
		
		// Hauptinhalt-Landmark
		$content = preg_replace('/<main(?![^>]*role)/i', '<main role="main"', $content);
		
		// Such-Formulare
		$content = preg_replace('/<form[^>]*class="[^"]*search[^"]*"(?![^>]*role)/i', '$0 role="search"', $content);
		
		return $content;
	}
	
	/**
	 * Bild Alt-Attribute prüfen
	 */
	public function check_image_alt($attr, $attachment, $size) {
		if ($this->options['enable_image_checker']) {
			// Prüfe ob Alt-Text vorhanden
			if (empty($attr['alt'])) {
				// Alt-Text aus Bildtitel generieren falls leer
				$attr['alt'] = get_the_title($attachment->ID);
				
				// Warnung für Admins - visuelle Markierung
				if (current_user_can('edit_posts') && !is_admin()) {
					$attr['data-wave-warning'] = __('Alt-Text fehlt', 'wave-access');
					$attr['style'] = (isset($attr['style']) ? $attr['style'] . '; ' : '') . 'border: 3px solid #ff0000 !important; box-shadow: 0 0 10px rgba(255,0,0,0.5) !important;';
					$attr['title'] = __('WARNUNG: Alt-Text fehlt! Bitte in der Mediathek hinzufügen.', 'wave-access');
				}
			}
		}
		
		return $attr;
	}
	
	/**
	 * AJAX: Nutzer-Präferenzen speichern
	 */
	public function ajax_save_preferences() {
		check_ajax_referer('wave_nonce', 'nonce');
		
		$preferences = array(
			'font_size' => isset($_POST['font_size']) ? sanitize_text_field($_POST['font_size']) : 'normal',
			'high_contrast' => isset($_POST['high_contrast']) ? (bool) $_POST['high_contrast'] : false
		);
		
		// In Cookie speichern (30 Tage)
		setcookie('wave_preferences', json_encode($preferences), time() + (30 * DAY_IN_SECONDS), '/');
		
		wp_send_json_success($preferences);
	}
	
	/**
	 * Language Attributes hinzufügen (dir und lang)
	 */
	public function add_language_attributes($output, $doctype) {
		// Nur wenn Feature aktiviert ist
		if (!$this->options['enable_lang_attributes']) {
			return $output;
		}
		
		// Dir-Attribut hinzufügen wenn nicht vorhanden
		if (strpos($output, 'dir=') === false) {
			$text_direction = is_rtl() ? 'rtl' : 'ltr';
			$output .= ' dir="' . $text_direction . '"';
		}
		
		// Lang-Attribut sicherstellen
		if (strpos($output, 'lang=') === false) {
			$lang = get_bloginfo('language');
			if (empty($lang)) {
				$lang = 'de-DE'; // Fallback für Deutsch
			}
			$output .= ' lang="' . esc_attr($lang) . '"';
		}
		
		// XML-Lang für XHTML-Kompatibilität
		if ($doctype === 'xhtml' && strpos($output, 'xml:lang=') === false) {
			$lang = get_bloginfo('language');
			if (empty($lang)) {
				$lang = 'de-DE';
			}
			$output .= ' xml:lang="' . esc_attr($lang) . '"';
		}
		
		return $output;
	}
	
	/**
	 * Dashboard Widget hinzufügen
	 */
	public function add_dashboard_widget() {
		if ( empty( $this->options['show_dashboard_widget'] ) ) {
			return;
		}
		wp_add_dashboard_widget(
			'wave_dashboard_widget',
			__('Barrierefreiheit Status', 'wave-access'),
			array($this, 'dashboard_widget_content')
		);
	}
	
	/**
	 * Dashboard Widget Inhalt
	 */
	public function dashboard_widget_content() {
		$images_without_alt = $this->check_images_without_alt();
		$total_images = wp_count_posts('attachment')->inherit;
		$percentage = $total_images > 0 ? round((($total_images - $images_without_alt) / $total_images) * 100) : 100;
		$checklist_progress = $this->get_checklist_progress();
		
		?>
		<div class="wave-dashboard-widget">
			<div class="main-stat">
				<span class="stat-number" style="color: <?php echo $percentage >= 90 ? '#46b450' : ($percentage >= 70 ? '#ffb900' : '#dc3232'); ?>">
					<?php echo $percentage; ?>%
				</span>
				<span class="stat-label"><?php esc_html_e('Bilder mit Alt-Text', 'wave-access'); ?></span>
			</div>
			
			<div class="secondary-stat" style="margin: 15px 0; padding: 10px; background: #f0f0f0; border-radius: 4px;">
				<strong><?php esc_html_e('BFSG-Checkliste:', 'wave-access'); ?></strong>
				<span style="float: right; color: <?php echo $checklist_progress >= 80 ? '#46b450' : ($checklist_progress >= 50 ? '#ffb900' : '#dc3232'); ?>">
					<?php echo $checklist_progress; ?>% <?php esc_html_e('abgeschlossen', 'wave-access'); ?>
				</span>
			</div>
			
			<?php if ($images_without_alt > 0): ?>
				<div class="warning-box" style="background: #fff8e5; border-left: 4px solid #ffb900; padding: 10px; margin: 15px 0;">
					<strong><?php echo sprintf(__('%d Bilder ohne Alt-Text', 'wave-access'), $images_without_alt); ?></strong>
				</div>
			<?php else: ?>
				<div class="success-box" style="background: #ecf7ed; border-left: 4px solid #46b450; padding: 10px; margin: 15px 0;">
					<strong><?php esc_html_e('Alle Bilder haben Alt-Texte! ✔', 'wave-access'); ?></strong>
				</div>
			<?php endif; ?>
			
			<p>
				<a href="<?php echo admin_url('options-general.php?page=wave-access&maintab=report'); ?>" class="button button-primary">
					<?php esc_html_e('Vollständigen Bericht anzeigen', 'wave-access'); ?>
				</a>
				<a href="<?php echo admin_url('options-general.php?page=wave-access&maintab=report&tab=checklist'); ?>" class="button">
					<?php esc_html_e('Zur Checkliste', 'wave-access'); ?>
				</a>
			</p>
		</div>
		
		<style>
			.wave-dashboard-widget .main-stat {
				text-align: center;
				padding: 20px 0;
			}
			.wave-dashboard-widget .stat-number {
				display: block;
				font-size: 48px;
				font-weight: 600;
				line-height: 1;
			}
			.wave-dashboard-widget .stat-label {
				display: block;
				margin-top: 10px;
				color: #666;
				font-size: 14px;
			}
		</style>
		<?php
	}
	
	/**
	 * Admin-Benachrichtigungen anzeigen
	 */
	public function show_admin_notices() {
		// Leer implementiert - kann bei Bedarf aktiviert werden
	}
	
	/**
	 * Prüfung bei neuem Bild-Upload
	 */
	public function check_new_image_alt($attachment_id) {
		$attachment = get_post($attachment_id);
		
		if (!wp_attachment_is_image($attachment_id)) {
			return;
		}
		
		$alt_text = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
		
		if (empty($alt_text)) {
			// Admin-Notice anzeigen (erscheint beim nächsten Seitenaufruf)
			set_transient('wave_new_image_without_alt_' . get_current_user_id(), array(
				'id' => $attachment_id,
				'filename' => basename($attachment->guid)
			), 60);
			
			// E-Mail-Benachrichtigung wenn aktiviert
			$this->send_alt_text_notification($attachment_id);
		}
	}
	
	/**
	 * Prüfung bei Bild-Update
	 */
	public function check_updated_image_alt($attachment_id) {
		$this->check_new_image_alt($attachment_id);
	}
	
	/**
	 * E-Mail-Benachrichtigung senden
	 */
	private function send_alt_text_notification($attachment_id) {
		// Prüfen ob E-Mail-Benachrichtigungen aktiviert sind
		if (empty($this->options['email_notifications'])) {
			return;
		}
		
		$attachment = get_post($attachment_id);
		$admin_email = get_option('admin_email');
		
		$subject = sprintf(
			__('[%s] Neues Bild ohne Alt-Text', 'wave-access'),
			get_bloginfo('name')
		);
		
		$message = sprintf(
			__("Hallo,\n\nEin neues Bild wurde ohne Alt-Text hochgeladen:\n\nDateiname: %s\nHochgeladen von: %s\nDatum: %s\n\nBitte fügen Sie einen Alt-Text hinzu:\n%s\n\nDiese Nachricht wurde automatisch vom BFSG Accessibility Helper Plugin generiert.", 'wave-access'),
			basename($attachment->guid),
			get_the_author_meta('display_name', $attachment->post_author),
			date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($attachment->post_date)),
			admin_url('post.php?post=' . $attachment_id . '&action=edit')
		);
		
		wp_mail($admin_email, $subject, $message);
	}
	
	/**
	 * AJAX: Notice dismissal
	 */
	public function ajax_dismiss_notice() {
		check_ajax_referer('wave_dismiss', '_wpnonce');
		
		$notice = sanitize_text_field($_POST['notice']);
		$user_id = get_current_user_id();
		
		$dismissed = get_user_meta($user_id, 'wave_dismissed_notices', true);
		if (!is_array($dismissed)) {
			$dismissed = array();
		}
		
		if (!in_array($notice, $dismissed)) {
			$dismissed[] = $notice;
			update_user_meta($user_id, 'wave_dismissed_notices', $dismissed);
		}
		
		wp_send_json_success();
	}
	
	/**
	 * AJAX: Checkliste speichern
	 */
	public function ajax_save_checklist() {
		check_ajax_referer('wave_checklist_nonce', 'nonce');
		
		if (!current_user_can('manage_options')) {
			wp_send_json_error('Keine Berechtigung');
		}
		
		$checklist = isset($_POST['checklist']) ? $_POST['checklist'] : array();
		$sanitized = array();
		
		// Sanitize checklist data
		foreach ($checklist as $key => $value) {
			$sanitized[sanitize_text_field($key)] = 1;
		}
		
		update_option('wave_checklist', $sanitized);
		
		wp_send_json_success(array(
			'message' => __('Checkliste gespeichert', 'wave-access'),
			'progress' => $this->get_checklist_progress()
		));
	}
	
	/**
	 * CSV Export der Bilder ohne Alt-Text
	 */
	private function export_csv_report() {
		if ( ! Wave_License::is_pro() ) {
			wp_die( esc_html__( 'Der CSV-Export ist Teil des Pro-Tarifs.', 'wave-access' ) );
		}
		if (!current_user_can('manage_options')) {
			wp_die(__('Keine Berechtigung', 'wave-access'));
		}
		
		$images = $this->get_images_without_alt_details();
		
		// CSV Header senden
		header('Content-Type: text/csv; charset=utf-8');
		header('Content-Disposition: attachment; filename="barrierefreiheit-bericht-' . date('Y-m-d') . '.csv"');
		
		// UTF-8 BOM für Excel
		echo "\xEF\xBB\xBF";
		
		// CSV erstellen
		$output = fopen('php://output', 'w');
		
		// Header-Zeile
		fputcsv($output, array(
			'ID',
			'Dateiname',
			'Titel',
			'URL',
			'Hochgeladen am',
			'Autor',
			'Verwendet in'
		), ';');
		
		// Daten-Zeilen
		foreach ($images as $image) {
			$used_in = $this->get_posts_using_image($image->ID);
			$posts_list = array();
			
			foreach ($used_in as $post_id) {
				$post = get_post($post_id);
				if ($post) {
					$posts_list[] = $post->post_title . ' (' . get_permalink($post_id) . ')';
				}
			}
			
			fputcsv($output, array(
				$image->ID,
				basename($image->guid),
				$image->post_title,
				$image->guid,
				date_i18n('Y-m-d H:i', strtotime($image->post_date)),
				get_the_author_meta('display_name', $image->post_author),
				implode(' | ', $posts_list) ?: 'Nicht verwendet'
			), ';');
		}
		
		fclose($output);
		exit;
	}
	
	/**
	 * Tab-Visualisierer Daten hinzufügen
	 */
	public function add_tab_visualizer_data() {
		?>
		<script>
		jQuery(document).ready(function($) {
			// Data-Attribut setzen
			$('body').attr('data-wave-tab-visualizer', 'true');
		});
		</script>
		<?php
	}
	
	/**
	 * Admin-Bar Menü hinzufügen
	 */
	public function add_admin_bar_menu($wp_admin_bar) {
		if ( empty( $this->options['show_admin_bar'] ) ) {
			return;
		}
		if (!current_user_can('manage_options')) {
			return;
		}
		
		// Hauptmenü
		$wp_admin_bar->add_node(array(
			'id' => 'wave-access',
			'title' => '<span class="ab-icon dashicons dashicons-universal-access-alt"></span>' . __('Barrierefreiheit', 'wave-access'),
			'href' => admin_url('options-general.php?page=wave-access'),
			'meta' => array(
				'title' => __('BFSG Barrierefreiheit', 'wave-access')
			)
		));
		
		// Tab-Visualisierer Toggle
		if (isset($this->options['enable_tab_visualizer']) && $this->options['enable_tab_visualizer']) {
			$wp_admin_bar->add_node(array(
				'id' => 'wave-tab-visualizer',
				'parent' => 'wave-access',
				'title' => __('🔍 Tab-Reihenfolge anzeigen', 'wave-access'),
				'href' => '#',
				'meta' => array(
					'onclick' => 'jQuery(".wave-tab-visualizer-toggle").click(); return false;',
					'title' => __('Tab-Reihenfolge visualisieren', 'wave-access')
				)
			));
		}
		
		// Prüfbericht
		$images_without_alt = $this->check_images_without_alt();
		$report_title = $images_without_alt > 0 
			? sprintf(__('⚠️ Prüfbericht (%d Probleme)', 'wave-access'), $images_without_alt)
			: __('✅ Prüfbericht', 'wave-access');
			
		$wp_admin_bar->add_node(array(
			'id' => 'wave-report',
			'parent' => 'wave-access',
			'title' => $report_title,
			'href' => admin_url('options-general.php?page=wave-access&maintab=report')
		));
		
		// Einstellungen
		$wp_admin_bar->add_node(array(
			'id' => 'wave-settings',
			'parent' => 'wave-access',
			'title' => __('⚙️ Einstellungen', 'wave-access'),
			'href' => admin_url('options-general.php?page=wave-access')
		));
	}
	
	/**
	 * Tab-Reihenfolge Test-Seite
	 */
	public function tab_order_page() {
		?>
			<h2><?php echo esc_html__('Tab-Reihenfolge Test & Optimierung', 'wave-access'); ?></h2>

			<div class="notice notice-info">
				<p><?php esc_html_e('Testen Sie die Tab-Reihenfolge Ihrer Website und optimieren Sie die Tastaturnavigation.', 'wave-access'); ?></p>
			</div>
			
			<div class="info-cards">
				<div class="info-card">
					<h3><span class="dashicons dashicons-yes-alt"></span> <?php esc_html_e('Automatische Optimierung', 'wave-access'); ?></h3>
					<p><?php esc_html_e('Das Plugin optimiert automatisch:', 'wave-access'); ?></p>
					<ul>
						<li><?php esc_html_e('Entfernt negative tabindex-Werte', 'wave-access'); ?></li>
						<li><?php esc_html_e('Fügt tabindex="0" zu interaktiven Elementen hinzu', 'wave-access'); ?></li>
						<li><?php esc_html_e('Strukturiert Navigation, Hauptinhalt und Footer', 'wave-access'); ?></li>
						<li><?php esc_html_e('Optimiert Formular-Reihenfolge', 'wave-access'); ?></li>
						<li><?php esc_html_e('Implementiert Fokus-Traps für Modale', 'wave-access'); ?></li>
					</ul>
				</div>
				
				<div class="info-card">
					<h3><span class="dashicons dashicons-visibility"></span> <?php esc_html_e('Tab-Visualisierer', 'wave-access'); ?></h3>
					<p><?php esc_html_e('Aktivieren Sie die visuelle Darstellung der Tab-Reihenfolge:', 'wave-access'); ?></p>
					<ol>
						<li><?php esc_html_e('Aktivieren Sie "Tab-Reihenfolge visualisieren" in den Einstellungen', 'wave-access'); ?></li>
						<li><?php esc_html_e('Besuchen Sie Ihre Website als Admin', 'wave-access'); ?></li>
						<li><?php esc_html_e('Klicken Sie auf den Button "Tab-Reihenfolge"', 'wave-access'); ?></li>
						<li><?php esc_html_e('Rote Nummern zeigen die Tab-Reihenfolge an', 'wave-access'); ?></li>
					</ol>
				</div>
			</div>
			
			<h2><?php esc_html_e('Test-Formular', 'wave-access'); ?></h2>
			<p><?php esc_html_e('Testen Sie die Tab-Reihenfolge mit diesem Beispielformular:', 'wave-access'); ?></p>
			
			<form class="wave-test-form" style="max-width: 600px; padding: 20px; background: #f9f9f9; border: 1px solid #ddd;">
				<div class="form-group" style="margin-bottom: 15px;">
					<label for="test-name"><?php esc_html_e('Name:', 'wave-access'); ?></label><br>
					<input type="text" id="test-name" name="name" style="width: 100%; padding: 5px;">
				</div>
				
				<div class="form-group" style="margin-bottom: 15px;">
					<label for="test-email"><?php esc_html_e('E-Mail:', 'wave-access'); ?></label><br>
					<input type="email" id="test-email" name="email" style="width: 100%; padding: 5px;">
				</div>
				
				<div class="form-group" style="margin-bottom: 15px;">
					<label for="test-select"><?php esc_html_e('Auswahl:', 'wave-access'); ?></label><br>
					<select id="test-select" name="select" style="width: 100%; padding: 5px;">
						<option><?php esc_html_e('Option 1', 'wave-access'); ?></option>
						<option><?php esc_html_e('Option 2', 'wave-access'); ?></option>
						<option><?php esc_html_e('Option 3', 'wave-access'); ?></option>
					</select>
				</div>
				
				<div class="form-group" style="margin-bottom: 15px;">
					<label for="test-message"><?php esc_html_e('Nachricht:', 'wave-access'); ?></label><br>
					<textarea id="test-message" name="message" rows="4" style="width: 100%; padding: 5px;"></textarea>
				</div>
				
				<div class="form-group">
					<button type="button" class="button button-secondary"><?php esc_html_e('Zurücksetzen', 'wave-access'); ?></button>
					<button type="button" class="button button-primary"><?php esc_html_e('Absenden', 'wave-access'); ?></button>
				</div>
			</form>
			
			<h2><?php esc_html_e('Tab-Reihenfolge Tipps', 'wave-access'); ?></h2>
			
			<div style="background: #fff; padding: 20px; border-left: 4px solid #0073aa; margin: 20px 0;">
				<h3><?php esc_html_e('Best Practices:', 'wave-access'); ?></h3>
				<ul>
					<li><strong><?php esc_html_e('Logische Reihenfolge:', 'wave-access'); ?></strong> <?php esc_html_e('Die Tab-Reihenfolge sollte der visuellen Reihenfolge entsprechen', 'wave-access'); ?></li>
					<li><strong><?php esc_html_e('Alle Elemente erreichbar:', 'wave-access'); ?></strong> <?php esc_html_e('Jedes interaktive Element muss per Tastatur erreichbar sein', 'wave-access'); ?></li>
					<li><strong><?php esc_html_e('Fokus sichtbar:', 'wave-access'); ?></strong> <?php esc_html_e('Der Fokus muss immer klar erkennbar sein', 'wave-access'); ?></li>
					<li><strong><?php esc_html_e('Skip-Links:', 'wave-access'); ?></strong> <?php esc_html_e('Ermöglichen das Überspringen von sich wiederholenden Inhalten', 'wave-access'); ?></li>
					<li><strong><?php esc_html_e('Keine Fokus-Fallen:', 'wave-access'); ?></strong> <?php esc_html_e('Nutzer dürfen nicht in einem Element gefangen werden', 'wave-access'); ?></li>
				</ul>
			</div>
			
			<div style="background: #fff3cd; padding: 20px; border-left: 4px solid #ffc107; margin: 20px 0;">
				<h3><?php esc_html_e('Häufige Probleme:', 'wave-access'); ?></h3>
				<ul>
					<li><?php esc_html_e('Positive tabindex-Werte (1, 2, 3...) - verwenden Sie stattdessen 0', 'wave-access'); ?></li>
					<li><?php esc_html_e('Versteckte Elemente mit tabindex - entfernen Sie tabindex von unsichtbaren Elementen', 'wave-access'); ?></li>
					<li><?php esc_html_e('Fehlende Fokus-Indikatoren - stellen Sie sicher, dass :focus sichtbar ist', 'wave-access'); ?></li>
					<li><?php esc_html_e('Links ohne href - diese sind nicht per Tastatur erreichbar', 'wave-access'); ?></li>
					<li><?php esc_html_e('Onclick-Handler auf divs - verwenden Sie stattdessen Buttons', 'wave-access'); ?></li>
				</ul>
			</div>
			
			<div class="action-buttons">
				<a href="<?php echo home_url(); ?>" target="_blank" class="button button-primary">
					<?php esc_html_e('Website mit Visualisierer öffnen', 'wave-access'); ?>
				</a>
				<a href="<?php echo admin_url('options-general.php?page=wave-access'); ?>" class="button button-secondary">
					<?php esc_html_e('Zu den Einstellungen', 'wave-access'); ?>
				</a>
			</div>

		<script>
		jQuery(document).ready(function($) {
			// Test-Formular Tab-Reihenfolge demonstrieren
			var tabIndex = 1;
			$('.wave-test-form').find('input, select, textarea, button').each(function() {
				var $elem = $(this);
				$elem.on('focus', function() {
					console.log('Tab-Reihenfolge: Element ' + tabIndex + ' fokussiert');
				});
			});
		});
		</script>
		<?php
	}
}

/**
 * Plugin aktivieren — inkl. Migration alter wave_*-Optionen
 */
function wave_activate() {
	// Sanfte Migration: alte wave_*-Optionen umkopieren, falls vorhanden
	$old_options = get_option('wave_options');
	if ($old_options !== false && get_option('wave_options') === false) {
		add_option('wave_options', $old_options);
		delete_option('wave_options');
	}
	$old_checklist = get_option('wave_checklist');
	if ($old_checklist !== false && get_option('wave_checklist') === false) {
		add_option('wave_checklist', $old_checklist);
		delete_option('wave_checklist');
	}

	// Prüfen ob Optionen bereits existieren
	$existing_options = get_option('wave_options');

	if ($existing_options === false) {
		// Standardoptionen nur setzen wenn noch keine existieren
		$default_options = array(
			'enable_grayscale' => true,
			'enable_skip_links' => true,
			'enable_focus_indicator' => true,
			'enable_image_checker' => true,
			'enable_heading_checker' => true,
			'enable_aria_labels' => true,
			'enable_contrast_toggle' => true,
			'enable_font_resizer' => true,
			'enable_keyboard_nav' => true,
			'enable_screen_reader_text' => true,
			'enable_lang_attributes' => true,
			'enable_tab_order' => true,
			'enable_tab_visualizer' => false,
			'enable_floating_widget' => true,
			'enable_underline_links' => true,
			'enable_inherit_font' => false,
			'email_notifications' => false,
			'custom_focus_color' => '#0073aa',
			'widget_accent_color' => '#4a4a4a',
			'min_contrast_ratio' => '4.5',
			// Widget 2.0 – Darstellung
			'widget_position'    => 'br',      // br | bl | tr | tl
			'widget_offset'      => 24,        // Randabstand in px
			'widget_size'        => 'm',       // s | m | l
			'widget_radius'      => 24,        // Panel-Rundung in px
			'widget_icon'        => 'person',  // person | wheelchair | sliders | custom
			'widget_icon_custom' => '',        // Attachment-URL bei custom
			'panel_theme'        => 'light',   // light | dark | custom
			'panel_bg_var'       => '',        // CSS-Variable für Hintergrund (custom)
			'panel_text_var'     => '',        // CSS-Variable für Text (custom)
			'show_branding'      => true,      // "powered by Wave Tools" (abschaltbar ab Pro)
			// Backend-Integration
			'show_dashboard_widget' => true,   // Status-Widget im WP-Dashboard
			'show_admin_bar'        => true    // Eintrag in der Admin-Leiste
		);

		add_option('wave_options', $default_options);
	} else {
		// Neue Optionen zu bestehenden hinzufügen
		$updated = false;
		if (!isset($existing_options['enable_grayscale'])) {
			$existing_options['enable_grayscale'] = true;
			$updated = true;
		}
		if (!isset($existing_options['enable_lang_attributes'])) {
			$existing_options['enable_lang_attributes'] = true;
			$updated = true;
		}
		if (!isset($existing_options['email_notifications'])) {
			$existing_options['email_notifications'] = false;
			$updated = true;
		}
		if (!isset($existing_options['enable_tab_order'])) {
			$existing_options['enable_tab_order'] = true;
			$updated = true;
		}
		if (!isset($existing_options['enable_tab_visualizer'])) {
			$existing_options['enable_tab_visualizer'] = false;
			$updated = true;
		}
		if (!isset($existing_options['enable_floating_widget'])) {
			$existing_options['enable_floating_widget'] = true;
			$updated = true;
		}
		if (!isset($existing_options['enable_underline_links'])) {
			$existing_options['enable_underline_links'] = true;
			$updated = true;
		}
		if (!isset($existing_options['widget_accent_color'])) {
			$existing_options['widget_accent_color'] = '#4a4a4a';
			$updated = true;
		}
		if (!isset($existing_options['enable_inherit_font'])) {
			$existing_options['enable_inherit_font'] = false;
			$updated = true;
		}

		if ($updated) {
			update_option('wave_options', $existing_options);
		}
	}
}
register_activation_hook(__FILE__, 'wave_activate');

/**
 * Plugin deaktivieren
 */
function wave_deactivate() {
	// Cleanup bei Bedarf
}
register_deactivation_hook(__FILE__, 'wave_deactivate');

/**
 * Plugin initialisieren
 */
function wave_init() {
	Wave_Access::get_instance();
}
add_action('plugins_loaded', 'wave_init');

// Textdomain laden
function wave_load_textdomain() {
	load_plugin_textdomain('wave-access', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
add_action('init', 'wave_load_textdomain');
