<?php

namespace Fotogenic_AI;

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

final class Studio_Module {
    private static ?Studio_Module $instance = null;
    private bool $filter_registered = false;

    private function __construct() {}

    public static function instance(): Studio_Module {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function init(): void {
        add_action( 'current_screen', [ $this, 'maybe_register_thumbnail_filter' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_product_link_style' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_media_edit_button_assets' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_media_library_action_script' ] );
        add_filter( 'attachment_fields_to_edit', [ $this, 'add_attachment_edit_button' ], 10, 2 );
        add_filter( 'media_row_actions', [ $this, 'add_media_library_action' ], 10, 2 );
        add_filter( 'post_row_actions', [ $this, 'add_product_list_action' ], 10, 2 );
        add_filter( 'wp_prepare_attachment_for_js', [ $this, 'add_media_grid_action_data' ], 10, 2 );
    }

    public function enqueue_core_assets(): void {
		Assets_Manifest::enqueue_style( 'fotogenic-ai-shared-ui-icons-css' );
		Assets_Manifest::enqueue_style( 'fotogenic-ai-direct-port-css' );
		Assets_Manifest::enqueue_style( 'fotogenic-ai-shared' );
		Assets_Manifest::enqueue_style( 'fotogenic-ai-studio' );

		Assets_Manifest::enqueue_script( 'fotogenic-ai-direct-port' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-store' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-transport' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-source-picker' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-recipe-form' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-summary' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-shell' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-view-model' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-progress' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-bulk-view' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-results' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-history' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-run-controller' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-app' );
		Assets_Manifest::enqueue_script( 'fotogenic-ai-studio-bootstrap' );
    }

    public function maybe_register_thumbnail_filter( $screen ): void {
        if ( $this->filter_registered ) {
            return;
        }
        if ( ! fotogenic_ai_user_can_access() ) {
            return;
        }
        $hook = $screen ? (string) $screen->base : null;
        if ( ! Admin::is_classic_product_editor_screen( $hook ) ) {
            return;
        }
        add_filter( 'admin_post_thumbnail_html', [ $this, 'inject_generate_button' ], 10, 3 );
        $this->filter_registered = true;
    }

    public function inject_generate_button( string $content, int $post_id, $thumbnail_id ): string {
        if ( ! fotogenic_ai_user_can_access() ) {
            return $content;
        }
        if ( ! Admin::is_classic_product_editor_screen() ) {
            return $content;
        }
        if ( 'product' !== get_post_type( $post_id ) ) {
            return $content;
        }
        if ( false !== strpos( $content, 'fotogenic-ai-generate-button' ) ) {
            return $content;
        }

        $studio_url = fotogenic_ai_get_studio_url( [
			'workflow'   => 'product_images',
			'sourceType' => 'product',
			'scope'      => 'bulk',
			'sourceId'   => $post_id,
        ] );
        $button = sprintf(
            '<div class="fotogenic-ai-button-wrap"><a class="button fotogenic-ai-generate-button" href="%s" target="_blank" rel="noopener noreferrer"><span class="dashicons dashicons-camera"></span>%s</a></div>',
            esc_url( $studio_url ),
            esc_html__( 'Generate with Fotogenic AI', 'fotogenic-ai' )
        );

        return $content . $button;
    }

    public function enqueue_product_link_style( string $hook ): void {
        if ( ! fotogenic_ai_user_can_access() ) {
            return;
        }
        if ( ! Admin::is_classic_product_editor_screen( $hook ) ) {
            return;
        }
        $this->enqueue_action_button_style();
    }

    private function enqueue_action_button_style(): void {
        if ( ! wp_style_is( 'fotogenic-ai-product-link', 'registered' ) ) {
            wp_register_style( 'fotogenic-ai-product-link', false, [], FOTOGENIC_AI_VERSION );
        }
        wp_enqueue_style( 'fotogenic-ai-product-link' );
        $styles = '.fotogenic-ai-button-wrap{display:flex;justify-content:flex-start;padding:10px;margin-bottom:10px;}'
            . '.wp-core-ui .fotogenic-ai-generate-button{background:#121212;margin:0;padding:6px 18px;text-align:center;text-transform:none;transition:background-color .2s ease,color .2s ease,border-color .2s ease,box-shadow .2s ease;color:#fff;box-shadow:none;border-radius:12px;display:inline-flex;align-items:center;gap:8px;border:1px solid #121212;line-height:1.4;min-height:0;}'
            . '.wp-core-ui .fotogenic-ai-generate-button .dashicons{color:currentColor;font-size:18px;width:18px;height:18px;line-height:18px;}'
            . '.wp-core-ui .fotogenic-ai-generate-button:hover{color:#fff;text-decoration:none;background:#1e1e1e;border-color:#1e1e1e;}'
            . '.wp-core-ui .fotogenic-ai-generate-button:focus,.wp-core-ui .fotogenic-ai-generate-button:active,.wp-core-ui .fotogenic-ai-generate-button:focus-visible{background:#1e1e1e;color:#fff;text-decoration:none;box-shadow:0 0 0 3px rgba(18,18,18,.16);}'
            . '.wp-core-ui .fotogenic-ai-generate-button.is-disabled,.wp-core-ui .fotogenic-ai-generate-button:disabled{background:#e5e7eb;color:#9ca3af;border-color:#e5e7eb;box-shadow:none;cursor:not-allowed;filter:none;}';
        wp_add_inline_style( 'fotogenic-ai-product-link', $styles );
    }

    /**
     * Enqueue button style and placement script on attachment edit screen (for Edit with Fotogenic AI).
     * When the "Edit Image" button exists, the script moves our button next to it and hides the form row.
     */
    public function enqueue_media_edit_button_assets( string $hook ): void {
        if ( 'post.php' !== $hook ) {
            return;
        }
        if ( ! fotogenic_ai_user_can_access() ) {
            return;
        }
        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
        if ( ! $screen || 'attachment' !== $screen->post_type ) {
            return;
        }
        $this->enqueue_action_button_style();

        $post    = get_post();
        $post_id = $post instanceof \WP_Post ? (int) $post->ID : 0;
        if ( ! $post_id || ! wp_attachment_is_image( $post_id ) ) {
            return;
        }
		$url = fotogenic_ai_get_studio_url(
			[
				'workflow'   => 'product_images',
				'sourceType' => 'media',
				'scope'      => 'bulk',
				'sourceId'   => $post_id,
			]
		);
        $label = __( 'Edit with Fotogenic AI', 'fotogenic-ai' );
        $script = sprintf(
            "(function(){var u=%s,l=%s;function run(){var editBtn=document.querySelector('[id^=\"imgedit-open-btn-\"]');var wrap=document.querySelector('.fotogenic-ai-attachment-edit-wrap');if(editBtn&&wrap){var a=document.createElement('a');a.href=u;a.className='button fotogenic-ai-generate-button';a.style.marginLeft='8px';a.target='_blank';a.rel='noopener noreferrer';a.textContent=l;editBtn.parentNode.insertBefore(a,editBtn.nextSibling);var tr=wrap.closest('tr');if(tr) tr.style.display='none';}}if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',run); else run();})();",
            fotogenic_ai_json_encode_for_inline( $url, '""' ),
            fotogenic_ai_json_encode_for_inline( $label, '""' )
        );
        wp_add_inline_script( 'common', $script, 'after' );
    }

    /**
     * Add "Edit with Fotogenic AI" to attachment edit form via WordPress API.
     * Uses attachment_fields_to_edit so it works on all sites and future WP versions.
     */
    public function add_attachment_edit_button( array $form_fields, \WP_Post $post ): array {
        if ( ! wp_attachment_is_image( $post->ID ) ) {
            return $form_fields;
        }
        if ( ! current_user_can( 'edit_post', $post->ID ) || ! fotogenic_ai_user_can_access() ) {
            return $form_fields;
        }
        $url = fotogenic_ai_get_studio_url( [
			'workflow'   => 'product_images',
			'sourceType' => 'media',
			'scope'      => 'bulk',
			'sourceId'   => $post->ID,
        ] );
        $label = __( 'Edit with Fotogenic AI', 'fotogenic-ai' );
        $form_fields['fotogenic_ai'] = [
            'label' => '',
            'input' => 'html',
            'html'  => '<span class="fotogenic-ai-attachment-edit-wrap"><a class="button fotogenic-ai-generate-button" href="' . esc_url( $url ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( $label ) . '</a></span>',
        ];
        return $form_fields;
    }

    public function add_media_library_action( array $actions, \WP_Post $post ): array {
        if ( 'attachment' !== $post->post_type ) {
            return $actions;
        }
        if ( ! wp_attachment_is_image( $post->ID ) ) {
            return $actions;
        }
        if ( ! current_user_can( 'edit_post', $post->ID ) || ! fotogenic_ai_user_can_access() ) {
            return $actions;
        }
        $studio_url = fotogenic_ai_get_studio_url( [
			'workflow'   => 'product_images',
			'sourceType' => 'media',
			'scope'      => 'bulk',
			'sourceId'   => $post->ID,
        ] );
        $actions['fotogenic_ai'] = sprintf(
            '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
            esc_url( $studio_url ),
            esc_html__( 'Fotogenic AI', 'fotogenic-ai' )
        );
        return $actions;
    }

    public function add_product_list_action( array $actions, \WP_Post $post ): array {
        if ( 'product' !== $post->post_type ) {
            return $actions;
        }
        if ( ! fotogenic_ai_woocommerce_available() ) {
            return $actions;
        }
        if ( ! current_user_can( 'edit_post', $post->ID ) || ! fotogenic_ai_user_can_access() ) {
            return $actions;
        }

        $studio_url = fotogenic_ai_get_studio_url( [
			'workflow'   => 'product_images',
			'sourceType' => 'product',
			'scope'      => 'bulk',
			'sourceId'   => $post->ID,
        ] );
        $actions['fotogenic_ai'] = sprintf(
            '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
            esc_url( $studio_url ),
            esc_html__( 'Fotogenic AI', 'fotogenic-ai' )
        );
        return $actions;
    }

    public function add_media_grid_action_data( array $response, \WP_Post $attachment ): array {
        if ( 'attachment' !== $attachment->post_type ) {
            return $response;
        }
        if ( ! wp_attachment_is_image( $attachment->ID ) ) {
            return $response;
        }
        if ( ! current_user_can( 'edit_post', $attachment->ID ) || ! fotogenic_ai_user_can_access() ) {
            return $response;
        }
        $response['fotogenicAiUrl'] = fotogenic_ai_get_studio_url( [
			'workflow'   => 'product_images',
			'sourceType' => 'media',
			'scope'      => 'bulk',
			'sourceId'   => $attachment->ID,
        ] );
        return $response;
    }

    public function enqueue_media_library_action_script( string $hook ): void {
        if ( 'upload.php' !== $hook ) {
            return;
        }
        if ( ! fotogenic_ai_user_can_access() ) {
            return;
        }
        wp_enqueue_script( 'media-views' );
        $media_action_label = __( 'Fotogenic AI', 'fotogenic-ai' );
        $script = implode(
            "\n",
            [
                '(() => {',
                '    if (!window.wp || !wp.media || !wp.media.view || !wp.media.view.Attachment) {',
                '        return;',
                '    }',
                '    const proto = wp.media.view.Attachment.prototype;',
                '    if (proto.__fotogenicAiActionApplied) {',
                '        return;',
                '    }',
                '    proto.__fotogenicAiActionApplied = true;',
                '    const originalRender = proto.render;',
                '    proto.render = function () {',
                '        const result = originalRender.apply(this, arguments);',
                '        try {',
                '            const url = this.model && this.model.get && this.model.get("fotogenicAiUrl");',
                '            if (!url) {',
                '                return result;',
                '            }',
                '            const actions = this.$el && this.$el.find && this.$el.find(".actions");',
                '            if (!actions || !actions.length) {',
                '                return result;',
                '            }',
                '            if (actions.find(".fotogenic-ai-media-action").length) {',
                '                return result;',
                '            }',
                '            const link = document.createElement("a");',
                '            link.className = "fotogenic-ai-media-action";',
                '            link.href = url;',
                '            link.target = "_blank";',
                '            link.rel = "noopener noreferrer";',
                '            link.textContent = %s;',
                '            actions.append(link);',
                '        } catch (e) {',
                '            if (window.console && typeof window.console.warn === "function") {',
                '                window.console.warn("Fotogenic AI could not render the Media Library action.");',
                '            }',
                '        }',
                '        return result;',
                '    };',
                '})();',
            ]
        );
        $script = sprintf( $script, fotogenic_ai_json_encode_for_inline( $media_action_label, '""' ) );
        wp_add_inline_script( 'media-views', $script, 'after' );
    }
}
