<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Admin;

use APD\Support\ProductionPackBuilder;
use APD\Support\RequestData;
use WC_Order;
use WC_Order_Item_Product;

defined('ABSPATH') || exit;

class OrderProductionPage
{
    public function render() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to access this page.', 'asuka-product-designer'));
        }

        $query = RequestData::query();
        $builder = new ProductionPackBuilder();
        $statusFilter = 'all';
        if (isset($query['status_filter']) && (string) $query['status_filter'] !== 'all') {
            $statusFilter = ProductionPackBuilder::normalizeStatus((string) $query['status_filter']);
        }
        $search = sanitize_text_field((string) ($query['s'] ?? ''));
        $paged = max(1, absint($query['paged'] ?? 1));
        $perPage = 20;

        $orders = $this->findOrders($search, $paged, $perPage);
        $entries = [];
        foreach ($orders as $order) {
            if (! $order instanceof WC_Order) {
                continue;
            }
            foreach ($order->get_items('line_item') as $item) {
                if (! $item instanceof WC_Order_Item_Product) {
                    continue;
                }
                $pack = $builder->build($item, $order);
                if (! empty($pack['isCustomized'])) {
                    if ($statusFilter === 'all' || ($pack['productionStatus'] ?? '') === $statusFilter) {
                        $entries[] = $pack;
                    }
                }
            }
        }

        $selectedOrderId = absint($query['order_id'] ?? 0);
        $selectedItemId = absint($query['item_id'] ?? 0);
        $selectedPack = ($selectedOrderId > 0 && $selectedItemId > 0) ? $this->resolvePack($selectedOrderId, $selectedItemId) : null;
        $settings = (new AdminSettings())->all();

        echo '<div class="wrap apd-admin-shell apd-admin-theme-' . esc_attr($settings['admin_theme']) . ' apd-production-page">';
        echo '<div class="apd-page-heading apd-page-heading-wide">';
        echo '<div>';
        echo '<span class="apd-badge">' . esc_html__('Workshop flow', 'asuka-product-designer') . '</span>';
        echo '<h1>' . esc_html__('Production orders', 'asuka-product-designer') . '</h1>';
        echo '<p>' . esc_html__('Review customized WooCommerce line items, inspect production packs, and update workshop status from one unified workspace.', 'asuka-product-designer') . '</p>';
        echo '</div>';
        echo '<div class="apd-chip-row">';
        echo '<span class="apd-chip"><strong>' . (int) count($entries) . '</strong> ' . esc_html(_n('matching item', 'matching items', count($entries), 'asuka-product-designer')) . '</span>';
        if (is_array($selectedPack) && ! empty($selectedPack['isCustomized'])) {
            echo '<span class="apd-chip apd-chip-status apd-status apd-status--' . esc_attr((string) ($selectedPack['productionStatus'] ?? 'pending')) . '">' . esc_html((string) ($selectedPack['productionStatusLabel'] ?? __('Selected pack', 'asuka-product-designer'))) . '</span>';
        }
        echo '</div>';
        echo '</div>';

        if (isset($query['updated'])) {
            $updated = sanitize_key((string) $query['updated']);
            if ($updated === 'status') {
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Production status updated.', 'asuka-product-designer') . '</p></div>';
            } elseif ($updated === 'notes') {
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Production notes updated.', 'asuka-product-designer') . '</p></div>';
            }
        }

        echo '<section class="apd-card apd-production-toolbar-card">';
        echo '<div class="apd-card-head apd-card-head-stack">';
        echo '<div><h2>' . esc_html__('Filters', 'asuka-product-designer') . '</h2><p>' . esc_html__('Limit the list to a production status or jump directly to an order number before opening the detailed pack.', 'asuka-product-designer') . '</p></div>';
        echo '</div>';
        $this->renderFilters($statusFilter, $search);
        echo '</section>';

        $this->renderList($entries, $statusFilter, $paged, $search);

        if (is_array($selectedPack) && ! empty($selectedPack['isCustomized'])) {
            $this->renderDetail($selectedPack, $statusFilter, $search, $paged);
        }

        echo '</div>';
    }

    public function export() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to export this production pack.', 'asuka-product-designer'));
        }

        $query = RequestData::query();
        $orderId = absint($query['order_id'] ?? 0);
        $itemId = absint($query['item_id'] ?? 0);
        $export = sanitize_key((string) ($query['export'] ?? 'pack'));

        if (! wp_verify_nonce(sanitize_text_field((string) ($query['_wpnonce'] ?? '')), 'apd_export_production_pack_' . $orderId . '_' . $itemId . '_' . $export)) {
            wp_die(esc_html__('The export link is no longer valid.', 'asuka-product-designer'));
        }

        $pack = $this->resolvePack($orderId, $itemId);
        if (! is_array($pack) || empty($pack['isCustomized'])) {
            wp_die(esc_html__('Unable to load this production pack.', 'asuka-product-designer'));
        }

        switch ($export) {
            case 'worksheet':
                $this->renderWorksheetDocument($pack);
                exit;
            case 'design':
                $payload = $pack['design'] ?? [];
                $filename = sprintf('apd-design-order-%d-item-%d.json', $orderId, $itemId);
                break;
            case 'state':
                $payload = $pack['state'] ?? [];
                $filename = sprintf('apd-state-order-%d-item-%d.json', $orderId, $itemId);
                break;
            case 'summary':
                $payload = $pack;
                unset($payload['design'], $payload['state']);
                $filename = sprintf('apd-production-summary-order-%d-item-%d.json', $orderId, $itemId);
                break;
            case 'pack':
            default:
                $payload = $pack;
                $filename = sprintf('apd-production-pack-order-%d-item-%d.json', $orderId, $itemId);
                break;
        }

        $json = wp_json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        if (! is_string($json)) {
            wp_die(esc_html__('Unable to export this production pack.', 'asuka-product-designer'));
        }

        nocache_headers();
        header('Content-Type: application/json; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $filename);
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- This response is a JSON download; HTML escaping would corrupt the exported package.
        echo $json;
        exit;
    }

    public function updateStatus() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to update production status.', 'asuka-product-designer'));
        }

        $request = RequestData::request();
        $orderId = absint($request['order_id'] ?? 0);
        $itemId = absint($request['item_id'] ?? 0);
        $status = ProductionPackBuilder::normalizeStatus((string) ($request['status'] ?? ''));

        if (! wp_verify_nonce(sanitize_text_field((string) ($request['_wpnonce'] ?? '')), 'apd_update_production_status_' . $orderId . '_' . $itemId . '_' . $status)) {
            wp_die(esc_html__('The production status action is no longer valid.', 'asuka-product-designer'));
        }

        [$order, $item] = $this->resolveOrderAndItem($orderId, $itemId);
        if (! $order instanceof WC_Order || ! $item instanceof WC_Order_Item_Product) {
            wp_die(esc_html__('Unable to load the targeted order item.', 'asuka-product-designer'));
        }

        $item->update_meta_data('_apd_production_status', $status);
        $item->save();

        $redirect = esc_url_raw(rawurldecode((string) ($request['redirect'] ?? '')));
        if ($redirect === '') {
            $redirect = add_query_arg([
                'page' => 'apd-production',
                'order_id' => $orderId,
                'item_id' => $itemId,
                'updated' => 'status',
            ], admin_url('admin.php'));
        } else {
            $redirect = add_query_arg('updated', 'status', $redirect);
        }

        wp_safe_redirect($redirect);
        exit;
    }

    public function updateNotes() : void
    {
        if (! current_user_can('manage_asuka_designer')) {
            wp_die(esc_html__('You are not allowed to update production notes.', 'asuka-product-designer'));
        }

        $request = RequestData::request();
        $orderId = absint($request['order_id'] ?? 0);
        $itemId = absint($request['item_id'] ?? 0);

        if (! wp_verify_nonce(sanitize_text_field((string) ($request['_wpnonce'] ?? '')), 'apd_update_production_notes_' . $orderId . '_' . $itemId)) {
            wp_die(esc_html__('The production notes action is no longer valid.', 'asuka-product-designer'));
        }

        [$order, $item] = $this->resolveOrderAndItem($orderId, $itemId);
        if (! $order instanceof WC_Order || ! $item instanceof WC_Order_Item_Product) {
            wp_die(esc_html__('Unable to load the targeted order item.', 'asuka-product-designer'));
        }

        $notes = sanitize_textarea_field((string) ($request['notes'] ?? ''));
        $item->update_meta_data('_apd_production_notes', $notes);
        $item->save();

        $redirect = esc_url_raw(rawurldecode((string) ($request['redirect'] ?? '')));
        if ($redirect === '') {
            $redirect = add_query_arg([
                'page' => 'apd-production',
                'order_id' => $orderId,
                'item_id' => $itemId,
                'updated' => 'notes',
            ], admin_url('admin.php'));
        } else {
            $redirect = add_query_arg('updated', 'notes', $redirect);
        }

        wp_safe_redirect($redirect);
        exit;
    }

    protected function findOrders(string $search, int $paged, int $perPage) : array
    {
        if ($search !== '' && ctype_digit($search)) {
            $order = wc_get_order((int) $search);
            return $order instanceof WC_Order ? [$order] : [];
        }

        return wc_get_orders([
            'limit' => $perPage,
            'paged' => $paged,
            'orderby' => 'date',
            'order' => 'DESC',
            'status' => array_keys(wc_get_order_statuses()),
            'return' => 'objects',
        ]);
    }

    protected function renderFilters(string $statusFilter, string $search) : void
    {
        echo '<form method="get" class="apd-production-toolbar">';
        echo '<input type="hidden" name="page" value="apd-production">';
        echo '<div class="apd-production-toolbar__group">';
        echo '<label for="apd-status-filter"><strong>' . esc_html__('Status', 'asuka-product-designer') . '</strong></label>';
        echo '<select id="apd-status-filter" name="status_filter">';
        echo '<option value="all"' . selected($statusFilter, 'all', false) . '>' . esc_html__('All statuses', 'asuka-product-designer') . '</option>';
        foreach (ProductionPackBuilder::statusOptions() as $value => $label) {
            echo '<option value="' . esc_attr($value) . '"' . selected($statusFilter, $value, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
        echo '</div>';
        echo '<div class="apd-production-toolbar__group">';
        echo '<label for="apd-production-search"><strong>' . esc_html__('Order', 'asuka-product-designer') . '</strong></label>';
        echo '<input id="apd-production-search" type="search" name="s" value="' . esc_attr($search) . '" placeholder="' . esc_attr__('Order ID', 'asuka-product-designer') . '">';
        echo '</div>';
        submit_button(__('Filter', 'asuka-product-designer'), 'secondary', '', false);
        echo '</form>';
    }

    protected function renderList(array $entries, string $statusFilter, int $paged, string $search) : void
    {
        echo '<section class="apd-card apd-production-card">';
        echo '<div class="apd-card-head apd-card-head-stack">';
        echo '<div><h2>' . esc_html__('Customized order items', 'asuka-product-designer') . '</h2><p>' . esc_html__('Each row represents a WooCommerce line item that contains a saved customization ready for production review.', 'asuka-product-designer') . '</p></div>';
        echo '<span class="apd-chip"><strong>' . (int) count($entries) . '</strong> ' . esc_html(_n('item', 'items', count($entries), 'asuka-product-designer')) . '</span>';
        echo '</div>';

        if ($entries === []) {
            echo '<div class="apd-empty-state-soft"><p>' . esc_html__('No customized line items matched the current filters.', 'asuka-product-designer') . '</p></div>';
            echo '</section>';
            return;
        }

        echo '<div class="apd-table-wrap">';
        echo '<table class="widefat striped apd-production-table">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__('Order', 'asuka-product-designer') . '</th>';
        echo '<th>' . esc_html__('Item', 'asuka-product-designer') . '</th>';
        echo '<th>' . esc_html__('Custom Product', 'asuka-product-designer') . '</th>';
        echo '<th>' . esc_html__('Status', 'asuka-product-designer') . '</th>';
        echo '<th>' . esc_html__('Final unit price', 'asuka-product-designer') . '</th>';
        echo '<th>' . esc_html__('Views / Objects', 'asuka-product-designer') . '</th>';
        echo '<th>' . esc_html__('Actions', 'asuka-product-designer') . '</th>';
        echo '</tr></thead><tbody>';

        foreach ($entries as $pack) {
            $detailUrl = add_query_arg([
                'page' => 'apd-production',
                'order_id' => (int) $pack['orderId'],
                'item_id' => (int) $pack['itemId'],
                'status_filter' => $statusFilter,
                'paged' => $paged,
                's' => $search,
            ], admin_url('admin.php'));
            $statusClass = 'apd-status apd-status--' . esc_attr((string) $pack['productionStatus']);
            $views = (int) ($pack['analysis']['viewCount'] ?? 0);
            $objects = (int) ($pack['analysis']['objectCount'] ?? 0);
            echo '<tr>';
            echo '<td><a href="' . esc_url(get_edit_post_link((int) $pack['orderId'], '')) . '">#' . (int) $pack['orderId'] . '</a><br><span class="description">' . esc_html((string) ($pack['dateCreated'] ?? '')) . '</span></td>';
            echo '<td><strong>' . esc_html((string) $pack['itemName']) . '</strong><br><span class="description">' . sprintf(/* translators: Placeholder values are populated from the current administration record. */ esc_html__('Line #%1$d · Qty %2$d', 'asuka-product-designer'), (int) $pack['itemId'], (int) $pack['quantity']) . '</span></td>';
            echo '<td>' . esc_html((string) (($pack['configTitle'] ?? '') !== '' ? $pack['configTitle'] : '#' . (int) ($pack['configId'] ?? 0))) . '</td>';
            echo '<td><span class="' . esc_attr($statusClass) . '">' . esc_html((string) $pack['productionStatusLabel']) . '</span></td>';
            echo '<td>' . wp_kses_post(wc_price((float) ($pack['price']['total'] ?? 0))) . '</td>';
            echo '<td>' . sprintf(/* translators: Placeholder values are populated from the current administration record. */ esc_html__('%1$d views · %2$d objects', 'asuka-product-designer'), (int) $views, (int) $objects) . '</td>';
            echo '<td><a class="button button-secondary" href="' . esc_url($detailUrl) . '">' . esc_html__('View pack', 'asuka-product-designer') . '</a> <a class="button button-link" href="' . esc_url((string) ($pack['downloads']['pack'] ?? '')) . '">' . esc_html__('JSON', 'asuka-product-designer') . '</a></td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
        echo '</div>';
        echo '</section>';
    }

    protected function renderDetail(array $pack, string $statusFilter, string $search, int $paged) : void
    {
        $redirectUrl = add_query_arg([
            'page' => 'apd-production',
            'order_id' => (int) $pack['orderId'],
            'item_id' => (int) $pack['itemId'],
            'status_filter' => $statusFilter,
            'paged' => $paged,
            's' => $search,
        ], admin_url('admin.php'));

        echo '<section class="apd-card apd-production-card apd-production-detail">';
        echo '<div class="apd-production-detail__head">';
        echo '<div><h2>' . esc_html__('Production pack', 'asuka-product-designer') . '</h2><p>' . esc_html((string) $pack['itemName']) . ' · #' . (int) $pack['orderId'] . ' / ' . sprintf(/* translators: Placeholder values are populated from the current administration record. */ esc_html__('Line %d', 'asuka-product-designer'), (int) $pack['itemId']) . '</p></div>';
        echo '<span class="apd-status apd-status--' . esc_attr((string) $pack['productionStatus']) . '">' . esc_html((string) $pack['productionStatusLabel']) . '</span>';
        echo '</div>';

        echo '<div class="apd-production-detail__grid">';
        echo '<div>';
        echo '<dl class="apd-production-dl">';
        echo '<dt>' . esc_html__('Order', 'asuka-product-designer') . '</dt><dd><a href="' . esc_url(get_edit_post_link((int) $pack['orderId'], '')) . '">#' . (int) $pack['orderId'] . '</a></dd>';
        echo '<dt>' . esc_html__('Customer', 'asuka-product-designer') . '</dt><dd>' . esc_html((string) (($pack['customerName'] ?? '') !== '' ? $pack['customerName'] : __('Guest', 'asuka-product-designer'))) . '</dd>';
        echo '<dt>' . esc_html__('Custom Product', 'asuka-product-designer') . '</dt><dd>' . esc_html((string) (($pack['configTitle'] ?? '') !== '' ? $pack['configTitle'] : '#' . (int) ($pack['configId'] ?? 0))) . '</dd>';
        echo '<dt>' . esc_html__('Variation', 'asuka-product-designer') . '</dt><dd>' . esc_html((int) ($pack['variationId'] ?? 0) > 0 ? ('#' . (int) $pack['variationId']) : __('Parent product', 'asuka-product-designer')) . '</dd>';
        echo '<dt>' . esc_html__('Price', 'asuka-product-designer') . '</dt><dd>' . wp_kses_post(wc_price((float) ($pack['price']['total'] ?? 0))) . ' <span class="description">(' . esc_html__('final unit', 'asuka-product-designer') . ')</span></dd>';
        if (! empty($pack['resumeUrl'])) {
            echo '<dt>' . esc_html__('Resume link', 'asuka-product-designer') . '</dt><dd><a href="' . esc_url((string) $pack['resumeUrl']) . '">' . esc_html__('Open saved customization', 'asuka-product-designer') . '</a></dd>';
        }
        echo '</dl>';

        echo '<div class="apd-production-actions">';
        echo '<a class="button button-primary" href="' . esc_url((string) ($pack['downloads']['worksheet'] ?? '')) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Printable worksheet', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['pack'] ?? '')) . '">' . esc_html__('Download production pack', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['summary'] ?? '')) . '">' . esc_html__('Download summary JSON', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['design'] ?? '')) . '">' . esc_html__('Download design JSON', 'asuka-product-designer') . '</a> ';
        echo '<a class="button button-secondary" href="' . esc_url((string) ($pack['downloads']['state'] ?? '')) . '">' . esc_html__('Download state JSON', 'asuka-product-designer') . '</a> ';
        if (! empty($pack['previewUrl'])) {
            echo '<a class="button button-link" href="' . esc_url((string) $pack['previewUrl']) . '" target="_blank" rel="noopener noreferrer">' . esc_html__('Open HD preview', 'asuka-product-designer') . '</a>';
        }
        echo '</div>';

        echo '<div class="apd-production-statusbar"><strong>' . esc_html__('Production status', 'asuka-product-designer') . ':</strong> ';
        foreach (ProductionPackBuilder::statusOptions() as $status => $label) {
            $url = ProductionPackBuilder::buildStatusUrl((int) $pack['orderId'], (int) $pack['itemId'], $status, $redirectUrl);
            $class = $status === ($pack['productionStatus'] ?? '') ? 'button button-primary' : 'button button-secondary';
            echo '<a class="' . esc_attr($class) . '" href="' . esc_url($url) . '">' . esc_html($label) . '</a> ';
        }
        echo '</div>';
        $this->renderNotesEditor($pack, $redirectUrl);
        echo '</div>';

        echo '<div>';
        if (! empty($pack['previewUrl'])) {
            echo '<div class="apd-production-preview"><img src="' . esc_url((string) $pack['previewUrl']) . '" alt="' . esc_attr__('Production preview', 'asuka-product-designer') . '"></div>';
        }
        echo '</div>';
        echo '</div>';

        $analysis = is_array($pack['analysis'] ?? null) ? $pack['analysis'] : [];
        echo '<div class="apd-production-section-grid">';
        echo '<section><h3>' . esc_html__('Views', 'asuka-product-designer') . '</h3>';
        if (! empty($analysis['viewDetails']) && is_array($analysis['viewDetails'])) {
            echo '<ul class="apd-production-list">';
            foreach ($analysis['viewDetails'] as $view) {
                if (! is_array($view)) {
                    continue;
                }
                $dims = '';
                if ((float) ($view['width'] ?? 0) > 0 && (float) ($view['height'] ?? 0) > 0) {
                    $dims = sprintf('%s × %s %s', rtrim(rtrim(number_format((float) $view['width'], 2, '.', ''), '0'), '.'), rtrim(rtrim(number_format((float) $view['height'], 2, '.', ''), '0'), '.'), (string) ($view['unit'] ?? 'px'));
                }
                echo '<li><strong>' . esc_html((string) ($view['name'] ?? $view['id'] ?? __('View', 'asuka-product-designer'))) . '</strong> — ' . esc_html($dims !== '' ? $dims : __('No dimensions', 'asuka-product-designer')) . ' · ' . sprintf(/* translators: Placeholder values are populated from the current administration record. */ esc_html__('%d objects', 'asuka-product-designer'), (int) ($view['objectCount'] ?? 0)) . '</li>';
            }
            echo '</ul>';
        } else {
            echo '<p>' . esc_html__('No view data found.', 'asuka-product-designer') . '</p>';
        }
        echo '</section>';

        echo '<section><h3>' . esc_html__('Design details', 'asuka-product-designer') . '</h3><ul class="apd-production-list">';
        echo '<li><strong>' . esc_html__('Objects', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['objectTypes'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Colors', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['colors'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Texts', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(' · ', (array) ($analysis['texts'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Catalog designs', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['catalogDesigns'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Catalog elements', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['catalogElements'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Printing methods', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['printingMethods'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        if (! empty($pack['productionNotes'])) {
            echo '<li><strong>' . esc_html__('Workshop notes', 'asuka-product-designer') . ':</strong> ' . nl2br(esc_html((string) $pack['productionNotes'])) . '</li>';
        }
        echo '</ul></section>';
        echo '</div>';
        echo '</section>';
    }


    protected function renderWorksheetDocument(array $pack) : void
    {
        nocache_headers();
        header('Content-Type: text/html; charset=utf-8');

        wp_enqueue_style(
            'asuka-product-designer-production-worksheet',
            ASUKA_PRODUCT_DESIGNER_ASSETS_URL . 'css/production-worksheet.css',
            [],
            ASUKA_PRODUCT_DESIGNER_VERSION
        );
        wp_enqueue_script(
            'asuka-product-designer-production-worksheet',
            ASUKA_PRODUCT_DESIGNER_ASSETS_URL . 'js/production-worksheet.js',
            [],
            ASUKA_PRODUCT_DESIGNER_VERSION,
            true
        );

        $title = sprintf(
            /* translators: 1: order id, 2: item id */
            __('Production worksheet — Order #%1$d / Item #%2$d', 'asuka-product-designer'),
            (int) ($pack['orderId'] ?? 0),
            (int) ($pack['itemId'] ?? 0)
        );

        $analysis = is_array($pack['analysis'] ?? null) ? $pack['analysis'] : [];
        $price = is_array($pack['price'] ?? null) ? $pack['price'] : [];
        $breakdown = is_array($price['breakdown'] ?? null) ? $price['breakdown'] : [];
        $rows = is_array($breakdown['breakdown'] ?? null) ? $breakdown['breakdown'] : [];
        $rules = is_array($breakdown['appliedRules'] ?? null) ? $breakdown['appliedRules'] : [];
        $configLabel = (string) (($pack['configTitle'] ?? '') !== '' ? $pack['configTitle'] : ('#' . (int) ($pack['configId'] ?? 0)));
        $variationLabel = (int) ($pack['variationId'] ?? 0) > 0 ? ('#' . (int) $pack['variationId']) : __('Parent product', 'asuka-product-designer');
        $customerLabel = (string) (($pack['customerName'] ?? '') !== '' ? $pack['customerName'] : __('Guest', 'asuka-product-designer'));
        $previewUrl = (string) ($pack['previewUrl'] ?? '');

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- get_language_attributes() returns the complete escaped lang/dir attribute fragment.
        echo '<!doctype html><html ' . get_language_attributes() . '><head><meta charset="' . esc_attr(get_bloginfo('charset')) . '">';
        echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
        echo '<title>' . esc_html($title) . '</title>';
        wp_print_styles(['asuka-product-designer-production-worksheet']);
        echo '</head><body><div class="apd-sheet">';
        echo '<div class="apd-sheet__bar">';
        echo '<div><span class="apd-pill">' . esc_html((string) ($pack['productionStatusLabel'] ?? __('To produce', 'asuka-product-designer'))) . '</span>';
        echo '<h1 class="apd-sheet__title">' . esc_html($title) . '</h1>';
        echo '<p class="apd-sheet__subtitle">' . esc_html((string) ($pack['itemName'] ?? '')) . ' · ' . sprintf(/* translators: Placeholder values are populated from the current administration record. */ esc_html__('Qty %d', 'asuka-product-designer'), (int) ($pack['quantity'] ?? 1)) . '</p></div>';
        echo '<div class="apd-sheet__actions"><button type="button" class="apd-btn apd-btn--dark" data-apd-print-worksheet>' . esc_html__('Print worksheet', 'asuka-product-designer') . '</button>';
        if (! empty($pack['downloads']['pack'])) {
            echo '<a class="apd-btn" href="' . esc_url((string) $pack['downloads']['pack']) . '">' . esc_html__('Download JSON pack', 'asuka-product-designer') . '</a>';
        }
        echo '</div></div>';

        echo '<div class="apd-grid">';
        echo '<div class="apd-card">';
        echo '<h2>' . esc_html__('Order & production summary', 'asuka-product-designer') . '</h2>';
        echo '<dl class="apd-meta">';
        echo '<dt>' . esc_html__('Order', 'asuka-product-designer') . '</dt><dd>#' . (int) ($pack['orderId'] ?? 0) . '</dd>';
        echo '<dt>' . esc_html__('Line item', 'asuka-product-designer') . '</dt><dd>#' . (int) ($pack['itemId'] ?? 0) . '</dd>';
        echo '<dt>' . esc_html__('Date', 'asuka-product-designer') . '</dt><dd>' . esc_html((string) ($pack['dateCreated'] ?? '')) . '</dd>';
        echo '<dt>' . esc_html__('Customer', 'asuka-product-designer') . '</dt><dd>' . esc_html($customerLabel) . '</dd>';
        echo '<dt>' . esc_html__('Custom Product', 'asuka-product-designer') . '</dt><dd>' . esc_html($configLabel) . '</dd>';
        echo '<dt>' . esc_html__('Variation', 'asuka-product-designer') . '</dt><dd>' . esc_html($variationLabel) . '</dd>';
        echo '<dt>' . esc_html__('Order status', 'asuka-product-designer') . '</dt><dd>' . esc_html((string) ($pack['orderStatus'] ?? '')) . '</dd>';
        if (! empty($pack['resumeUrl'])) {
            echo '<dt>' . esc_html__('Resume URL', 'asuka-product-designer') . '</dt><dd>' . esc_html((string) $pack['resumeUrl']) . '</dd>';
        }
        echo '</dl>';
        echo '<div class="apd-kpis">';
        echo '<div class="apd-kpi"><span class="apd-kpi__label">' . esc_html__('Base', 'asuka-product-designer') . '</span><span class="apd-kpi__value">' . wp_kses_post(wc_price((float) ($price['base'] ?? 0))) . '</span></div>';
        echo '<div class="apd-kpi"><span class="apd-kpi__label">' . esc_html__('Adjustment', 'asuka-product-designer') . '</span><span class="apd-kpi__value">' . wp_kses_post(wc_price((float) ($price['adjustment'] ?? 0))) . '</span></div>';
        echo '<div class="apd-kpi"><span class="apd-kpi__label">' . esc_html__('Final unit', 'asuka-product-designer') . '</span><span class="apd-kpi__value">' . wp_kses_post(wc_price((float) ($price['total'] ?? 0))) . '</span></div>';
        echo '<div class="apd-kpi"><span class="apd-kpi__label">' . esc_html__('Views / Objects', 'asuka-product-designer') . '</span><span class="apd-kpi__value">' . esc_html((string) ((int) ($analysis['viewCount'] ?? 0) . ' / ' . (int) ($analysis['objectCount'] ?? 0))) . '</span></div>';
        echo '</div>';
        echo '</div>';
        echo '<div class="apd-preview">';
        echo '<h2>' . esc_html__('Design preview', 'asuka-product-designer') . '</h2>';
        if ($previewUrl !== '') {
            echo '<img src="' . esc_url($previewUrl) . '" alt="' . esc_attr__('Production preview', 'asuka-product-designer') . '">';
        } else {
            echo '<p>' . esc_html__('No preview captured for this customization.', 'asuka-product-designer') . '</p>';
        }
        echo '</div>';
        echo '</div>';

        echo '<div class="apd-section-grid">';
        echo '<section class="apd-card"><h3>' . esc_html__('Production checklist', 'asuka-product-designer') . '</h3><div class="apd-checks">';
        foreach ([
            __('Print validated', 'asuka-product-designer'),
            __('Artwork positioned', 'asuka-product-designer'),
            __('Colors validated', 'asuka-product-designer'),
            __('Texts proofread', 'asuka-product-designer'),
        ] as $label) {
            echo '<div class="apd-check"><strong>☐ ' . esc_html($label) . '</strong></div>';
        }
        echo '</div>';
        if (! empty($analysis['notes'])) {
            echo '<div class="apd-note"><strong>' . esc_html__('Notes', 'asuka-product-designer') . ':</strong> ' . esc_html((string) $analysis['notes']) . '</div>';
        }
        echo '</section>';

        echo '<section class="apd-card"><h3>' . esc_html__('Design details', 'asuka-product-designer') . '</h3><ul class="apd-list">';
        echo '<li><strong>' . esc_html__('Object types', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['objectTypes'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Colors', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['colors'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Texts', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(' · ', (array) ($analysis['texts'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Catalog designs', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['catalogDesigns'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Catalog elements', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['catalogElements'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '<li><strong>' . esc_html__('Printing methods', 'asuka-product-designer') . ':</strong> ' . esc_html(implode(', ', (array) ($analysis['printingMethods'] ?? [])) ?: __('None', 'asuka-product-designer')) . '</li>';
        echo '</ul></section>';
        echo '</div>';

        echo '<div class="apd-section-grid">';
        echo '<section class="apd-card"><h3>' . esc_html__('View breakdown', 'asuka-product-designer') . '</h3>';
        if (! empty($analysis['viewDetails']) && is_array($analysis['viewDetails'])) {
            echo '<table class="apd-table"><thead><tr><th>' . esc_html__('View', 'asuka-product-designer') . '</th><th>' . esc_html__('Dimensions', 'asuka-product-designer') . '</th><th>' . esc_html__('Objects', 'asuka-product-designer') . '</th><th>' . esc_html__('Types', 'asuka-product-designer') . '</th></tr></thead><tbody>';
            foreach ($analysis['viewDetails'] as $view) {
                if (! is_array($view)) {
                    continue;
                }
                $dims = __('No dimensions', 'asuka-product-designer');
                if ((float) ($view['width'] ?? 0) > 0 && (float) ($view['height'] ?? 0) > 0) {
                    $dims = sprintf('%s × %s %s', rtrim(rtrim(number_format((float) $view['width'], 2, '.', ''), '0'), '.'), rtrim(rtrim(number_format((float) $view['height'], 2, '.', ''), '0'), '.'), (string) ($view['unit'] ?? 'px'));
                }
                $types = [];
                foreach ((array) ($view['objectTypes'] ?? []) as $type => $count) {
                    $types[] = sprintf('%s (%d)', (string) $type, (int) $count);
                }
                echo '<tr><td><strong>' . esc_html((string) ($view['name'] ?? $view['id'] ?? __('View', 'asuka-product-designer'))) . '</strong></td><td>' . esc_html($dims) . '</td><td>' . esc_html((string) (int) ($view['objectCount'] ?? 0)) . '</td><td>' . esc_html(implode(', ', $types) ?: __('None', 'asuka-product-designer')) . '</td></tr>';
            }
            echo '</tbody></table>';
        } else {
            echo '<p>' . esc_html__('No view data found.', 'asuka-product-designer') . '</p>';
        }
        echo '</section>';

        echo '<section class="apd-card"><h3>' . esc_html__('Pricing breakdown', 'asuka-product-designer') . '</h3>';
        if ($rows === [] && $rules === []) {
            echo '<p>' . esc_html__('No pricing breakdown captured for this item.', 'asuka-product-designer') . '</p>';
        } else {
            foreach ($rows as $row) {
                if (! is_array($row)) {
                    continue;
                }
                $type = $this->humanizeBreakdownLabel((string) ($row['type'] ?? __('Entry', 'asuka-product-designer')));
                $amount = wp_kses_post(wc_price((float) ($row['amount'] ?? 0)));
                echo '<div class="apd-rule"><div><strong>' . esc_html($type) . '</strong></div><div>' . wp_kses_post($amount) . '</div></div>';
            }
            if ($rules !== []) {
                echo '<h4 class="apd-subsection-title">' . esc_html__('Applied rules', 'asuka-product-designer') . '</h4>';
                foreach ($rules as $rule) {
                    if (! is_array($rule)) {
                        continue;
                    }
                    $meta = [];
                    if (! empty($rule['handler'])) {
                        $meta[] = (string) $rule['handler'];
                    }
                    if (! empty($rule['scope'])) {
                        $meta[] = (string) $rule['scope'];
                    }
                    echo '<div class="apd-rule"><div><strong>' . esc_html((string) ($rule['label'] ?? $rule['id'] ?? __('Rule', 'asuka-product-designer'))) . '</strong><div class="apd-rule__meta">' . esc_html(implode(' · ', $meta)) . '</div></div><div>' . wp_kses_post(wc_price((float) ($rule['amount'] ?? 0))) . '</div></div>';
                }
            }
        }
        echo '</section>';
        echo '</div>';

        echo '</div>';
        wp_print_scripts(['asuka-product-designer-production-worksheet']);
        echo '</body></html>';
    }

    protected function renderNotesEditor(array $pack, string $redirectUrl) : void
    {
        $action = esc_url(admin_url('admin-post.php'));
        echo '<form class="apd-production-notes" method="post" action="' . esc_url($action) . '">';
        echo '<input type="hidden" name="action" value="apd_save_production_notes">';
        echo '<input type="hidden" name="order_id" value="' . (int) ($pack['orderId'] ?? 0) . '">';
        echo '<input type="hidden" name="item_id" value="' . (int) ($pack['itemId'] ?? 0) . '">';
        echo '<input type="hidden" name="redirect" value="' . esc_attr(rawurlencode($redirectUrl)) . '">';
        wp_nonce_field('apd_update_production_notes_' . (int) ($pack['orderId'] ?? 0) . '_' . (int) ($pack['itemId'] ?? 0));
        echo '<label for="apd-production-notes"><strong>' . esc_html__('Workshop notes', 'asuka-product-designer') . '</strong></label>';
        echo '<textarea id="apd-production-notes" name="notes" rows="5" placeholder="' . esc_attr__('Add internal production notes, finishing instructions, or QA remarks…', 'asuka-product-designer') . '">' . esc_textarea((string) ($pack['productionNotes'] ?? '')) . '</textarea>';
        echo '<div class="apd-production-notes__actions">';
        submit_button(__('Save notes', 'asuka-product-designer'), 'secondary', '', false);
        echo '</div>';
        echo '</form>';
    }

    protected function resolvePack(int $orderId, int $itemId) : ?array
    {
        [$order, $item] = $this->resolveOrderAndItem($orderId, $itemId);
        if (! $order instanceof WC_Order || ! $item instanceof WC_Order_Item_Product) {
            return null;
        }

        return (new ProductionPackBuilder())->build($item, $order);
    }

    protected function resolveOrderAndItem(int $orderId, int $itemId) : array
    {
        $order = $orderId > 0 ? wc_get_order($orderId) : null;
        if (! $order instanceof WC_Order) {
            return [null, null];
        }
        $item = $itemId > 0 ? $order->get_item($itemId, false) : null;
        return [$order, $item instanceof WC_Order_Item_Product ? $item : null];
    }


}
