<?php
/**
 * Premium admin panel (top-level "Copyfend" menu).
 *
 * Single-page app feel: one settings form, sections switched client-side with
 * no reload. Built with plain PHP + CSS + vanilla JS — no build pipeline.
 *
 * @package Copyfend
 */

defined( 'ABSPATH' ) || exit;

/**
 * Registers the menu, enqueues assets and renders the panel.
 */
class CShield_Admin {

	/**
	 * Settings handler.
	 *
	 * @var CShield_Settings
	 */
	private $settings;

	/**
	 * Current option values (cached for render helpers).
	 *
	 * @var array
	 */
	private $o = array();

	/**
	 * Admin page hook suffix.
	 *
	 * @var string
	 */
	private $hook = '';

	/**
	 * Pro section renderer (present in Copyfend Pro only).
	 *
	 * @var CShield_Admin_Pro|null
	 */
	private $pro = null;

	/**
	 * Constructor.
	 *
	 * @param CShield_Settings $settings Settings handler.
	 */
	public function __construct( CShield_Settings $settings ) {
		$this->settings = $settings;
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_init', array( $this, 'register' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
		add_filter( 'plugin_action_links_' . CSHIELD_BASENAME, array( $this, 'action_links' ) );
		add_action( 'add_meta_boxes', array( $this, 'add_protect_meta_box' ) );
		add_action( 'save_post', array( $this, 'save_protect_meta' ), 10, 2 );
		add_action( 'admin_post_cshield_apply_profile', array( $this, 'apply_profile' ) );

		if ( class_exists( 'CShield_Admin_Pro' ) ) {
			$this->pro = new CShield_Admin_Pro( $this, $settings );
		}
	}

	/**
	 * The settings page hook suffix (used by the Pro renderer's enqueue).
	 *
	 * @return string
	 */
	public function hook() {
		return $this->hook;
	}

	/**
	 * Register the top-level menu with a custom shield icon.
	 */
	public function menu() {
		$svg        = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path fill="#a7aaad" d="M12 2l8 3v6c0 5-3.5 8.5-8 11-4.5-2.5-8-6-8-11V5l8-3z"/></svg>';
		$icon       = 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
		$this->hook = add_menu_page(
			__( 'Copyfend', 'copyfend' ),
			__( 'Copyfend', 'copyfend' ),
			'manage_options',
			'copyfend',
			array( $this, 'render' ),
			$icon,
			58
		);
	}

	/**
	 * Register the setting + sanitizer.
	 */
	public function register() {
		register_setting(
			'cshield_group',
			CShield_Settings::OPTION,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( 'CShield_Settings', 'sanitize' ),
				'default'           => CShield_Settings::defaults(),
			)
		);
	}

	/**
	 * Enqueue panel CSS/JS only on our page.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function assets( $hook ) {
		if ( $hook !== $this->hook ) {
			return;
		}
		wp_enqueue_style( 'cshield-admin', CSHIELD_URL . 'assets/css/admin.css', array(), CSHIELD_VERSION );
		wp_enqueue_script( 'cshield-admin', CSHIELD_URL . 'assets/js/admin.js', array(), CSHIELD_VERSION, true );
	}

	/**
	 * Add a "Settings" link on the Plugins screen.
	 *
	 * @param array $links Existing links.
	 * @return array
	 */
	public function action_links( $links ) {
		$url     = admin_url( 'admin.php?page=copyfend' );
		$links[] = '<a href="' . esc_url( $url ) . '">' . esc_html__( 'Settings', 'copyfend' ) . '</a>';
		return $links;
	}

	/* --------------------------------------------------------------------- */
	/* Per-post protection override (meta box)                               */
	/* --------------------------------------------------------------------- */

	/**
	 * Register the per-post override meta box on public post types.
	 */
	public function add_protect_meta_box() {
		foreach ( get_post_types( array( 'public' => true ) ) as $type ) {
			if ( 'attachment' === $type ) {
				continue;
			}
			add_meta_box( 'cshield_protect', __( 'Copyfend', 'copyfend' ), array( $this, 'render_protect_meta_box' ), $type, 'side' );
		}
	}

	/**
	 * Render the per-post override radio options.
	 *
	 * @param WP_Post $post Post.
	 */
	public function render_protect_meta_box( $post ) {
		$value = get_post_meta( $post->ID, '_cshield_protect', true );
		if ( '' === $value ) {
			$value = 'default';
		}
		wp_nonce_field( 'cshield_protect_meta', 'cshield_protect_nonce' );

		$options = array(
			'default' => __( 'Default (use global rules)', 'copyfend' ),
			'on'      => __( 'Always protect this content', 'copyfend' ),
			'off'     => __( 'Never protect this content', 'copyfend' ),
		);
		foreach ( $options as $key => $label ) {
			echo '<p><label><input type="radio" name="cshield_protect" value="' . esc_attr( $key ) . '" ' . checked( $value, $key, false ) . ' /> ' . esc_html( $label ) . '</label></p>';
		}
	}

	/**
	 * Save the per-post override.
	 *
	 * @param int     $post_id Post ID.
	 * @param WP_Post $post    Post.
	 */
	public function save_protect_meta( $post_id, $post ) {
		if ( ! isset( $_POST['cshield_protect_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['cshield_protect_nonce'] ) ), 'cshield_protect_meta' ) ) {
			return;
		}
		if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		$value = isset( $_POST['cshield_protect'] ) ? sanitize_key( wp_unslash( $_POST['cshield_protect'] ) ) : 'default';
		if ( ! in_array( $value, array( 'default', 'on', 'off' ), true ) ) {
			$value = 'default';
		}
		update_post_meta( $post_id, '_cshield_protect', $value );
	}

	/* --------------------------------------------------------------------- */
	/* Onboarding profiles                                                    */
	/* --------------------------------------------------------------------- */

	/**
	 * Option that stores the chosen onboarding profile ('' = not chosen yet).
	 */
	const ONBOARDING = 'cshield_onboarding';

	/**
	 * Site-profile presets applied by the one-click onboarding.
	 *
	 * 'set' holds free settings; 'pro' is merged on top only when licensed.
	 *
	 * @return array
	 */
	private function profiles() {
		return array(
			'blog'     => array(
				'icon'  => 'file',
				'title' => __( 'Blog / Magazine / SEO', 'copyfend' ),
				'desc'  => __( 'Allow copying but turn every copy into a backlink, deter casual copying and protect your feed.', 'copyfend' ),
				'set'   => array(
					'enabled'             => 1,
					'disable_right_click' => 1,
					'disable_image_drag'  => 1,
					'append_attribution'  => 1,
					'disable_selection'   => 0,
					'disable_copy_cut'    => 0,
					'disable_shortcuts'   => 0,
					'block_print'         => 0,
					'copyright_meta'      => 1,
					'rss_attribution'     => 1,
					'exclude_admins'      => 1,
					'allow_search_bots'   => 1,
				),
				'pro'   => array(
					'block_ai_crawlers' => 1,
					'truncate_rss'      => 1,
				),
			),
			'business' => array(
				'icon'  => 'star',
				'title' => __( 'Business / Services', 'copyfend' ),
				'desc'  => __( 'Deter copying, declare ownership and capture leads with the content locker.', 'copyfend' ),
				'set'   => array(
					'enabled'             => 1,
					'disable_right_click' => 1,
					'disable_image_drag'  => 1,
					'append_attribution'  => 1,
					'disable_selection'   => 0,
					'disable_copy_cut'    => 0,
					'disable_shortcuts'   => 0,
					'block_print'         => 0,
					'copyright_meta'      => 1,
					'locker_enabled'      => 1,
					'exclude_admins'      => 1,
					'allow_search_bots'   => 1,
				),
				'pro'   => array(
					'block_bad_bots' => 1,
					'rate_limit'     => 1,
				),
			),
			'photo'    => array(
				'icon'  => 'image',
				'title' => __( 'Photography / Portfolio', 'copyfend' ),
				'desc'  => __( 'Lock text and images down hard: selection, copying, dragging and printing are all blocked.', 'copyfend' ),
				'set'   => array(
					'enabled'             => 1,
					'disable_right_click' => 1,
					'disable_image_drag'  => 1,
					'disable_selection'   => 1,
					'disable_copy_cut'    => 1,
					'disable_shortcuts'   => 1,
					'block_print'         => 1,
					'append_attribution'  => 0,
					'copyright_meta'      => 1,
					'exclude_admins'      => 1,
					'allow_search_bots'   => 1,
				),
				'pro'   => array(
					'watermark_enabled'    => 1,
					'watermark_apply_text' => 1,
					'honeypot_enabled'     => 1,
				),
			),
		);
	}

	/**
	 * Short human labels for the "profile applied" summary chips.
	 *
	 * @return array
	 */
	private function feature_labels() {
		return array(
			'enabled'             => __( 'Protection enabled', 'copyfend' ),
			'disable_right_click' => __( 'Right-click disabled', 'copyfend' ),
			'disable_image_drag'  => __( 'Image dragging blocked', 'copyfend' ),
			'append_attribution'  => __( 'Attribution on copy', 'copyfend' ),
			'disable_selection'   => __( 'Text selection blocked', 'copyfend' ),
			'disable_copy_cut'    => __( 'Copying blocked', 'copyfend' ),
			'disable_shortcuts'   => __( 'Keyboard shortcuts blocked', 'copyfend' ),
			'block_print'         => __( 'Printing blocked', 'copyfend' ),
			'copyright_meta'      => __( 'Copyright meta tag', 'copyfend' ),
			'rss_attribution'     => __( 'RSS attribution footer', 'copyfend' ),
			'locker_enabled'      => __( 'Content Locker', 'copyfend' ),
			'block_ai_crawlers'   => __( 'AI crawlers blocked', 'copyfend' ),
			'truncate_rss'        => __( 'RSS feed truncated', 'copyfend' ),
			'block_bad_bots'      => __( 'Scraping tools blocked', 'copyfend' ),
			'rate_limit'          => __( 'Rate limiting', 'copyfend' ),
			'watermark_enabled'   => __( 'Image watermark', 'copyfend' ),
			'honeypot_enabled'    => __( 'Honeypot bot-trap', 'copyfend' ),
		);
	}

	/**
	 * Apply a one-click onboarding profile (admin-post handler).
	 */
	public function apply_profile() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You are not allowed to do this.', 'copyfend' ) );
		}
		check_admin_referer( 'cshield_profile' );

		$profile  = isset( $_POST['cshield_profile'] ) ? sanitize_key( wp_unslash( $_POST['cshield_profile'] ) ) : '';
		$profiles = $this->profiles();
		$url      = admin_url( 'admin.php?page=copyfend' );

		if ( isset( $profiles[ $profile ] ) ) {
			$preset = $profiles[ $profile ]['set'];
			if ( $this->is_pro() && ! empty( $profiles[ $profile ]['pro'] ) ) {
				$preset = array_merge( $preset, $profiles[ $profile ]['pro'] );
			}
			$current = (array) get_option( CShield_Settings::OPTION, array() );
			update_option( CShield_Settings::OPTION, array_merge( CShield_Settings::defaults(), $current, $preset ) );
			update_option( self::ONBOARDING, $profile, false );
			$url = add_query_arg( 'cshield-profile', $profile, $url );
		} else {
			update_option( self::ONBOARDING, 'skip', false );
		}

		wp_safe_redirect( $url );
		exit;
	}

	/**
	 * Recommended-but-off suggestions for the dashboard checklist.
	 *
	 * @return array Rows of array( key, label, impact, view ).
	 */
	private function boost_items() {
		$items = array();

		// Attribution only makes sense when copying is not blocked outright.
		if ( empty( $this->o['disable_copy_cut'] ) ) {
			$items[] = array( 'append_attribution', __( 'Turn copies into backlinks', 'copyfend' ), __( 'Every copied paragraph pastes with a link back to you.', 'copyfend' ), 'protection' );
		}
		$items[] = array( 'disable_right_click', __( 'Disable right-click', 'copyfend' ), __( 'Blocks the right-click copy menu.', 'copyfend' ), 'protection' );
		$items[] = array( 'disable_image_drag', __( 'Prevent image dragging', 'copyfend' ), __( 'Images cannot be dragged out of the page to save them.', 'copyfend' ), 'protection' );
		$items[] = array( 'copyright_meta', __( 'Copyright meta tag', 'copyfend' ), __( 'Declares ownership on every page.', 'copyfend' ), 'dmca' );
		$items[] = array( 'rss_attribution', __( 'RSS attribution footer', 'copyfend' ), __( 'Adds your link to every RSS item.', 'copyfend' ), 'dmca' );
		$items[] = array( 'locker_enabled', __( 'Content Locker', 'copyfend' ), __( 'Capture emails by gating your best content.', 'copyfend' ), 'locker' );

		if ( $this->is_pro() ) {
			$items[] = array( 'block_ai_crawlers', __( 'Block AI crawlers', 'copyfend' ), __( 'GPTBot, ClaudeBot, CCBot and more get a 403.', 'copyfend' ), 'scraping' );
			$items[] = array( 'forensic_enabled', __( 'Forensic watermark', 'copyfend' ), __( 'Trace any leak back to the visitor who copied it.', 'copyfend' ), 'forensic' );
			$items[] = array( 'honeypot_enabled', __( 'Honeypot bot-trap', 'copyfend' ), __( 'Catch scrapers that ignore robots.txt.', 'copyfend' ), 'scraping' );
		}

		return $items;
	}

	/**
	 * Verification steps for the "Test your protection" card, from live settings.
	 *
	 * @return array
	 */
	private function test_steps() {
		$o = $this->o;
		if ( empty( $o['enabled'] ) ) {
			return array();
		}

		$steps = array();
		if ( ! empty( $o['disable_right_click'] ) ) {
			$steps[] = __( 'Right-click a paragraph. The menu should not open.', 'copyfend' );
		}
		if ( ! empty( $o['disable_copy_cut'] ) ) {
			$steps[] = __( 'Try to copy a paragraph. A notice should block it.', 'copyfend' );
		} elseif ( ! empty( $o['append_attribution'] ) ) {
			$steps[] = __( 'Copy a paragraph and paste it. Your attribution line appears at the end.', 'copyfend' );
		}
		if ( ! empty( $o['disable_selection'] ) ) {
			$steps[] = __( 'Try to select text. The selection should not stick.', 'copyfend' );
		}
		if ( ! empty( $o['disable_image_drag'] ) ) {
			$steps[] = __( 'Drag an image to your desktop. Nothing should happen.', 'copyfend' );
		}
		if ( ! empty( $o['block_print'] ) ) {
			$steps[] = __( 'Press Ctrl+P. The print preview should be blank.', 'copyfend' );
		}

		return $steps;
	}

	/**
	 * Weighted protection score (0–100) over the layers available to this tier.
	 *
	 * Client-side layers only count while the master switch is on, and blocking
	 * copying outright scores the same as attribution (they are alternatives).
	 *
	 * @return int
	 */
	private function protection_score() {
		$o       = $this->o;
		$enabled = ! empty( $o['enabled'] );

		$items = array(
			array( 25, $enabled ),
			array( 10, $enabled && ! empty( $o['disable_right_click'] ) ),
			array( 10, $enabled && ! empty( $o['disable_image_drag'] ) ),
			array( 25, $enabled && ( ! empty( $o['append_attribution'] ) || ! empty( $o['disable_copy_cut'] ) ) ),
			array( 10, ! empty( $o['copyright_meta'] ) ),
			array( 10, ! empty( $o['rss_attribution'] ) ),
			array( 10, ! empty( $o['locker_enabled'] ) ),
		);
		if ( $this->is_pro() ) {
			$items[] = array( 15, ! empty( $o['block_ai_crawlers'] ) );
			$items[] = array( 10, ! empty( $o['block_bad_bots'] ) || ! empty( $o['rate_limit'] ) );
			$items[] = array( 10, ! empty( $o['honeypot_enabled'] ) );
			$items[] = array( 15, ! empty( $o['forensic_enabled'] ) );
			$items[] = array( 10, ! empty( $o['watermark_enabled'] ) );
		}

		$total = 0;
		$got   = 0;
		foreach ( $items as $item ) {
			$total += $item[0];
			if ( $item[1] ) {
				$got += $item[0];
			}
		}

		return $total ? (int) round( 100 * $got / $total ) : 0;
	}

	/**
	 * A checkbox list bound to an array setting.
	 *
	 * @param string $key   Setting key.
	 * @param array  $items value => label pairs.
	 */
	public function checklist_field( $key, $items ) {
		if ( empty( $items ) ) {
			echo '<p class="cs-hint">' . esc_html__( 'Nothing to show yet.', 'copyfend' ) . '</p>';
			return;
		}
		$saved = array_map( 'strval', (array) ( isset( $this->o[ $key ] ) ? $this->o[ $key ] : array() ) );
		foreach ( $items as $value => $label ) {
			$checked = in_array( (string) $value, $saved, true );
			echo '<div class="cs-row">';
			echo '<div class="cs-row-txt"><b>' . esc_html( $label ) . '</b></div>';
			echo '<label class="cs-switch"><input type="checkbox" name="' . esc_attr( CShield_Settings::OPTION . '[' . $key . '][]' ) . '" value="' . esc_attr( $value ) . '" ' . checked( $checked, true, false ) . ( $this->is_locked( $key ) ? ' disabled' : '' ) . ' /><span class="cs-slider"></span></label>';
			echo '</div>';
		}
	}

	/**
	 * Category choices ( term_id => name ).
	 *
	 * @return array
	 */
	public function category_choices() {
		$out = array();
		foreach ( get_categories( array( 'hide_empty' => false, 'number' => 200 ) ) as $cat ) {
			$out[ (int) $cat->term_id ] = $cat->name;
		}
		return $out;
	}

	/**
	 * Role choices ( slug => display name ).
	 *
	 * @return array
	 */
	public function role_choices() {
		return wp_roles()->get_names();
	}

	/**
	 * Return an inline SVG icon (stroke = currentColor, scales with font size).
	 *
	 * @param string $name Icon name.
	 * @return string
	 */
	private function icon( $name ) {
		$paths = array(
			'grid'   => '<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/>',
			'shield' => '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>',
			'ban'    => '<circle cx="12" cy="12" r="9"/><line x1="5.6" y1="5.6" x2="18.4" y2="18.4"/>',
			'image'  => '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="M21 15l-5-5L5 21"/>',
			'target' => '<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3.5"/>',
			'lock'   => '<rect x="4" y="11" width="16" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
			'search' => '<circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>',
			'file'   => '<path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><path d="M14 3v6h6"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="16" y2="17"/>',
			'link'   => '<path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/>',
			'star'   => '<path d="M12 3l2.6 5.6 6.1.6-4.6 4 1.4 6L12 16.8 6.5 19.2l1.4-6-4.6-4 6.1-.6z"/>',
			'mail'   => '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 6.5L12 13l8.5-6.5"/>',
		);
		$inner = isset( $paths[ $name ] ) ? $paths[ $name ] : '';
		return '<svg class="cs-ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">' . $inner . '</svg>';
	}

	/**
	 * Whether the install can run premium (PRO) code.
	 *
	 * @return bool
	 */
	public function is_pro() {
		return CShield::is_pro();
	}

	/**
	 * Setting keys that belong to PRO features.
	 *
	 * @return array
	 */
	private function pro_keys() {
		return array(
			'block_ai_crawlers',
			'block_bad_bots',
			'rate_limit',
			'truncate_rss',
			'rss_words',
			'forensic_enabled',
			'forensic_log',
			'forensic_log_anonymize_ip',
			'forensic_log_retention',
			'watermark_enabled',
			'watermark_apply_logo',
			'watermark_logo',
			'watermark_apply_text',
			'watermark_text',
			'watermark_position',
			'watermark_opacity',
			'watermark_text_size',
			'watermark_keep_original',
			'honeypot_enabled',
			'honeypot_block',
			'honeypot_canary',
			'protect_exclude_terms',
			'protect_exclude_roles',
		);
	}

	/**
	 * Whether a control is a PRO feature on a free install (so it renders locked).
	 *
	 * @param string $key Setting key.
	 * @return bool
	 */
	private function is_locked( $key ) {
		return ! $this->is_pro() && in_array( $key, $this->pro_keys(), true );
	}

	/**
	 * Freemius upgrade / pricing URL.
	 *
	 * @return string
	 */
	private function upgrade_url() {
		return function_exists( 'cshield_fs' ) ? cshield_fs()->get_upgrade_url() : '#';
	}

	/**
	 * An informational upgrade card for a Pro-only view (free plugin).
	 *
	 * The free plugin contains no Pro code; these cards only describe what the
	 * separate Pro upgrade adds, which the directory guidelines allow.
	 *
	 * @param string $icon  Icon name.
	 * @param string $title Card title.
	 * @param string $desc  Feature description.
	 */
	private function upsell_card( $icon, $title, $desc ) {
		echo '<div class="cs-card cs-pro-card big">';
		echo '<div class="cs-pro-ic">' . $this->icon( $icon ) . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo '<h3>' . esc_html( $title ) . ' <span class="cs-tag pro">PRO</span></h3>';
		echo '<p class="cs-desc">' . esc_html( $desc ) . '</p>';
		echo '<p class="cs-desc">' . esc_html__( 'Available in Copyfend Pro, a separate paid upgrade. This free plugin works fully without it.', 'copyfend' ) . '</p>';
		echo '<a class="cs-btn pro" href="' . esc_url( $this->upgrade_url() ) . '">' . esc_html__( 'See PRO plans', 'copyfend' ) . '</a>';
		echo '</div>';
	}

	/* --------------------------------------------------------------------- */
	/* Render helpers                                                         */
	/* --------------------------------------------------------------------- */

	/**
	 * A labelled toggle switch bound to a setting.
	 *
	 * @param string $key   Setting key.
	 * @param string $label Label.
	 * @param string $desc  Optional description.
	 * @param bool   $pro   Render as a locked PRO control.
	 * @param string $badge Optional guidance badge: 'rec' (recommended) or 'warn' (aggressive).
	 */
	public function toggle( $key, $label, $desc = '', $pro = false, $badge = '' ) {
		$name = CShield_Settings::OPTION . '[' . $key . ']';
		if ( $this->is_locked( $key ) ) {
			$pro = true;
		}
		echo '<div class="cs-row">';
		echo '<div class="cs-row-txt"><b>' . esc_html( $label );
		if ( $pro ) {
			echo ' <span class="cs-tag pro">PRO</span>';
		}
		if ( 'rec' === $badge ) {
			echo ' <span class="cs-tag rec">' . esc_html__( 'Recommended', 'copyfend' ) . '</span>';
		} elseif ( 'warn' === $badge ) {
			echo ' <span class="cs-tag warn">' . esc_html__( 'Aggressive', 'copyfend' ) . '</span>';
		}
		echo '</b>';
		if ( $desc ) {
			echo '<span>' . esc_html( $desc ) . '</span>';
		}
		echo '</div>';
		echo '<label class="cs-switch">';
		echo '<input type="checkbox" name="' . esc_attr( $name ) . '" value="1" ' . checked( ! empty( $this->o[ $key ] ), true, false ) . ( $pro ? ' disabled' : '' ) . ' />';
		echo '<span class="cs-slider"></span></label>';
		echo '</div>';
	}

	/**
	 * A text/email/url field bound to a setting.
	 *
	 * @param string $key   Setting key.
	 * @param string $label Label.
	 * @param string $desc  Optional hint.
	 * @param string $type  Input type: text | email | url.
	 */
	public function text_field( $key, $label, $desc = '', $type = 'text' ) {
		$name = CShield_Settings::OPTION . '[' . $key . ']';
		$val  = isset( $this->o[ $key ] ) ? $this->o[ $key ] : '';
		$type = in_array( $type, array( 'text', 'email', 'url' ), true ) ? $type : 'text';
		echo '<div class="cs-field"><label>' . esc_html( $label ) . '</label>';
		echo '<input type="' . esc_attr( $type ) . '" name="' . esc_attr( $name ) . '" value="' . esc_attr( $val ) . '"' . ( $this->is_locked( $key ) ? ' disabled' : '' ) . ' />';
		if ( $desc ) {
			echo '<div class="cs-hint">' . esc_html( $desc ) . '</div>';
		}
		echo '</div>';
	}

	/**
	 * A number field bound to a setting.
	 *
	 * @param string $key   Setting key.
	 * @param string $label Label.
	 * @param int    $min   Minimum.
	 * @param int    $max   Maximum.
	 */
	public function number_field( $key, $label, $min = 0, $max = 1000 ) {
		$name = CShield_Settings::OPTION . '[' . $key . ']';
		$val  = isset( $this->o[ $key ] ) ? (int) $this->o[ $key ] : 0;
		echo '<div class="cs-field"><label>' . esc_html( $label ) . '</label>';
		echo '<input type="number" min="' . (int) $min . '" max="' . (int) $max . '" class="cs-num" name="' . esc_attr( $name ) . '" value="' . esc_attr( $val ) . '"' . ( $this->is_locked( $key ) ? ' disabled' : '' ) . ' />';
		echo '</div>';
	}

	/**
	 * A select field bound to a setting.
	 *
	 * @param string $key     Setting key.
	 * @param string $label   Label.
	 * @param array  $choices value => label pairs.
	 */
	public function select_field( $key, $label, $choices ) {
		$name = CShield_Settings::OPTION . '[' . $key . ']';
		$cur  = (string) ( isset( $this->o[ $key ] ) ? $this->o[ $key ] : '' );
		echo '<div class="cs-field"><label>' . esc_html( $label ) . '</label>';
		echo '<select name="' . esc_attr( $name ) . '"' . ( $this->is_locked( $key ) ? ' disabled' : '' ) . '>';
		foreach ( $choices as $value => $text ) {
			echo '<option value="' . esc_attr( $value ) . '" ' . selected( $cur, (string) $value, false ) . '>' . esc_html( $text ) . '</option>';
		}
		echo '</select></div>';
	}

	/**
	 * Render the captured-leads table with export / clear actions.
	 */
	private function locker_leads_table() {
		$rows   = CShield_Locker::recent_leads( 100 );
		$export = wp_nonce_url( admin_url( 'admin-post.php?action=cshield_export_leads' ), 'cshield_leads' );
		$clear  = wp_nonce_url( admin_url( 'admin-post.php?action=cshield_clear_leads' ), 'cshield_leads' );

		echo '<p>';
		echo '<a class="button button-primary" href="' . esc_url( $export ) . '">' . esc_html__( 'Export CSV', 'copyfend' ) . '</a> ';
		echo '<a class="button" href="' . esc_url( $clear ) . '" onclick="return confirm(\'' . esc_js( __( 'Delete all captured leads? This cannot be undone.', 'copyfend' ) ) . '\')">' . esc_html__( 'Clear leads', 'copyfend' ) . '</a>';
		echo '</p>';

		if ( empty( $rows ) ) {
			echo '<p class="cs-hint">' . esc_html__( 'No leads captured yet.', 'copyfend' ) . ' ' . esc_html__( 'Leads appear here when a visitor unlocks gated content. Paste the shortcode above into any post to start capturing.', 'copyfend' ) . '</p>';
			return;
		}

		echo '<table class="widefat striped" style="margin-top:8px"><thead><tr>';
		echo '<th>' . esc_html__( 'Email', 'copyfend' ) . '</th>';
		echo '<th>' . esc_html__( 'Page', 'copyfend' ) . '</th>';
		echo '<th>' . esc_html__( 'When', 'copyfend' ) . '</th>';
		echo '</tr></thead><tbody>';
		foreach ( $rows as $r ) {
			$title = $r['post_id'] ? get_the_title( (int) $r['post_id'] ) : '';
			echo '<tr>';
			echo '<td>' . esc_html( $r['email'] ) . '</td>';
			echo '<td>' . esc_html( $title ) . '</td>';
			echo '<td>' . esc_html( $r['created_at'] ) . '</td>';
			echo '</tr>';
		}
		echo '</tbody></table>';
	}

	/**
	 * A checklist of public post types bound to the targeting setting.
	 *
	 * Unchecked = that singular content type is not protected. Before the setting
	 * is ever saved (null) every type is protected by default.
	 */
	private function post_type_checklist() {
		$saved = isset( $this->o['protected_post_types'] ) ? $this->o['protected_post_types'] : null;
		$types = get_post_types( array( 'public' => true ), 'objects' );
		unset( $types['attachment'] );

		foreach ( $types as $type ) {
			$checked = ! is_array( $saved ) || in_array( $type->name, $saved, true );
			echo '<div class="cs-row">';
			echo '<div class="cs-row-txt"><b>' . esc_html( $type->labels->name ) . '</b><span>' . esc_html( $type->name ) . '</span></div>';
			echo '<label class="cs-switch">';
			echo '<input type="checkbox" name="' . esc_attr( CShield_Settings::OPTION . '[protected_post_types][]' ) . '" value="' . esc_attr( $type->name ) . '" ' . checked( $checked, true, false ) . ' />';
			echo '<span class="cs-slider"></span></label>';
			echo '</div>';
		}
	}

	/**
	 * A read-only status row with an "Edit" jump link (dashboard overview).
	 *
	 * @param string $label Label.
	 * @param bool   $on    State.
	 * @param string $view  Target view to jump to.
	 */
	private function status_row( $label, $on, $view ) {
		echo '<div class="cs-row">';
		echo '<div class="cs-row-txt"><b>' . esc_html( $label ) . '</b></div>';
		echo '<span class="cs-state ' . ( $on ? 'on' : 'off' ) . '">' . ( $on ? esc_html__( 'On', 'copyfend' ) : esc_html__( 'Off', 'copyfend' ) ) . '</span>';
		echo '<a class="cs-edit" href="#" data-goto="' . esc_attr( $view ) . '">' . esc_html__( 'Edit', 'copyfend' ) . ' &rsaquo;</a>';
		echo '</div>';
	}

	/* --------------------------------------------------------------------- */
	/* Page                                                                  */
	/* --------------------------------------------------------------------- */

	/**
	 * Render the panel.
	 */
	public function render() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$this->o = $this->settings->all();
		$o       = $this->o;
		$stats   = get_option( 'cshield_stats', array() );
		$blocked = isset( $stats['week_count'] ) ? (int) $stats['week_count'] : 0;
		$saved   = isset( $_GET['settings-updated'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		$copy_stats = get_option( 'cshield_copy_stats', array() );
		$copies     = ( isset( $copy_stats['week'] ) && gmdate( 'oW' ) === $copy_stats['week'] ) ? (int) $copy_stats['week_count'] : 0;

		$profiles  = $this->profiles();
		$onboarded = (string) get_option( self::ONBOARDING, '' );
		$applied   = isset( $_GET['cshield-profile'] ) ? sanitize_key( wp_unslash( $_GET['cshield-profile'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only banner.
		?>
		<div class="cs-app<?php echo $this->is_pro() ? ' cs-is-pro' : ''; ?>">
			<h1 class="screen-reader-text"><?php esc_html_e( 'Copyfend', 'copyfend' ); ?></h1>

			<header class="cs-top">
				<div class="cs-logo">
					<span class="cs-mark"><svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 3l7 2.6v5.6c0 4.6-3.2 7.8-7 9.8-3.8-2-7-5.2-7-9.8V5.6L12 3z" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M9 12l2.2 2.2L15.5 10" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
					<span><?php esc_html_e( 'Copyfend', 'copyfend' ); ?></span>
					<em><?php echo esc_html( 'v' . CSHIELD_VERSION ); ?></em>
				</div>
				<div class="cs-top-right">
					<?php if ( $this->is_pro() ) : ?>
						<span class="cs-pill" style="background:#ecfdf5;color:#047857"><?php esc_html_e( 'PRO', 'copyfend' ); ?></span>
					<?php else : ?>
						<span class="cs-pill"><?php esc_html_e( 'Free plan', 'copyfend' ); ?></span>
						<a class="cs-btn upgrade" href="<?php echo esc_url( $this->upgrade_url() ); ?>"><span class="cs-dot"></span><?php esc_html_e( 'Upgrade to PRO', 'copyfend' ); ?></a>
					<?php endif; ?>
				</div>
			</header>

			<hr class="wp-header-end" style="margin:0;border:0;height:0">

			<?php if ( $saved ) : ?>
				<div class="cs-saved">&#10003; <?php esc_html_e( 'Settings saved.', 'copyfend' ); ?></div>
			<?php endif; ?>

			<div class="cs-shell">
				<nav class="cs-nav">
					<a class="active" href="#" data-view="dashboard"><span class="i"><?php echo $this->icon( 'grid' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Dashboard', 'copyfend' ); ?></a>
					<div class="cs-navgroup"><?php esc_html_e( 'Protection', 'copyfend' ); ?></div>
					<a href="#" data-view="protection"><span class="i"><?php echo $this->icon( 'shield' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Protection', 'copyfend' ); ?></a>
					<a href="#" data-view="rules"><span class="i"><?php echo $this->icon( 'target' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Rules', 'copyfend' ); ?></a>
					<div class="cs-navgroup"><?php esc_html_e( 'Tools', 'copyfend' ); ?></div>
					<a href="#" data-view="locker"><span class="i"><?php echo $this->icon( 'lock' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Content Locker', 'copyfend' ); ?></a>
					<a href="#" data-view="dmca"><span class="i"><?php echo $this->icon( 'file' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'DMCA &amp; Copyright', 'copyfend' ); ?></a>
					<div class="cs-navgroup"><?php esc_html_e( 'Premium', 'copyfend' ); ?></div>
					<a href="#" data-view="scraping"><span class="i"><?php echo $this->icon( 'ban' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Anti-Scraping', 'copyfend' ); ?><?php if ( ! $this->is_pro() ) : ?><span class="cs-lock">PRO</span><?php endif; ?></a>
					<a href="#" data-view="images"><span class="i"><?php echo $this->icon( 'image' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Images', 'copyfend' ); ?><?php if ( ! $this->is_pro() ) : ?><span class="cs-lock">PRO</span><?php endif; ?></a>
					<a href="#" data-view="forensic"><span class="i"><?php echo $this->icon( 'search' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span><?php esc_html_e( 'Forensic', 'copyfend' ); ?><?php if ( ! $this->is_pro() ) : ?><span class="cs-lock">PRO</span><?php endif; ?></a>
				</nav>

				<main class="cs-main">

					<section class="cs-view active" id="view-dashboard">
						<h2 class="cs-h2"><?php esc_html_e( 'Dashboard', 'copyfend' ); ?></h2>
						<p class="cs-sub"><?php esc_html_e( 'Your content is protected. Here is the status at a glance.', 'copyfend' ); ?></p>

						<div class="cs-card cs-welcome<?php echo '' === $onboarded ? '' : ' cs-hide'; ?>" id="cs-welcome">
							<h3><?php esc_html_e( 'Welcome to Copyfend', 'copyfend' ); ?></h3>
							<p class="cs-desc"><?php esc_html_e( 'Pick what best describes this site and we will apply a recommended, SEO-safe setup. You can fine-tune everything later.', 'copyfend' ); ?></p>
							<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
								<?php wp_nonce_field( 'cshield_profile' ); ?>
								<input type="hidden" name="action" value="cshield_apply_profile" />
								<div class="cs-profiles">
									<?php foreach ( $profiles as $pkey => $p ) : ?>
									<button type="submit" name="cshield_profile" value="<?php echo esc_attr( $pkey ); ?>" class="cs-profile">
										<span class="cs-profile-ic"><?php echo $this->icon( $p['icon'] ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
										<b><?php echo esc_html( $p['title'] ); ?></b>
										<span class="d"><?php echo esc_html( $p['desc'] ); ?></span>
									</button>
									<?php endforeach; ?>
								</div>
								<p class="cs-skip"><button type="submit" name="cshield_profile" value="skip" class="cs-linklike"><?php esc_html_e( 'Skip, I will configure it myself', 'copyfend' ); ?></button></p>
							</form>
						</div>

						<?php if ( $applied && isset( $profiles[ $applied ] ) ) : ?>
						<div class="cs-card cs-applied">
							<div class="cs-cardhead">
								<h3>&#10003; <?php esc_html_e( 'Recommended setup applied. Protections enabled:', 'copyfend' ); ?></h3>
								<button type="button" class="cs-dismiss" aria-label="<?php esc_attr_e( 'Dismiss', 'copyfend' ); ?>">&times;</button>
							</div>
							<p class="cs-chips">
								<?php
								$labels = $this->feature_labels();
								$active = array_merge( $profiles[ $applied ]['set'], $this->is_pro() ? $profiles[ $applied ]['pro'] : array() );
								foreach ( $active as $fkey => $fval ) {
									if ( $fval && isset( $labels[ $fkey ] ) ) {
										echo '<span class="cs-chip">' . esc_html( $labels[ $fkey ] ) . '</span>';
									}
								}
								?>
							</p>
							<p class="cs-desc" style="margin:8px 0 0"><?php esc_html_e( 'Scroll down to "Test your protection" to see it working on your site.', 'copyfend' ); ?></p>
						</div>
						<?php endif; ?>

						<?php
						$score = $this->protection_score();
						$band  = $score >= 80 ? 'ok' : ( $score >= 50 ? 'mid' : 'low' );
						if ( empty( $o['enabled'] ) ) {
							$score_msg = __( 'Client-side protection is off. Turn it on to start protecting your content.', 'copyfend' );
						} elseif ( $score >= 80 ) {
							$score_msg = __( 'Strong protection. Your content is well covered.', 'copyfend' );
						} elseif ( $score >= 50 ) {
							$score_msg = __( 'Good coverage. Some recommended layers are still off.', 'copyfend' );
						} else {
							$score_msg = __( 'Your content is lightly protected. Enable the recommended layers below.', 'copyfend' );
						}
						$dash = round( 326.7 * $score / 100, 1 );
						?>
						<div class="cs-card cs-hero">
							<div class="cs-score <?php echo esc_attr( $band ); ?>">
								<svg viewBox="0 0 120 120" aria-hidden="true">
									<circle class="bg" cx="60" cy="60" r="52"/>
									<circle class="fg" cx="60" cy="60" r="52" stroke-dasharray="<?php echo esc_attr( $dash . ' 326.7' ); ?>"/>
								</svg>
								<div class="cs-score-num"><?php echo (int) $score; ?><span>%</span></div>
							</div>
							<div class="cs-hero-txt">
								<h3><?php esc_html_e( 'Protection score', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php echo esc_html( $score_msg ); ?></p>
							</div>
							<div class="cs-hero-stats">
									<div class="hs">
										<b><?php echo esc_html( number_format_i18n( $copies ) ); ?></b>
										<span><?php esc_html_e( 'Copies with attribution (this week)', 'copyfend' ); ?></span>
									</div>
									<?php if ( class_exists( 'CShield_Server' ) ) : ?>
									<div class="hs">
										<b><?php echo esc_html( number_format_i18n( $blocked ) ); ?></b>
										<span><?php esc_html_e( 'Bots / AI blocked (this week)', 'copyfend' ); ?></span>
									</div>
									<?php else : ?>
									<div class="hs">
										<b><?php echo esc_html( number_format_i18n( CShield_Locker::lead_count() ) ); ?></b>
										<span><?php esc_html_e( 'Captured leads', 'copyfend' ); ?></span>
									</div>
									<?php endif; ?>
									<div class="hs">
										<b><?php echo $this->is_pro() ? ( ! empty( $o['forensic_enabled'] ) ? esc_html__( 'On', 'copyfend' ) : esc_html__( 'Off', 'copyfend' ) ) : '&mdash;'; ?></b>
										<span><?php esc_html_e( 'Forensic watermark', 'copyfend' ); ?> <span class="cs-tag pro">PRO</span></span>
								</div>
							</div>
						</div>

						<div class="cs-grid two">
							<div class="cs-card">
								<h3><?php esc_html_e( 'Protection status', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'A quick overview. Click Edit to change a setting.', 'copyfend' ); ?></p>
								<?php
								$this->status_row( __( 'Right-click disabled', 'copyfend' ), ! empty( $o['disable_right_click'] ), 'protection' );
								$this->status_row( __( 'Copy attribution (backlink)', 'copyfend' ), ! empty( $o['append_attribution'] ), 'protection' );
								if ( $this->pro ) {
									$this->status_row( __( 'Block AI crawlers', 'copyfend' ), ! empty( $o['block_ai_crawlers'] ), 'scraping' );
									$this->status_row( __( 'Truncate RSS feed', 'copyfend' ), ! empty( $o['truncate_rss'] ), 'scraping' );
								} else {
									$this->status_row( __( 'Content Locker', 'copyfend' ), ! empty( $o['locker_enabled'] ), 'locker' );
									$this->status_row( __( 'Copyright meta tag', 'copyfend' ), ! empty( $o['copyright_meta'] ), 'dmca' );
								}
								?>
							</div>
							<?php if ( $this->is_pro() && $this->pro ) : ?>
							<div class="cs-card">
								<h3><?php esc_html_e( 'Advanced protection', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Your PRO layers. Click Edit to change a setting.', 'copyfend' ); ?></p>
								<?php
								$this->status_row( __( 'Block AI crawlers & bad bots', 'copyfend' ), ! empty( $o['block_ai_crawlers'] ) || ! empty( $o['block_bad_bots'] ), 'scraping' );
								$this->status_row( __( 'Forensic watermark', 'copyfend' ), ! empty( $o['forensic_enabled'] ), 'forensic' );
								$this->status_row( __( 'Image watermark', 'copyfend' ), ! empty( $o['watermark_enabled'] ), 'images' );
								$this->status_row( __( 'Honeypot bot-trap', 'copyfend' ), ! empty( $o['honeypot_enabled'] ), 'scraping' );
								?>
							</div>
							<?php else : ?>
							<div class="cs-card cs-pro-card">
								<div class="cs-pro-ic"><?php echo $this->icon( 'search' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></div>
								<h3><?php esc_html_e( 'Unlock protection that cannot be bypassed', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Invisible forensic watermark (identify who leaked), server-side anti-scraping, image watermarking, honeypot bot-traps and granular category/role rules.', 'copyfend' ); ?></p>
								<a class="cs-btn pro" href="<?php echo esc_url( $this->upgrade_url() ); ?>"><?php esc_html_e( 'See PRO plans', 'copyfend' ); ?></a>
							</div>
							<?php endif; ?>
						</div>

						<div class="cs-grid two">
							<div class="cs-card">
								<?php
								$boost = $this->boost_items();
								$done  = 0;
								foreach ( $boost as $b ) {
									if ( ! empty( $o[ $b[0] ] ) ) {
										$done++;
									}
								}
								?>
								<div class="cs-cardhead">
									<h3><?php esc_html_e( 'Boost your protection', 'copyfend' ); ?></h3>
									<a href="#" id="cs-change-profile" class="cs-mini"><?php esc_html_e( 'Use a recommended profile', 'copyfend' ); ?> &rsaquo;</a>
								</div>
								<p class="cs-desc">
									<?php
									/* translators: 1: enabled count, 2: total count. */
									echo esc_html( sprintf( __( '%1$d of %2$d recommended protections enabled.', 'copyfend' ), $done, count( $boost ) ) );
									?>
								</p>
								<?php foreach ( $boost as $b ) : $on = ! empty( $o[ $b[0] ] ); ?>
								<div class="cs-check-row">
									<span class="cs-check <?php echo $on ? 'done' : 'todo'; ?>"><?php echo $on ? '&#10003;' : ''; ?></span>
									<div class="cs-row-txt">
										<b class="<?php echo $on ? 'done' : ''; ?>"><?php echo esc_html( $b[1] ); ?></b>
										<span><?php echo esc_html( $b[2] ); ?></span>
									</div>
									<?php if ( ! $on ) : ?>
									<a class="cs-edit" href="#" data-goto="<?php echo esc_attr( $b[3] ); ?>"><?php esc_html_e( 'Enable', 'copyfend' ); ?> &rsaquo;</a>
									<?php endif; ?>
								</div>
								<?php endforeach; ?>
							</div>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Test your protection', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Check each protection on your live site.', 'copyfend' ); ?></p>
								<?php $steps = $this->test_steps(); ?>
								<?php if ( empty( $steps ) ) : ?>
									<p class="cs-testwarn"><?php esc_html_e( 'Client-side protection is disabled. Enable it first.', 'copyfend' ); ?>
										<a class="cs-edit" href="#" data-goto="protection"><?php esc_html_e( 'Enable', 'copyfend' ); ?> &rsaquo;</a></p>
								<?php else : ?>
									<?php if ( ! empty( $o['exclude_admins'] ) ) : ?>
									<p class="cs-testwarn"><?php esc_html_e( 'You are excluded as an administrator. Test in a private or incognito window.', 'copyfend' ); ?></p>
									<?php endif; ?>
									<ol class="cs-teststeps">
										<?php foreach ( $steps as $step ) : ?>
										<li><?php echo esc_html( $step ); ?></li>
										<?php endforeach; ?>
									</ol>
									<a class="cs-btn primary" href="<?php echo esc_url( home_url( '/' ) ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Open my site', 'copyfend' ); ?> &#8599;</a>
								<?php endif; ?>
							</div>
						</div>
					</section>

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

						<section class="cs-view" id="view-protection">
							<h2 class="cs-h2"><?php esc_html_e( 'Protection', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Client-side deterrence. It never breaks forms, accessibility or SEO.', 'copyfend' ); ?></p>
							<div class="cs-card">
								<div class="cs-cardhead">
									<h3><?php esc_html_e( 'Behaviour', 'copyfend' ); ?></h3>
									<a href="#" class="cs-mini cs-enable-all" data-enable="<?php esc_attr_e( 'Enable all', 'copyfend' ); ?>" data-disable="<?php esc_attr_e( 'Disable all', 'copyfend' ); ?>"><?php esc_html_e( 'Enable all', 'copyfend' ); ?></a>
								</div>
								<?php
								$this->toggle( 'enabled', __( 'Enable protection', 'copyfend' ), __( 'Master switch for the client-side layer.', 'copyfend' ) );
								$this->toggle( 'disable_right_click', __( 'Disable right-click menu', 'copyfend' ), __( 'Visitors cannot open the right-click menu on your content.', 'copyfend' ), false, 'rec' );
								$this->toggle( 'disable_selection', __( 'Disable text selection', 'copyfend' ), __( 'Visitors cannot select text with the mouse or keyboard.', 'copyfend' ), false, 'warn' );
								$this->toggle( 'disable_copy_cut', __( 'Block copy / cut entirely', 'copyfend' ), __( 'Copying and cutting text is fully blocked.', 'copyfend' ), false, 'warn' );
								$this->toggle( 'disable_shortcuts', __( 'Block keyboard shortcuts (Ctrl+C / X / A / S / U)', 'copyfend' ), __( 'Blocks Ctrl+C, Ctrl+X, Ctrl+A, Ctrl+S and Ctrl+U.', 'copyfend' ), false, 'warn' );
								$this->toggle( 'disable_image_drag', __( 'Prevent image dragging', 'copyfend' ), __( 'Images cannot be dragged out of the page to save them.', 'copyfend' ), false, 'rec' );
								$this->toggle( 'block_print', __( 'Block printing', 'copyfend' ), __( 'Blocks printing and Save as PDF.', 'copyfend' ) );
								$this->toggle( 'append_attribution', __( 'Append source attribution on copy', 'copyfend' ), __( 'Copied text is pasted with a "Source: URL" line at the end.', 'copyfend' ), false, 'rec' );
								$this->toggle( 'exclude_admins', __( 'Exclude administrators', 'copyfend' ), __( 'Administrators browse the site without any protection.', 'copyfend' ), false, 'rec' );
								$this->toggle( 'allow_search_bots', __( 'Never block search engines (SEO-safe)', 'copyfend' ), __( 'Search engines always see the page without protection.', 'copyfend' ), false, 'rec' );
								?>
							</div>
							<div class="cs-card">
								<h3><?php esc_html_e( 'Texts', 'copyfend' ); ?></h3>
								<?php
								$this->text_field( 'attribution_text', __( 'Attribution text', 'copyfend' ), __( 'Use {url} for the page URL.', 'copyfend' ) );
								$this->text_field( 'notice_message', __( 'Notice message', 'copyfend' ) );
								?>
							</div>
						</section>

						<section class="cs-view" id="view-scraping">
							<h2 class="cs-h2"><?php esc_html_e( 'Anti-Scraping', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Server-side protection. Cannot be bypassed by disabling JavaScript.', 'copyfend' ); ?></p>
							<?php
							if ( $this->pro ) {
								$this->pro->render_scraping( $o );
							} else {
								$this->upsell_card( 'ban', __( 'Anti-Scraping', 'copyfend' ), __( 'Block AI crawlers and known scraping tools, throttle aggressive IPs, truncate your RSS feed, and trap misbehaving bots with a honeypot.', 'copyfend' ) );
							}
							?>
						</section>

						<section class="cs-view" id="view-images">
							<h2 class="cs-h2"><?php esc_html_e( 'Images', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Watermark images automatically on upload.', 'copyfend' ); ?></p>
							<?php
							if ( $this->pro ) {
								$this->pro->render_images( $o );
							} else {
								$this->upsell_card( 'image', __( 'Image watermark', 'copyfend' ), __( 'Automatically stamp a logo or text watermark on new uploads, keeping a backup of the original so you can restore it anytime.', 'copyfend' ) );
							}
							?>
						</section>

						<section class="cs-view" id="view-rules">
							<h2 class="cs-h2"><?php esc_html_e( 'Rules', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Choose exactly where the client-side protection applies.', 'copyfend' ); ?></p>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Protected content types', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Turn a type off to leave those single pages unprotected. Archives and the homepage stay protected.', 'copyfend' ); ?></p>
								<?php $this->post_type_checklist(); ?>
							</div>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Per-post override', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'On each post or page edit screen, use the "Copyfend" box (sidebar) to force protection On or Off for that single item.', 'copyfend' ); ?></p>
							</div>

							<?php
							if ( $this->pro ) {
								$this->pro->render_rules_extras( $o );
							} else {
								$this->upsell_card( 'target', __( 'Exclude categories & user roles', 'copyfend' ), __( 'Skip protection for specific categories or for logged-in users with certain roles.', 'copyfend' ) );
							}
							?>
						</section>

						<section class="cs-view" id="view-locker">
							<h2 class="cs-h2"><?php esc_html_e( 'Content Locker', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Gate content behind an email (capture leads) or a password. Rendered server-side, so it cannot be revealed with view-source.', 'copyfend' ); ?></p>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Enable', 'copyfend' ); ?></h3>
								<?php $this->toggle( 'locker_enabled', __( 'Enable content locker shortcodes', 'copyfend' ) ); ?>
							</div>

							<div class="cs-card">
								<h3><?php esc_html_e( 'How to use', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Wrap the content you want to protect in a shortcode, inside any post or page:', 'copyfend' ); ?></p>
								<p><strong><?php esc_html_e( 'Email gate (captures a lead):', 'copyfend' ); ?></strong></p>
								<textarea readonly rows="3" class="cs-dmca-output" id="cs-sc-gate">[cshield_gate]
<?php esc_html_e( 'Your protected content goes here…', 'copyfend' ); ?>
[/cshield_gate]</textarea>
								<p><button type="button" class="button cs-copy-sc" data-target="cs-sc-gate" data-copied="<?php esc_attr_e( 'Copied!', 'copyfend' ); ?>"><?php esc_html_e( 'Copy shortcode', 'copyfend' ); ?></button></p>
								<p style="margin-top:12px"><strong><?php esc_html_e( 'Password lock:', 'copyfend' ); ?></strong></p>
								<textarea readonly rows="3" class="cs-dmca-output" id="cs-sc-lock">[cshield_lock password="your-password"]
<?php esc_html_e( 'Your protected content goes here…', 'copyfend' ); ?>
[/cshield_lock]</textarea>
								<p><button type="button" class="button cs-copy-sc" data-target="cs-sc-lock" data-copied="<?php esc_attr_e( 'Copied!', 'copyfend' ); ?>"><?php esc_html_e( 'Copy shortcode', 'copyfend' ); ?></button></p>
							</div>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Gate texts', 'copyfend' ); ?></h3>
								<?php
								$this->text_field( 'locker_gate_title', __( 'Email gate title', 'copyfend' ) );
								$this->text_field( 'locker_gate_desc', __( 'Email gate description', 'copyfend' ) );
								$this->text_field( 'locker_gate_button', __( 'Unlock button text', 'copyfend' ) );
								$this->text_field( 'locker_lock_title', __( 'Password lock title', 'copyfend' ) );
								$this->text_field( 'locker_lock_desc', __( 'Password lock description', 'copyfend' ) );
								?>
							</div>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Captured leads', 'copyfend' ); ?></h3>
								<?php $this->locker_leads_table(); ?>
							</div>
						</section>

						<section class="cs-view" id="view-dmca">
							<h2 class="cs-h2"><?php esc_html_e( 'DMCA &amp; Copyright', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Declare ownership, add attribution, and generate a takedown notice when someone steals your work.', 'copyfend' ); ?></p>

							<div class="cs-card">
								<h3><?php esc_html_e( 'Copyright registry', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Used in your copyright meta tag, RSS attribution and DMCA notices.', 'copyfend' ); ?></p>
								<?php
								$this->text_field( 'copyright_holder', __( 'Copyright holder', 'copyfend' ), __( 'Leave empty to use the site name.', 'copyfend' ) );
								$this->text_field( 'copyright_email', __( 'Contact email', 'copyfend' ), '', 'email' );
								$this->text_field( 'copyright_license', __( 'License', 'copyfend' ), __( 'e.g. All rights reserved, CC BY-NC 4.0…', 'copyfend' ) );
								$this->toggle( 'copyright_meta', __( 'Add a copyright meta tag to the page head', 'copyfend' ) );
								$this->toggle( 'rss_attribution', __( 'Add an attribution footer to RSS feed items', 'copyfend' ), __( 'When scrapers republish your feed, your link comes with it.', 'copyfend' ) );
								?>
							</div>

							<div class="cs-card" id="cs-dmca" data-site="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>">
								<h3><?php esc_html_e( 'DMCA takedown notice generator', 'copyfend' ); ?></h3>
								<p class="cs-desc"><?php esc_html_e( 'Fill in the details and generate a ready-to-send notice. Nothing leaves your browser.', 'copyfend' ); ?></p>
								<div class="cs-field">
									<label for="cs-dmca-infringing"><?php esc_html_e( 'Infringing URL (the copy)', 'copyfend' ); ?></label>
									<input type="url" id="cs-dmca-infringing" placeholder="https://thief.example/stolen-post" />
								</div>
								<div class="cs-field">
									<label for="cs-dmca-original"><?php esc_html_e( 'Your original URL', 'copyfend' ); ?></label>
									<input type="url" id="cs-dmca-original" placeholder="<?php echo esc_attr( home_url( '/' ) ); ?>" />
								</div>
								<div class="cs-field">
									<label for="cs-dmca-work"><?php esc_html_e( 'Description of the work (optional)', 'copyfend' ); ?></label>
									<input type="text" id="cs-dmca-work" placeholder="<?php esc_attr_e( 'e.g. My article, published on …', 'copyfend' ); ?>" />
								</div>
								<p><button type="button" class="button button-primary" id="cs-dmca-generate"><?php esc_html_e( 'Generate notice', 'copyfend' ); ?></button></p>
								<textarea id="cs-dmca-output" class="cs-dmca-output" rows="14" readonly placeholder="<?php esc_attr_e( 'Your DMCA notice will appear here…', 'copyfend' ); ?>"></textarea>
								<p>
									<button type="button" class="button" id="cs-dmca-copy"><?php esc_html_e( 'Copy', 'copyfend' ); ?></button>
									<button type="button" class="button" id="cs-dmca-download"><?php esc_html_e( 'Download .txt', 'copyfend' ); ?></button>
								</p>
							</div>
						</section>

						<section class="cs-view" id="view-forensic">
							<h2 class="cs-h2"><?php esc_html_e( 'Forensic', 'copyfend' ); ?></h2>
							<p class="cs-sub"><?php esc_html_e( 'Trace leaks back to the exact visitor who copied your content.', 'copyfend' ); ?></p>
							<?php
							if ( $this->pro ) {
								$this->pro->render_forensic( $o );
							} else {
								$this->upsell_card( 'search', __( 'Forensic watermark', 'copyfend' ), __( 'Add an invisible per-visitor fingerprint to your content and trace any leak back to the exact visitor who copied it, with a privacy-first access log.', 'copyfend' ) );
							}
							?>
						</section>

						<div class="cs-savebar">
							<?php submit_button( __( 'Save changes', 'copyfend' ), 'primary cs-save', 'submit', false ); ?>
						</div>
					</form>

				</main>
			</div>
		</div>
		<?php
	}
}
