<?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\WooCommerce;

use APD\Repositories\UserDesignRepository;
use APD\Support\DesignSummary;
use APD\Support\PreviewStorage;
use APD\Support\PricingSnapshot;
use APD\Support\ProductionPackBuilder;
use APD\Support\UserDesignLinks;
use WC_Order;
use WC_Order_Item;
use WC_Order_Item_Product;

defined('ABSPATH') || exit;

class OrderIntegration
{
    public function boot(WC_Order_Item_Product $item, string $cartItemKey, array $values, WC_Order $order) : void
    {
        if (empty($values['apd']) || ! is_array($values['apd'])) {
            return;
        }

        $apd = $values['apd'];
        $summary = is_array($apd['design_summary'] ?? null) ? $apd['design_summary'] : [];
        $configTitle = (string) ($apd['config_title'] ?? '');
        $pricingPayload = PricingSnapshot::normalize($apd['pricing_payload'] ?? ($apd['price_breakdown'] ?? []), (float) ($apd['price_base'] ?? 0));

        $item->add_meta_data('_apd_config_id', absint($apd['config_id'] ?? 0), true);
        $item->add_meta_data('_apd_config_title', $configTitle, true);
        $item->add_meta_data('_apd_product_id', absint($apd['product_id'] ?? 0), true);
        $item->add_meta_data('_apd_product_title', (string) ($apd['product_title'] ?? ''), true);
        $item->add_meta_data('_apd_product_sku', (string) ($apd['product_sku'] ?? ''), true);
        $item->add_meta_data('_apd_variation_id', absint($apd['variation_id'] ?? 0), true);
        $item->add_meta_data('_apd_variation_label', (string) ($apd['variation_label'] ?? ''), true);
        $item->add_meta_data('_apd_variation_attributes', wp_json_encode($apd['variation_attributes'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), true);
        $item->add_meta_data('_apd_user_design_id', absint($apd['user_design_id'] ?? 0), true);
        $item->add_meta_data('_apd_design_json', (string) ($apd['design_json'] ?? ''), true);
        $item->add_meta_data('_apd_state_json', (string) ($apd['state_json'] ?? ''), true);
        $item->add_meta_data('_apd_design_summary', wp_json_encode($summary, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), true);
        $item->add_meta_data('_apd_preview_url', (string) ($apd['preview_url'] ?? ''), true);
        $item->add_meta_data('_apd_preview_attachment_id', absint($apd['preview_attachment_id'] ?? 0), true);
        $item->add_meta_data('_apd_resume_url', (string) ($apd['resume_url'] ?? ''), true);
        $item->add_meta_data('_apd_payload_version', (int) ($pricingPayload['payload_version'] ?? PricingSnapshot::VERSION), true);
        $item->add_meta_data('_apd_pricing_payload', wp_json_encode($pricingPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), true);
        $item->add_meta_data('_apd_price_base', (float) ($pricingPayload['base_price'] ?? ($apd['price_base'] ?? 0)), true);
        $item->add_meta_data('_apd_price_adjustment', (float) ($pricingPayload['adjustment_total'] ?? ($apd['price_adjustment'] ?? 0)), true);
        $item->add_meta_data('_apd_price_total', (float) ($pricingPayload['final_price'] ?? ($apd['price_total'] ?? 0)), true);
        $item->add_meta_data('_apd_price_breakdown', wp_json_encode($pricingPayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), true);
        $item->add_meta_data('_apd_production_status', 'pending', true);

        $repo = new UserDesignRepository();

        $userDesignId = absint($apd['user_design_id'] ?? 0);
        $existing = $userDesignId > 0 ? $repo->find($userDesignId) : [];
        $accessToken = (string) ($existing['accessToken'] ?? '');
        $resumeUrl = UserDesignLinks::buildResumeUrl(absint($apd['product_id'] ?? 0), $userDesignId, $accessToken, true, [
            'variation_id' => absint($apd['variation_id'] ?? 0),
            'attributes' => is_array($apd['variation_attributes'] ?? null) ? $apd['variation_attributes'] : [],
        ]);

        $payload = [
            'title' => sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ __('Order #%1$d / Item %2$s', 'asuka-product-designer'), (int) $order->get_id(), (string) $cartItemKey),
            'userId' => (int) $order->get_user_id(),
            'configId' => absint($apd['config_id'] ?? 0),
            'productId' => absint($apd['product_id'] ?? 0),
            'orderId' => (int) $order->get_id(),
            'orderItemId' => (int) $item->get_id(),
            'designJson' => $this->decodeJson((string) ($apd['design_json'] ?? '')),
            'stateJson' => $this->decodeJson((string) ($apd['state_json'] ?? '')),
            'previewUrls' => ! empty($apd['preview_url']) ? [(string) $apd['preview_url']] : [],
            'productionData' => [
                'quantity' => (int) ($values['quantity'] ?? 1),
                'source' => 'woocommerce_checkout',
                'variationId' => absint($apd['variation_id'] ?? 0),
                'variationAttributes' => is_array($apd['variation_attributes'] ?? null) ? $apd['variation_attributes'] : [],
                'priceBase' => (float) ($pricingPayload['base_price'] ?? ($apd['price_base'] ?? 0)),
                'priceAdjustment' => (float) ($pricingPayload['adjustment_total'] ?? ($apd['price_adjustment'] ?? 0)),
                'priceTotal' => (float) ($pricingPayload['final_price'] ?? ($apd['price_total'] ?? 0)),
                'payloadVersion' => (int) ($pricingPayload['payload_version'] ?? PricingSnapshot::VERSION),
                'resumeUrl' => $resumeUrl,
                'summary' => $summary,
                'configTitle' => $configTitle,
                'productTitle' => (string) ($apd['product_title'] ?? ''),
                'productSku' => (string) ($apd['product_sku'] ?? ''),
                'variationLabel' => (string) ($apd['variation_label'] ?? ''),
                'previewUrl' => (string) ($apd['preview_url'] ?? ''),
                'orderStatus' => (string) $order->get_status(),
            ],
            'priceSnapshot' => $pricingPayload,
            'accessToken' => $accessToken !== '' ? $accessToken : wp_generate_password(20, false, false),
        ];

        if ($userDesignId > 0) {
            $repo->update($userDesignId, $payload);
        } else {
            $createdId = $repo->create($payload);
            if ($createdId > 0) {
                $userDesignId = $createdId;
                $item->update_meta_data('_apd_user_design_id', $createdId);
            }
        }

        $finalDesign = $userDesignId > 0 ? $repo->find($userDesignId) : [];
        $finalResumeUrl = UserDesignLinks::buildResumeUrl(absint($apd['product_id'] ?? 0), $userDesignId, (string) ($finalDesign['accessToken'] ?? ($payload['accessToken'] ?? '')), true, [
            'variation_id' => absint($apd['variation_id'] ?? 0),
            'attributes' => is_array($apd['variation_attributes'] ?? null) ? $apd['variation_attributes'] : [],
        ]);
        if ($finalResumeUrl !== '') {
            $item->update_meta_data('_apd_resume_url', $finalResumeUrl);
        }
        $item->update_meta_data('_apd_production_data', wp_json_encode($payload['productionData'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    public function finalizeOrderLinks(WC_Order $order) : void
    {
        $orderId = (int) $order->get_id();
        if ($orderId <= 0) {
            return;
        }

        $repo = new UserDesignRepository();
        foreach ($order->get_items('line_item') as $item) {
            if (! $item instanceof WC_Order_Item_Product) {
                continue;
            }

            $itemId = (int) $item->get_id();
            $userDesignId = absint($item->get_meta('_apd_user_design_id', true));
            $this->promoteOrderPreview($item);
            if ($itemId <= 0 || $userDesignId <= 0) {
                continue;
            }

            $userDesign = $repo->find($userDesignId);
            if ($userDesign === []) {
                continue;
            }

            $productionData = is_array($userDesign['productionData'] ?? null) ? $userDesign['productionData'] : [];
            $productionData['quantity'] = (int) $item->get_quantity();
            $productionData['orderStatus'] = (string) $order->get_status();

            $repo->update($userDesignId, [
                'orderId' => $orderId,
                'orderItemId' => $itemId,
                'productionData' => $productionData,
            ]);
        }
    }

    protected function promoteOrderPreview(WC_Order_Item_Product $item) : void
    {
        $attachmentId = absint($item->get_meta('_apd_preview_attachment_id', true));
        if ($attachmentId <= 0) {
            $previewUrl = esc_url_raw((string) $item->get_meta('_apd_preview_url', true));
            if ($previewUrl !== '') {
                $attachmentId = (new PreviewStorage())->attachmentIdFromUrl($previewUrl);
            }
        }

        if (
            $attachmentId <= 0
            || get_post_type($attachmentId) !== 'attachment'
            || (string) get_post_meta($attachmentId, '_apd_temporary_preview', true) !== '1'
        ) {
            return;
        }

        delete_post_meta($attachmentId, '_apd_temporary_preview');
        update_post_meta($attachmentId, '_apd_preview_context', 'order');

        if (absint($item->get_meta('_apd_preview_attachment_id', true)) <= 0) {
            $item->update_meta_data('_apd_preview_attachment_id', $attachmentId);
            $item->save_meta_data();
        }
    }

    public function enqueueCustomerOrderAssets() : void
    {
        if (is_admin() || wp_doing_ajax()) {
            return;
        }

        if (! function_exists('is_account_page') || ! function_exists('is_order_received_page')) {
            return;
        }

        if (! is_account_page() && ! is_order_received_page()) {
            return;
        }

        wp_enqueue_style('apd-front');
    }

    public function filterMyAccountOrderActions(array $actions, WC_Order $order) : array
    {
        $packs = $this->getCustomizedPacks($order);
        if ($packs === []) {
            return $actions;
        }

        $targetUrl = '';
        if (count($packs) === 1 && ! empty($packs[0]['resumeUrl'])) {
            $targetUrl = (string) $packs[0]['resumeUrl'];
        }

        if ($targetUrl === '') {
            $targetUrl = $order->get_view_order_url() . '#apd-order-designs';
        }

        $actions['apd_designs'] = [
            'url' => $targetUrl,
            'name' => count($packs) === 1 ? __('Open saved design', 'asuka-product-designer') : __('View customizations', 'asuka-product-designer'),
        ];

        return $actions;
    }

    public function filterOrderItemPermalink(string $permalink, WC_Order_Item_Product $item, WC_Order $order) : string
    {
        $resumeUrl = (string) $item->get_meta('_apd_resume_url', true);
        return $resumeUrl !== '' ? $resumeUrl : $permalink;
    }

    public function renderResumeLink(int $itemId, WC_Order_Item_Product $item, WC_Order $order, bool $plainText = false) : void
    {
        $resumeUrl = (string) $item->get_meta('_apd_resume_url', true);
        $previewUrl = $this->resolveOrderItemImageUrl($item);
        $configId = absint($item->get_meta('_apd_config_id', true));
        $configTitle = trim((string) $item->get_meta('_apd_config_title', true));
        $summary = $this->decodeJson((string) $item->get_meta('_apd_design_summary', true));
        $summaryText = DesignSummary::describe($summary);
        $priceBase = (float) $item->get_meta('_apd_price_base', true);
        $priceAdjustment = (float) $item->get_meta('_apd_price_adjustment', true);
        $priceTotal = (float) $item->get_meta('_apd_price_total', true);

        if ($resumeUrl === '' && $previewUrl === '' && $configId <= 0) {
            return;
        }

        if (is_admin()) {
            if ($resumeUrl === '') {
                return;
            }
            echo '<div class="apd-order-resume-link"><a href="' . esc_url($resumeUrl) . '">' . esc_html__('Open this saved customization', 'asuka-product-designer') . '</a></div>';
            return;
        }

        if ($plainText) {
            echo "\n" . esc_html__('Asuka Designer:', 'asuka-product-designer');
            if ($configId > 0 || $configTitle !== '') {
                $label = $configTitle !== '' ? $configTitle : sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Custom Product #%d', 'asuka-product-designer'), $configId);
                echo ' ' . esc_html($label);
            }
            if ($summaryText !== '') {
                echo ' · ' . esc_html($summaryText);
            }
            if (! empty($summary['objectTypes']) && is_array($summary['objectTypes'])) {
                echo ' · ' . esc_html(implode(', ', $summary['objectTypes']));
            }
            if (abs($priceAdjustment) > 0.00001) {
                echo ' · ' . sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Adjustment %s', 'asuka-product-designer'), esc_html(wp_strip_all_tags(wc_price($priceAdjustment))));
            }
            if ($priceTotal > 0) {
                echo ' · ' . sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ esc_html__('Final %s', 'asuka-product-designer'), esc_html(wp_strip_all_tags(wc_price($priceTotal))));
            }
            if ($resumeUrl !== '') {
                echo "\n" . esc_html__('Resume customization:', 'asuka-product-designer') . ' ' . esc_url($resumeUrl);
            }
            echo "\n";
            return;
        }

        $buttons = [];
        if ($resumeUrl !== '') {
            $buttons[] = [
                'label' => __('Open saved design', 'asuka-product-designer'),
                'url' => $resumeUrl,
                'variant' => 'primary',
            ];
        }
        $productLink = $this->resolveProductLink($item);
        if ($productLink !== '' && $productLink !== $resumeUrl) {
            $buttons[] = [
                'label' => __('View product', 'asuka-product-designer'),
                'url' => $productLink,
                'variant' => 'secondary',
            ];
        }

        echo '<div class="apd-customer-order-summary">';
        if ($previewUrl !== '') {
            echo '<div class="apd-customer-order-summary__media"><img src="' . esc_url($previewUrl) . '" alt="' . esc_attr__('Design preview', 'asuka-product-designer') . '" class="apd-customer-order-summary__image"></div>';
        }
        echo '<div class="apd-customer-order-summary__content">';
        echo '<div class="apd-customer-order-summary__eyebrow">' . esc_html__('Customized with Asuka Designer', 'asuka-product-designer') . '</div>';
        if ($configId > 0 || $configTitle !== '') {
            echo '<div class="apd-customer-order-summary__title">' . esc_html($configTitle !== '' ? $configTitle : ('#' . $configId)) . '</div>';
        }
        if ($summaryText !== '') {
            echo '<p class="apd-customer-order-summary__text">' . esc_html($summaryText) . '</p>';
        }
        echo wp_kses_post($this->renderSummaryChips($summary));
        echo '<div class="apd-customer-order-summary__pricing">';
        echo '<span>' . esc_html__('Base', 'asuka-product-designer') . ' ' . wp_kses_post(wc_price($priceBase)) . '</span>';
        if (abs($priceAdjustment) > 0.00001) {
            echo '<span>' . esc_html__('Adjustment', 'asuka-product-designer') . ' ' . wp_kses_post(wc_price($priceAdjustment)) . '</span>';
        }
        if ($priceTotal > 0) {
            echo '<strong>' . esc_html__('Final', 'asuka-product-designer') . ' ' . wp_kses_post(wc_price($priceTotal)) . '</strong>';
        }
        echo '</div>';
        if ($buttons !== []) {
            echo '<div class="apd-customer-order-summary__actions">';
            foreach ($buttons as $button) {
                echo '<a class="apd-customer-order-summary__button apd-customer-order-summary__button--' . esc_attr((string) $button['variant']) . '" href="' . esc_url((string) $button['url']) . '">' . esc_html((string) $button['label']) . '</a>';
            }
            echo '</div>';
        }
        echo '</div>';
        echo '</div>';
    }

    public function renderCustomerOrderExperience(int|WC_Order $orderOrId) : void
    {
        if (is_admin()) {
            return;
        }

        $order = $orderOrId instanceof WC_Order ? $orderOrId : wc_get_order((int) $orderOrId);
        if (! $order instanceof WC_Order) {
            return;
        }

        static $rendered = [];
        $orderId = (int) $order->get_id();
        if (isset($rendered[$orderId])) {
            return;
        }
        $rendered[$orderId] = true;

        $packs = $this->getCustomizedPacks($order);
        if ($packs === []) {
            return;
        }

        echo '<section id="apd-order-designs" class="apd-customer-designs">';
        echo '<div class="apd-customer-designs__header">';
        echo '<div>';
        echo '<span class="apd-customer-designs__eyebrow">' . esc_html__('Asuka Designer', 'asuka-product-designer') . '</span>';
        echo '<h2 class="apd-customer-designs__title">' . esc_html__('Your customized products', 'asuka-product-designer') . '</h2>';
        echo '<p class="apd-customer-designs__intro">' . esc_html__('Review each saved customization, reopen it, or reuse it from your order history.', 'asuka-product-designer') . '</p>';
        echo '</div>';
        echo '<span class="apd-customer-designs__count">' . esc_html(sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ _n('%d customization', '%d customizations', count($packs), 'asuka-product-designer'), count($packs))) . '</span>';
        echo '</div>';
        echo '<div class="apd-customer-designs__grid">';
        foreach ($packs as $pack) {
            echo wp_kses_post($this->renderCustomerPackCard($pack, $order));
        }
        echo '</div>';
        echo '</section>';
    }

    public function filterOrderItemName(string $itemName, WC_Order_Item $item, bool $isVisible) : string
    {
        if (! $item instanceof WC_Order_Item_Product) {
            return $itemName;
        }

        $previewUrl = $this->resolveOrderItemImageUrl($item);
        if ($previewUrl === '') {
            return $itemName;
        }

        $imageHtml = '<span class="apd-order-item-thumb"><img class="apd-order-item-thumb__image" src="' . esc_url($previewUrl) . '" alt="' . esc_attr__('Customized product preview', 'asuka-product-designer') . '" /></span>';

        if (str_contains($itemName, 'apd-order-item-thumb')) {
            return $itemName;
        }

        return $imageHtml . '<span class="apd-order-item-name">' . $itemName . '</span>';
    }

    protected function getCustomizedPacks(WC_Order $order) : array
    {
        $builder = new ProductionPackBuilder();
        $packs = [];
        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'])) {
                $packs[] = $pack;
            }
        }

        return $packs;
    }

    protected function renderCustomerPackCard(array $pack, WC_Order $order) : string
    {
        $previewUrl = (string) ($pack['previewUrl'] ?? '');
        $resumeUrl = (string) ($pack['resumeUrl'] ?? '');
        $productUrl = '';
        $product = wc_get_product((int) ($pack['variationId'] ?: $pack['productId']));
        if ($product && $product->is_visible()) {
            $productUrl = (string) $product->get_permalink();
        }

        $summary = is_array($pack['summary'] ?? null) ? $pack['summary'] : [];
        $summaryText = DesignSummary::describe($summary);
        $chips = $this->buildPackHighlights($pack);
        $pricing = is_array($pack['price'] ?? null) ? $pack['price'] : [];
        $status = sanitize_html_class((string) ($pack['productionStatus'] ?? 'pending'));
        $statusLabel = (string) ($pack['productionStatusLabel'] ?? ProductionPackBuilder::statusLabel((string) ($pack['productionStatus'] ?? 'pending')));
        $variationHtml = $this->formatVariationAttributes(is_array($pack['variationAttributes'] ?? null) ? $pack['variationAttributes'] : []);
        $title = (string) ($pack['itemName'] ?? __('Customized product', 'asuka-product-designer'));
        $configTitle = trim((string) ($pack['configTitle'] ?? ''));

        ob_start();
        ?>
        <article class="apd-customer-design-card">
            <div class="apd-customer-design-card__media">
                <?php if ($previewUrl !== '') : ?>
                    <img src="<?php echo esc_url($previewUrl); ?>" alt="<?php echo esc_attr__('Design preview', 'asuka-product-designer'); ?>" class="apd-customer-design-card__image" />
                <?php else : ?>
                    <div class="apd-customer-design-card__placeholder"><?php esc_html_e('Preview unavailable', 'asuka-product-designer'); ?></div>
                <?php endif; ?>
                <span class="apd-customer-design-card__status apd-customer-design-card__status--<?php echo esc_attr($status); ?>"><?php echo esc_html($statusLabel); ?></span>
            </div>
            <div class="apd-customer-design-card__body">
                <div class="apd-customer-design-card__eyebrow"><?php echo esc_html($configTitle !== '' ? $configTitle : __('Customized product', 'asuka-product-designer')); ?></div>
                <h3 class="apd-customer-design-card__title"><?php echo esc_html($title); ?></h3>
                <?php if ($summaryText !== '') : ?>
                    <p class="apd-customer-design-card__summary"><?php echo esc_html($summaryText); ?></p>
                <?php endif; ?>
                <?php if ($variationHtml !== '') : ?>
                    <div class="apd-customer-design-card__meta"><?php echo wp_kses_post($variationHtml); ?></div>
                <?php endif; ?>
                <?php if ($chips !== []) : ?>
                    <div class="apd-customer-design-card__chips">
                        <?php foreach ($chips as $chip) : ?>
                            <span class="apd-customer-design-card__chip"><?php echo esc_html($chip); ?></span>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <div class="apd-customer-design-card__pricing">
                    <div>
                        <span><?php esc_html_e('Customized unit price', 'asuka-product-designer'); ?></span>
                        <strong><?php echo wp_kses_post(wc_price((float) ($pricing['total'] ?? 0))); ?></strong>
                    </div>
                    <?php if (abs((float) ($pricing['adjustment'] ?? 0)) > 0.00001) : ?>
                        <div>
                            <span><?php esc_html_e('Customization', 'asuka-product-designer'); ?></span>
                            <strong><?php echo wp_kses_post(wc_price((float) ($pricing['adjustment'] ?? 0))); ?></strong>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="apd-customer-design-card__actions">
                    <?php if ($resumeUrl !== '') : ?>
                        <a class="apd-customer-design-card__button apd-customer-design-card__button--primary" href="<?php echo esc_url($resumeUrl); ?>"><?php esc_html_e('Open saved design', 'asuka-product-designer'); ?></a>
                    <?php endif; ?>
                    <?php if ($productUrl !== '' && $productUrl !== $resumeUrl) : ?>
                        <a class="apd-customer-design-card__button apd-customer-design-card__button--secondary" href="<?php echo esc_url($productUrl); ?>"><?php esc_html_e('View product', 'asuka-product-designer'); ?></a>
                    <?php endif; ?>
                </div>
            </div>
        </article>
        <?php
        return (string) ob_get_clean();
    }

    protected function buildPackHighlights(array $pack) : array
    {
        $summary = is_array($pack['summary'] ?? null) ? $pack['summary'] : [];
        $highlights = [];
        if (! empty($summary['objectTypes']) && is_array($summary['objectTypes'])) {
            $highlights[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ _n('%d object type', '%d object types', count($summary['objectTypes']), 'asuka-product-designer'), count($summary['objectTypes']));
        }
        if (! empty($summary['colors']) && is_array($summary['colors'])) {
            $highlights[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ _n('%d color', '%d colors', count($summary['colors']), 'asuka-product-designer'), count($summary['colors']));
        }
        if (! empty($summary['texts']) && is_array($summary['texts'])) {
            $highlights[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ _n('%d text', '%d texts', count($summary['texts']), 'asuka-product-designer'), count($summary['texts']));
        }
        if (! empty($pack['views']) && is_array($pack['views'])) {
            $highlights[] = sprintf(/* translators: Placeholder values are populated from the current WooCommerce product, cart, or order. */ _n('%d view', '%d views', count($pack['views']), 'asuka-product-designer'), count($pack['views']));
        }

        return array_slice($highlights, 0, 4);
    }

    protected function renderSummaryChips(array $summary) : string
    {
        $chips = [];
        foreach ([
            'objectTypes' => __('Objects', 'asuka-product-designer'),
            'colors' => __('Colors', 'asuka-product-designer'),
            'catalogDesigns' => __('Designs', 'asuka-product-designer'),
        ] as $key => $label) {
            if (! empty($summary[$key]) && is_array($summary[$key])) {
                $chips[] = '<span class="apd-customer-order-summary__chip"><strong>' . esc_html($label) . ':</strong> ' . esc_html(implode(', ', array_slice(array_values($summary[$key]), 0, 3))) . '</span>';
            }
        }

        if ($chips === []) {
            return '';
        }

        return '<div class="apd-customer-order-summary__chips">' . implode('', $chips) . '</div>';
    }

    protected function formatVariationAttributes(array $attributes) : string
    {
        if ($attributes === []) {
            return '';
        }

        $parts = [];
        foreach ($attributes as $key => $value) {
            $labelKey = is_string($key) ? preg_replace('/^attribute_/', '', $key) : '';
            $label = $labelKey !== '' ? wc_attribute_label($labelKey) : (string) $key;
            $parts[] = '<span><strong>' . esc_html($label) . ':</strong> ' . esc_html((string) $value) . '</span>';
        }

        return implode(' · ', $parts);
    }

    protected function resolveProductLink(WC_Order_Item_Product $item) : string
    {
        $product = $item->get_product();
        if (! $product) {
            return '';
        }

        $permalink = $product->get_permalink();
        return is_string($permalink) ? $permalink : '';
    }

    protected function resolveOrderItemImageUrl(WC_Order_Item_Product $item) : string
    {
        $previewUrl = esc_url_raw((string) $item->get_meta('_apd_preview_url', true));
        if ($previewUrl !== '') {
            return $previewUrl;
        }

        $configId = absint($item->get_meta('_apd_config_id', true));
        if ($configId > 0) {
            $thumbnailId = get_post_thumbnail_id($configId);
            if ($thumbnailId > 0) {
                $image = wp_get_attachment_image_url($thumbnailId, 'woocommerce_thumbnail');
                if (is_string($image) && $image !== '') {
                    return $image;
                }
            }
        }

        $productId = absint($item->get_meta('_apd_variation_id', true)) ?: absint($item->get_meta('_apd_product_id', true));
        if ($productId > 0) {
            $image = get_the_post_thumbnail_url($productId, 'woocommerce_thumbnail');
            if (is_string($image) && $image !== '') {
                return $image;
            }
        }

        return '';
    }

    protected function decodeJson(string $json) : array
    {
        $decoded = json_decode($json, true);
        return is_array($decoded) ? $decoded : [];
    }
}
