<?php

/**
 * Admin settings and onboarding UI.
 *
 * @package Parkstatic
 */
declare (strict_types = 1);
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Renders the plugin admin page and handles the Start action.
 */
final class Parkstatic_Admin_Page {
    /** @var Parkstatic_Plugin */
    private $plugin;

    /** @var Parkstatic_Onboarding */
    private $onboarding;

    public function __construct( Parkstatic_Plugin $plugin ) {
        $this->plugin = $plugin;
        add_action( 'admin_menu', array($this, 'register_menu') );
        // Freemius activation mode strips plugin submenus after registration; restore ours.
        add_action( 'admin_menu', array($this, 'reregister_submenus_after_freemius'), 1000000000 );
        add_filter( 'admin_body_class', array($this, 'admin_body_class') );
        add_action( 'admin_init', array($this, 'handle_static_mode_save') );
        add_action( 'admin_init', array($this, 'handle_metadata_save') );
        add_action( 'admin_init', array($this, 'maybe_redirect_after_activation') );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_assets') );
        add_filter( 'plugin_action_links_' . plugin_basename( PARKSTATIC_PLUGIN_FILE ), array($this, 'add_settings_link') );
    }

    public function register_menu() : void {
        $this->register_full_menu();
    }

    private function register_full_menu() : void {
        add_menu_page(
            __( 'Parkstatic', 'parkstatic' ),
            __( 'Parkstatic', 'parkstatic' ),
            'manage_options',
            'parkstatic-deploy',
            array($this, 'render_page'),
            'dashicons-upload',
            80
        );
        // Same slug as the parent so WordPress deduplicates this entry; the top-level
        // menu item then opens Deploy directly.
        add_submenu_page(
            'parkstatic-deploy',
            __( 'Deploy', 'parkstatic' ),
            __( 'Deploy', 'parkstatic' ),
            'manage_options',
            'parkstatic-deploy',
            array($this, 'render_page')
        );
        add_submenu_page(
            'parkstatic-deploy',
            __( 'Settings', 'parkstatic' ),
            __( 'Settings', 'parkstatic' ),
            'manage_options',
            'parkstatic-settings',
            array($this, 'render_metadata_page')
        );
    }

    /**
     * Freemius replaces the top-level menu during opt-in and clears every
     * submenu under the plugin slug, which makes direct links like
     * admin.php?page=parkstatic-deploy fail with "Sorry, you are not allowed
     * to access this page." Re-add our pages only when they were removed.
     */
    public function reregister_submenus_after_freemius() : void {
        if ( $this->has_submenu_page( 'parkstatic-deploy', 'parkstatic-deploy' ) && $this->has_submenu_page( 'parkstatic-deploy', 'parkstatic-settings' ) ) {
            return;
        }
        if ( !$this->has_top_level_menu_page( 'parkstatic-deploy' ) ) {
            $this->register_full_menu();
            return;
        }
        if ( !$this->has_submenu_page( 'parkstatic-deploy', 'parkstatic-deploy' ) ) {
            add_submenu_page(
                'parkstatic-deploy',
                __( 'Deploy', 'parkstatic' ),
                __( 'Deploy', 'parkstatic' ),
                'manage_options',
                'parkstatic-deploy',
                array($this, 'render_page')
            );
        }
        if ( !$this->has_submenu_page( 'parkstatic-deploy', 'parkstatic-settings' ) ) {
            add_submenu_page(
                'parkstatic-deploy',
                __( 'Settings', 'parkstatic' ),
                __( 'Settings', 'parkstatic' ),
                'manage_options',
                'parkstatic-settings',
                array($this, 'render_metadata_page')
            );
        }
    }

    /**
     * @param string $parent_slug Parent menu slug.
     * @param string $menu_slug   Submenu slug.
     */
    private function has_submenu_page( string $parent_slug, string $menu_slug ) : bool {
        global $submenu;
        if ( !isset( $submenu[$parent_slug] ) || !is_array( $submenu[$parent_slug] ) ) {
            return false;
        }
        foreach ( $submenu[$parent_slug] as $item ) {
            if ( isset( $item[2] ) && $menu_slug === $item[2] ) {
                return true;
            }
        }
        return false;
    }

    private function has_top_level_menu_page( string $menu_slug ) : bool {
        global $menu;
        if ( !is_array( $menu ) ) {
            return false;
        }
        foreach ( $menu as $item ) {
            if ( isset( $item[2] ) && $menu_slug === $item[2] ) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param string[] $links Existing plugin action links.
     * @return string[]
     */
    public function add_settings_link( array $links ) : array {
        // Assign inside a nested is__premium_only() block (never inline) so the
        // Freemius preprocessor removes the premium-only call from the free build
        // and leaves `$defer_settings = false;` — the free build always links to
        // its own Settings page.
        $defer_settings = false;
        $url = ( $defer_settings ? $this->get_primary_landing_url() : admin_url( 'admin.php?page=parkstatic-settings' ) );
        $label = ( $defer_settings ? __( 'Deploy', 'parkstatic' ) : __( 'Settings', 'parkstatic' ) );
        array_unshift( $links, sprintf( '<a href="%s">%s</a>', esc_url( $url ), esc_html( $label ) ) );
        return $links;
    }

    public function enqueue_assets( string $hook_suffix ) : void {
        $is_deploy = in_array( $hook_suffix, array('parkstatic_page_parkstatic-deploy', 'toplevel_page_parkstatic-deploy'), true );
        $is_settings = 'parkstatic_page_parkstatic-settings' === $hook_suffix;
        if ( !$is_deploy && !$is_settings ) {
            return;
        }
        $this->enqueue_admin_assets();
    }

    private function enqueue_admin_assets() : void {
        wp_enqueue_media();
        $admin_css_path = dirname( PARKSTATIC_PLUGIN_FILE ) . '/assets/admin.css';
        $admin_js_path = dirname( PARKSTATIC_PLUGIN_FILE ) . '/assets/admin.js';
        wp_enqueue_style(
            'parkstatic-admin',
            plugins_url( 'assets/admin.css', PARKSTATIC_PLUGIN_FILE ),
            array(),
            ( file_exists( $admin_css_path ) ? (string) filemtime( $admin_css_path ) : PARKSTATIC_VERSION )
        );
        wp_enqueue_script(
            'parkstatic-admin',
            plugins_url( 'assets/admin.js', PARKSTATIC_PLUGIN_FILE ),
            array('jquery', 'media-editor'),
            ( file_exists( $admin_js_path ) ? (string) filemtime( $admin_js_path ) : PARKSTATIC_VERSION ),
            true
        );
        wp_localize_script( 'parkstatic-admin', 'parkstaticAdmin', array(
            'selectImage'  => __( 'Select image', 'parkstatic' ),
            'removeImage'  => __( 'Remove', 'parkstatic' ),
            'showSecret'   => __( 'Show', 'parkstatic' ),
            'hideSecret'   => __( 'Hide', 'parkstatic' ),
            'copiedSecret' => __( 'Copied!', 'parkstatic' ),
        ) );
    }

    /**
     * @param string $classes Space-separated admin body classes.
     * @return string
     */
    public function admin_body_class( string $classes ) : string {
        return $classes;
    }

    private function is_parkstatic_admin_page() : bool {
        if ( !isset( $_GET['page'] ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin screen routing only.
            return false;
        }
        $page = sanitize_key( wp_unslash( (string) $_GET['page'] ) );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin screen routing only.
        return 0 === strpos( $page, 'parkstatic-' );
    }

    private function is_deploy_admin_page() : bool {
        if ( !isset( $_GET['page'] ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin screen routing only.
            return false;
        }
        return 'parkstatic-deploy' === sanitize_key( wp_unslash( (string) $_GET['page'] ) );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin screen routing only.
    }

    public function maybe_redirect_after_activation() : void {
        if ( !get_transient( 'parkstatic_activation_redirect' ) ) {
            return;
        }
        delete_transient( 'parkstatic_activation_redirect' );
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- standard multisite activation query arg.
        if ( isset( $_GET['activate-multi'] ) ) {
            return;
        }
        wp_safe_redirect( $this->get_primary_landing_url() );
        exit;
    }

    /**
     * Default screen after plugin activation: the Deploy screen.
     */
    private function get_primary_landing_url() : string {
        return admin_url( 'admin.php?page=parkstatic-deploy' );
    }

    /**
     * Admin URL for the Deploy screen.
     */
    private function get_deploy_admin_url() : string {
        $url = menu_page_url( 'parkstatic-deploy', false );
        if ( is_string( $url ) && '' !== $url ) {
            return $url;
        }
        return admin_url( 'admin.php?page=parkstatic-deploy' );
    }

    /**
     * Label for the static front-end mode. Premium serves the user's deployed
     * site ("Your website"); the free build serves a bundled demo ("Test
     * site"). The premium branch is stripped from the free build.
     */
    private function frontend_static_label() : string {
        return __( 'Test site', 'parkstatic' );
    }

    /**
     * Description shown under the static front-end mode option.
     */
    private function frontend_static_description( bool $static_exists ) : string {
        return __( 'Serve the bundled demo site at your domain root so you can preview static front-end mode.', 'parkstatic' );
    }

    public function handle_static_mode_save() : void {
        if ( !isset( $_POST['parkstatic_save_static_mode'] ) ) {
            return;
        }
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        check_admin_referer( 'parkstatic_static_mode' );
        $enable = isset( $_POST['parkstatic_static_enabled'] ) && '1' === sanitize_text_field( wp_unslash( (string) $_POST['parkstatic_static_enabled'] ) );
        if ( $enable ) {
            $result = Parkstatic_Static_Site_Switcher::enable();
            if ( is_wp_error( $result ) ) {
                $this->redirect_with_settings_message( 'parkstatic_static_mode_failed', $result->get_error_message(), 'error' );
            }
            $this->redirect_with_settings_message( 'parkstatic_static_mode_enabled', sprintf( 
                /* translators: %s: static front-end label */
                __( '%s is now live at the site root. wp-admin still uses WordPress.', 'parkstatic' ),
                $this->frontend_static_label()
             ), 'success' );
        } else {
            Parkstatic_Static_Site_Switcher::disable();
            $this->redirect_with_settings_message( 'parkstatic_static_mode_disabled', __( 'WordPress site mode is on.', 'parkstatic' ), 'success' );
        }
    }

    public function handle_metadata_save() : void {
        if ( !isset( $_POST['parkstatic_save_settings'] ) ) {
            return;
        }
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        check_admin_referer( 'parkstatic_settings' );
        $title_enabled = isset( $_POST[Parkstatic_Meta_Injector::OPTION_TITLE_ENABLED] ) && '1' === sanitize_text_field( wp_unslash( (string) $_POST[Parkstatic_Meta_Injector::OPTION_TITLE_ENABLED] ) );
        $description_enabled = isset( $_POST[Parkstatic_Meta_Injector::OPTION_DESCRIPTION_ENABLED] ) && '1' === sanitize_text_field( wp_unslash( (string) $_POST[Parkstatic_Meta_Injector::OPTION_DESCRIPTION_ENABLED] ) );
        $favicon_enabled = isset( $_POST[Parkstatic_Meta_Injector::OPTION_FAVICON_ENABLED] ) && '1' === sanitize_text_field( wp_unslash( (string) $_POST[Parkstatic_Meta_Injector::OPTION_FAVICON_ENABLED] ) );
        $site_title = ( isset( $_POST['blogname'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['blogname'] ) ) : '' );
        $tagline = ( isset( $_POST['blogdescription'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['blogdescription'] ) ) : '' );
        $site_icon = ( isset( $_POST['site_icon'] ) ? absint( $_POST['site_icon'] ) : 0 );
        update_option( 'blogname', $site_title, true );
        update_option( 'blogdescription', $tagline, true );
        update_option( 'site_icon', $site_icon, true );
        update_option( Parkstatic_Meta_Injector::OPTION_TITLE_ENABLED, $title_enabled, false );
        update_option( Parkstatic_Meta_Injector::OPTION_DESCRIPTION_ENABLED, $description_enabled, false );
        update_option( Parkstatic_Meta_Injector::OPTION_FAVICON_ENABLED, $favicon_enabled, false );
        $this->redirect_with_settings_message(
            'parkstatic_settings_saved',
            __( 'Settings saved.', 'parkstatic' ),
            'success',
            'parkstatic-settings'
        );
    }

    /**
     * Redirect after form handling so admin notices are shown once.
     */
    private function redirect_with_settings_message(
        string $code,
        string $message,
        string $type,
        string $page = 'parkstatic-deploy'
    ) : void {
        add_settings_error(
            'parkstatic',
            $code,
            $message,
            $type
        );
        set_transient( 'settings_errors', get_settings_errors(), 30 );
        wp_safe_redirect( admin_url( 'admin.php?page=' . $page ) );
        exit;
    }

    private function render_static_mode_section() : void {
        $enabled = Parkstatic_Static_Site_Switcher::is_enabled();
        $static_exists = Parkstatic_Static_Site_Switcher::static_export_exists();
        ?>
		<div class="parkstatic-deploy__card">
			<div class="parkstatic-deploy__card-header">
				<div>
					<h2 class="parkstatic-deploy__card-title"><?php 
        esc_html_e( 'Front-end mode', 'parkstatic' );
        ?></h2>
					<p class="parkstatic-deploy__card-lead">
						<?php 
        esc_html_e( 'Choose what visitors see at your site root. wp-admin always stays on WordPress.', 'parkstatic' );
        ?>
					</p>
				</div>
				<span
					class="parkstatic-deploy__live-badge <?php 
        echo ( $enabled ? 'is-static' : 'is-wordpress' );
        ?>"
					id="parkstatic-deploy-live-badge"
				>
					<?php 
        echo ( $enabled ? esc_html( sprintf( 
            /* translators: %s: static front-end label */
            __( 'Currently serving %s', 'parkstatic' ),
            $this->frontend_static_label()
         ) ) : esc_html__( 'Currently serving WordPress', 'parkstatic' ) );
        ?>
				</span>
			</div>

			<form method="post" id="parkstatic-static-mode-form">
				<?php 
        wp_nonce_field( 'parkstatic_static_mode' );
        ?>

				<div class="parkstatic-deploy__mode-choices">
					<div class="parkstatic-deploy__mode-grid" role="radiogroup" aria-label="<?php 
        esc_attr_e( 'Front-end mode', 'parkstatic' );
        ?>">
						<label class="parkstatic-deploy__mode-option">
							<input
								type="radio"
								name="parkstatic_static_enabled"
								value="0"
								<?php 
        checked( !$enabled );
        ?>
							/>
							<span class="parkstatic-deploy__mode-card">
								<strong><?php 
        esc_html_e( 'WordPress', 'parkstatic' );
        ?></strong>
								<span><?php 
        esc_html_e( 'Your theme and plugins handle the front end as usual.', 'parkstatic' );
        ?></span>
							</span>
						</label>

						<label class="parkstatic-deploy__mode-option<?php 
        echo ( $static_exists ? '' : ' is-disabled' );
        ?>">
							<input
								type="radio"
								name="parkstatic_static_enabled"
								value="1"
								<?php 
        checked( $enabled );
        ?>
								<?php 
        disabled( !$static_exists );
        ?>
							/>
							<span class="parkstatic-deploy__mode-card">
								<strong><?php 
        echo esc_html( $this->frontend_static_label() );
        ?></strong>
								<span><?php 
        echo esc_html( $this->frontend_static_description( $static_exists ) );
        ?></span>
							</span>
						</label>
					</div>
				</div>

				<div class="parkstatic-deploy__form-foot">
					<?php 
        ?>
					<div class="parkstatic-deploy__actions">
						<?php 
        submit_button(
            __( 'Save changes', 'parkstatic' ),
            'primary',
            'parkstatic_save_static_mode',
            false,
            array(
                'id'       => 'parkstatic-save-static-mode',
                'disabled' => 'disabled',
            )
        );
        ?>
						<span class="parkstatic-deploy__hint is-unsaved" id="parkstatic-static-mode-hint" hidden>
							<?php 
        esc_html_e( 'You have unsaved changes.', 'parkstatic' );
        ?>
						</span>
					</div>
				</div>
			</form>
		</div>
		<?php 
    }

    public function render_page() : void {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
		<div class="wrap">
			<h1><?php 
        esc_html_e( 'Deploy', 'parkstatic' );
        ?></h1>

			<?php 
        settings_errors( 'parkstatic' );
        ?>

			<?php 
        $this->render_general_tab();
        ?>
		</div>
		<?php 
    }

    public function render_metadata_page() : void {
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
		<div class="wrap">
			<h1><?php 
        esc_html_e( 'Settings', 'parkstatic' );
        ?></h1>

			<?php 
        settings_errors( 'parkstatic' );
        ?>

			<div class="parkstatic-settings">
				<?php 
        $this->render_metadata_tab();
        ?>
				<?php 
        $this->render_pro_card();
        ?>
			</div>
		</div>
		<?php 
    }

    private function render_general_tab() : void {
        ?>
		<div class="parkstatic-deploy">
			<?php 
        $this->render_static_mode_section();
        ?>
			<?php 
        ?>
			<?php 
        $this->render_pro_card();
        ?>
		</div>

		<?php 
    }

    /**
     * Promo card for the paid Parkstatic plan. This is the only reference to the
     * paid offering in the plugin: the features it lists are delivered by the
     * external build/deploy service and the separate Pro plugin, not unlocked
     * inside this plugin. Both links open the website/checkout in a new tab.
     */
    private function render_pro_card() : void {
        if ( !parkstatic_fs()->is_free_plan() ) {
            return;
        }
        $checkout_url = ( defined( 'PARKSTATIC_CHECKOUT_URL' ) ? PARKSTATIC_CHECKOUT_URL : '' );
        $more_url = ( defined( 'PARKSTATIC_PRO_URL' ) ? PARKSTATIC_PRO_URL : '' );
        if ( '' === $checkout_url && '' === $more_url ) {
            return;
        }
        $features = array(
            __( 'Automatic deployment — publish your prebuilt static site straight from GitHub on every push.', 'parkstatic' ),
            __( 'Multi-page deploys — publish your entire static site, not just a single landing page.', 'parkstatic' ),
            __( 'Custom Open Graph tags — create and edit og-tags for richer social previews.', 'parkstatic' ),
            __( 'Version history — keep past deploys, activate manually, and roll back to any previous release.', 'parkstatic' )
        );
        ?>
		<div class="parkstatic-deploy__card parkstatic-pro">
			<h2 class="parkstatic-deploy__card-title"><?php 
        esc_html_e( 'Publish your real site with Parkstatic Premium', 'parkstatic' );
        ?></h2>

			<p class="parkstatic-deploy__card-lead">
				<strong><?php 
        esc_html_e( 'Subscribe to Parkstatic Premium to deploy your prebuilt static site automatically and control how your pages appear when shared.', 'parkstatic' );
        ?></strong>
			</p>

			<div class="parkstatic-pro__actions">
				<?php 
        if ( '' !== $checkout_url ) {
            ?>
					<a href="<?php 
            echo esc_url( $checkout_url );
            ?>" class="button button-primary" target="_blank" rel="noopener noreferrer">
						<?php 
            esc_html_e( 'Upgrade Now', 'parkstatic' );
            ?>
					</a>
				<?php 
        }
        ?>
				<?php 
        if ( '' !== $more_url ) {
            ?>
					<a href="<?php 
            echo esc_url( $more_url );
            ?>" class="button" target="_blank" rel="noopener noreferrer">
						<?php 
            esc_html_e( 'Find out more', 'parkstatic' );
            ?>
					</a>
				<?php 
        }
        ?>
			</div>

			<ul class="parkstatic-pro__features">
				<?php 
        foreach ( $features as $feature ) {
            ?>
					<li><?php 
            echo esc_html( $feature );
            ?></li>
				<?php 
        }
        ?>
			</ul>
		</div>
		<?php 
    }

    private function render_metadata_tab() : void {
        $site_title = get_option( 'blogname', '' );
        $tagline = get_option( 'blogdescription', '' );
        $site_icon = (int) get_option( 'site_icon', 0 );
        $static_enabled = Parkstatic_Static_Site_Switcher::is_enabled();
        $title_enabled = Parkstatic_Meta_Injector::is_field_enabled( Parkstatic_Meta_Injector::OPTION_TITLE_ENABLED );
        $description_enabled = Parkstatic_Meta_Injector::is_field_enabled( Parkstatic_Meta_Injector::OPTION_DESCRIPTION_ENABLED );
        $favicon_enabled = Parkstatic_Meta_Injector::is_field_enabled( Parkstatic_Meta_Injector::OPTION_FAVICON_ENABLED );
        ?>
		<?php 
        if ( !$static_enabled ) {
            ?>
			<div class="parkstatic-settings__banner" role="status">
				<p>
					<?php 
            $deploy_link = sprintf( '<a href="%s">%s</a>', esc_url( $this->get_deploy_admin_url() ), esc_html__( 'Deploy', 'parkstatic' ) );
            echo wp_kses_post( sprintf( 
                /* translators: %s: Deploy settings page link */
                __( 'These settings apply on the front end once a static site is enabled on the %s page.', 'parkstatic' ),
                $deploy_link
             ) );
            ?>
				</p>
			</div>
		<?php 
        }
        ?>

		<form method="post" id="parkstatic-settings-form">
			<?php 
        wp_nonce_field( 'parkstatic_settings' );
        ?>

			<div class="parkstatic-settings__card">
				<h2 class="parkstatic-settings__card-title"><?php 
        esc_html_e( 'Site metadata', 'parkstatic' );
        ?></h2>
				<p class="parkstatic-settings__card-lead">
					<?php 
        esc_html_e( 'Edit any value and enable it to override your static build. Disabled fields keep the build\'s original values.', 'parkstatic' );
        ?>
				</p>

				<div class="parkstatic-meta-fields">
					<?php 
        $this->render_meta_field_row(
            'blogname',
            __( 'Site title', 'parkstatic' ),
            __( 'Shown in the browser tab.', 'parkstatic' ),
            'text',
            ( is_string( $site_title ) ? $site_title : '' ),
            'parkstatic-site-title',
            Parkstatic_Meta_Injector::OPTION_TITLE_ENABLED,
            $title_enabled
        );
        $this->render_meta_field_row(
            'blogdescription',
            __( 'Site description', 'parkstatic' ),
            __( 'Short summary for search results.', 'parkstatic' ),
            'textarea',
            ( is_string( $tagline ) ? $tagline : '' ),
            'parkstatic-site-tagline',
            Parkstatic_Meta_Injector::OPTION_DESCRIPTION_ENABLED,
            $description_enabled
        );
        $this->render_meta_media_field_row(
            'site_icon',
            __( 'Site icon', 'parkstatic' ),
            __( 'Favicon shown in browser tabs.', 'parkstatic' ),
            $site_icon,
            'parkstatic-site-icon',
            __( 'Select site icon', 'parkstatic' ),
            Parkstatic_Meta_Injector::OPTION_FAVICON_ENABLED,
            $favicon_enabled
        );
        ?>
				</div>

				<div class="parkstatic-settings__card-foot">
					<div class="parkstatic-settings__actions">
						<?php 
        submit_button(
            __( 'Save settings', 'parkstatic' ),
            'primary',
            'parkstatic_save_settings',
            false
        );
        ?>
					</div>
				</div>
			</div>


			<?php 
        ?>
		</form>
		<?php 
    }

    /**
     * Renders a text or textarea metadata field row with a per-field enable toggle.
     *
     * @param string $input_name  Form input name attribute.
     * @param string $label       Visible field label.
     * @param string $hint        Hint text shown below the input.
     * @param string $type        'text' or 'textarea'.
     * @param string $value       Current stored value.
     * @param string $field_id    HTML id for the input element.
     * @param string $option_key  Meta injector option constant for the enabled flag.
     * @param bool   $enabled     Whether the override is currently active.
     */
    private function render_meta_field_row(
        string $input_name,
        string $label,
        string $hint,
        string $type,
        string $value,
        string $field_id,
        string $option_key,
        bool $enabled
    ) : void {
        $toggle_id = 'parkstatic-toggle-' . $field_id;
        ?>
		<div class="parkstatic-meta-field">
			<div class="parkstatic-meta-field__main">
				<label for="<?php 
        echo esc_attr( $field_id );
        ?>"><?php 
        echo esc_html( $label );
        ?></label>
				<?php 
        if ( 'textarea' === $type ) {
            ?>
					<textarea
						name="<?php 
            echo esc_attr( $input_name );
            ?>"
						id="<?php 
            echo esc_attr( $field_id );
            ?>"
						rows="3"
						class="large-text"
					><?php 
            echo esc_textarea( $value );
            ?></textarea>
				<?php 
        } else {
            ?>
					<input
						type="text"
						name="<?php 
            echo esc_attr( $input_name );
            ?>"
						id="<?php 
            echo esc_attr( $field_id );
            ?>"
						value="<?php 
            echo esc_attr( $value );
            ?>"
						class="regular-text"
					/>
				<?php 
        }
        ?>
				<p class="parkstatic-settings__field-hint"><?php 
        echo esc_html( $hint );
        ?></p>
			</div>
			<label class="parkstatic-meta-field__override" for="<?php 
        echo esc_attr( $toggle_id );
        ?>">
				<input
					type="checkbox"
					class="parkstatic-meta-toggle-input"
					id="<?php 
        echo esc_attr( $toggle_id );
        ?>"
					name="<?php 
        echo esc_attr( $option_key );
        ?>"
					value="1"
					<?php 
        checked( $enabled );
        ?>
				/>
				<span class="parkstatic-meta-toggle" aria-hidden="true"></span>
				<span class="parkstatic-meta-field__status">
				<span class="parkstatic-meta-field__status-on"><?php 
        esc_html_e( 'Active', 'parkstatic' );
        ?></span>
				<span class="parkstatic-meta-field__status-off"><?php 
        esc_html_e( 'Original', 'parkstatic' );
        ?></span>
			</span>
		</label>
	</div>
	<?php 
    }

    /**
     * Renders a media-picker metadata field row with a per-field enable toggle.
     *
     * @param string $input_name    Form input name attribute.
     * @param string $label         Visible field label.
     * @param string $hint          Hint text shown below the picker.
     * @param int    $attachment_id Currently selected attachment ID (0 = none).
     * @param string $field_id      HTML id prefix for the picker elements.
     * @param string $select_label  Label shown on the media library open button.
     * @param string $option_key    Meta injector option constant for the enabled flag.
     * @param bool   $enabled       Whether the override is currently active.
     */
    private function render_meta_media_field_row(
        string $input_name,
        string $label,
        string $hint,
        int $attachment_id,
        string $field_id,
        string $select_label,
        string $option_key,
        bool $enabled
    ) : void {
        $toggle_id = 'parkstatic-toggle-' . $field_id;
        ?>
		<div class="parkstatic-meta-field">
			<div class="parkstatic-meta-field__main">
				<span class="parkstatic-meta-field__label"><?php 
        echo esc_html( $label );
        ?></span>
				<?php 
        $this->render_media_picker_field(
            $input_name,
            $attachment_id,
            $field_id,
            $select_label
        );
        ?>
				<p class="parkstatic-settings__field-hint"><?php 
        echo esc_html( $hint );
        ?></p>
			</div>
			<label class="parkstatic-meta-field__override" for="<?php 
        echo esc_attr( $toggle_id );
        ?>">
				<input
					type="checkbox"
					class="parkstatic-meta-toggle-input"
					id="<?php 
        echo esc_attr( $toggle_id );
        ?>"
					name="<?php 
        echo esc_attr( $option_key );
        ?>"
					value="1"
					<?php 
        checked( $enabled );
        ?>
				/>
				<span class="parkstatic-meta-toggle" aria-hidden="true"></span>
				<span class="parkstatic-meta-field__status">
				<span class="parkstatic-meta-field__status-on"><?php 
        esc_html_e( 'Active', 'parkstatic' );
        ?></span>
				<span class="parkstatic-meta-field__status-off"><?php 
        esc_html_e( 'Original', 'parkstatic' );
        ?></span>
			</span>
		</label>
	</div>
	<?php 
    }

    private function render_media_picker_field(
        string $input_name,
        int $attachment_id,
        string $field_id,
        string $select_label
    ) : void {
        $preview_url = '';
        if ( $attachment_id > 0 ) {
            $preview_url = wp_get_attachment_image_url( $attachment_id, 'thumbnail' );
            if ( !is_string( $preview_url ) ) {
                $preview_url = '';
            }
        }
        ?>
		<div class="parkstatic-media-picker" id="<?php 
        echo esc_attr( $field_id );
        ?>-picker">
			<input
				type="hidden"
				name="<?php 
        echo esc_attr( $input_name );
        ?>"
				id="<?php 
        echo esc_attr( $field_id );
        ?>-id"
				value="<?php 
        echo esc_attr( (string) $attachment_id );
        ?>"
			/>
			<div class="parkstatic-media-preview" style="margin-bottom:8px;">
				<?php 
        if ( '' !== $preview_url ) {
            ?>
					<img
						src="<?php 
            echo esc_url( $preview_url );
            ?>"
						alt=""
						id="<?php 
            echo esc_attr( $field_id );
            ?>-preview"
						style="max-width:128px;height:auto;display:block;"
					/>
				<?php 
        } else {
            ?>
					<img
						src=""
						alt=""
						id="<?php 
            echo esc_attr( $field_id );
            ?>-preview"
						style="max-width:128px;height:auto;display:none;"
					/>
				<?php 
        }
        ?>
			</div>
			<button
				type="button"
				class="button parkstatic-media-select"
				data-target-id="<?php 
        echo esc_attr( $field_id );
        ?>-id"
				data-preview-id="<?php 
        echo esc_attr( $field_id );
        ?>-preview"
				data-title="<?php 
        echo esc_attr( $select_label );
        ?>"
			>
				<?php 
        echo esc_html( $select_label );
        ?>
			</button>
			<button
				type="button"
				class="button parkstatic-media-remove"
				data-target-id="<?php 
        echo esc_attr( $field_id );
        ?>-id"
				data-preview-id="<?php 
        echo esc_attr( $field_id );
        ?>-preview"
				<?php 
        disabled( $attachment_id <= 0 );
        ?>
			>
				<?php 
        esc_html_e( 'Remove', 'parkstatic' );
        ?>
			</button>
		</div>
		<?php 
    }

}
