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

defined('ABSPATH') || exit;

class DesignSummary
{
    public static function build(array $design, array $state = []) : array
    {
        $objects = [];
        $byView = $design['objects']['byView'] ?? [];
        if (is_array($byView)) {
            foreach ($byView as $viewObjects) {
                if (! is_array($viewObjects)) {
                    continue;
                }
                foreach ($viewObjects as $object) {
                    if (is_array($object)) {
                        $objects[] = $object;
                    }
                }
            }
        }

        $objectTypes = [];
        $colors = [];
        $texts = [];

        foreach ($objects as $object) {
            $type = self::normalizeObjectType((string) ($object['itemGroup'] ?? $object['type'] ?? 'Object'));
            if ($type !== '') {
                $objectTypes[$type] = true;
            }

            foreach (['fill', 'stroke', 'textBackgroundColor'] as $colorKey) {
                $value = trim((string) ($object[$colorKey] ?? ''));
                if ($value === '' || $value === 'transparent' || $value === 'none' || stripos($value, 'rgb(0,0,0)') !== false) {
                    continue;
                }
                $colors[$value] = true;
            }

            $text = trim((string) ($object['text'] ?? ''));
            if ($text !== '') {
                $texts[$text] = true;
            }
        }

        $catalog = is_array($state['catalog'] ?? null) ? $state['catalog'] : [];
        $catalogElements = self::extractCatalogLabels($catalog['elements'] ?? []);
        $catalogDesigns = self::extractCatalogLabels($catalog['designs'] ?? []);
        $views = is_array($design['views']['views'] ?? null) ? $design['views']['views'] : [];

        return [
            'viewCount' => count($views),
            'objectCount' => count($objects),
            'objectTypes' => array_values(array_slice(array_keys($objectTypes), 0, 8)),
            'colors' => array_values(array_slice(array_keys($colors), 0, 8)),
            'texts' => array_values(array_slice(array_keys($texts), 0, 3)),
            'catalogElements' => array_values(array_slice($catalogElements, 0, 8)),
            'catalogDesigns' => array_values(array_slice($catalogDesigns, 0, 8)),
        ];
    }

    public static function describe(array $summary) : string
    {
        $parts = [];
        $viewCount = absint($summary['viewCount'] ?? 0);
        $objectCount = absint($summary['objectCount'] ?? 0);
        if ($viewCount > 0) {
            $parts[] = sprintf(
                /* translators: Placeholder values are populated from the current Asuka Designer record. */ _n('%d view', '%d views', $viewCount, 'asuka-product-designer'),
                $viewCount
            );
        }
        if ($objectCount > 0) {
            $parts[] = sprintf(
                /* translators: Placeholder values are populated from the current Asuka Designer record. */ _n('%d object', '%d objects', $objectCount, 'asuka-product-designer'),
                $objectCount
            );
        }
        return implode(' · ', $parts);
    }

    protected static function normalizeObjectType(string $type) : string
    {
        $type = trim($type);
        if ($type === '') {
            return '';
        }

        $map = [
            'Textbox' => __('Text', 'asuka-product-designer'),
            'IText' => __('Text', 'asuka-product-designer'),
            'Text' => __('Text', 'asuka-product-designer'),
            'Image' => __('Image', 'asuka-product-designer'),
            'image' => __('Image', 'asuka-product-designer'),
            'Rect' => __('Shape', 'asuka-product-designer'),
            'Circle' => __('Shape', 'asuka-product-designer'),
            'Triangle' => __('Shape', 'asuka-product-designer'),
            'Polygon' => __('Shape', 'asuka-product-designer'),
            'Path' => __('Path', 'asuka-product-designer'),
            'Text' => __('Text', 'asuka-product-designer'),
        ];

        return $map[$type] ?? $type;
    }

    protected static function extractCatalogLabels($items) : array
    {
        if (! is_array($items)) {
            return [];
        }

        $labels = [];
        foreach ($items as $item) {
            if (! is_array($item)) {
                continue;
            }
            $label = trim((string) ($item['label'] ?? $item['name'] ?? $item['title'] ?? $item['id'] ?? ''));
            if ($label !== '') {
                $labels[$label] = true;
            }
        }

        return array_values(array_keys($labels));
    }
}
