<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Support;

use Illuminate\Support\Str;

/**
 * 插件中心「使用指引」展示：表格摘要 + 侧滑详情分块数据。
 */
final class HostPluginCenterUsageGuidanceFormatter
{
    /**
     * @param  array<string, mixed>  $row
     */
    public function summaryForTableRow(array $row): string
    {
        $guidance = $row['usage_guidance'] ?? null;

        if (is_array($guidance)) {
            if (filled($guidance['disabled_hint'] ?? null)) {
                return (string) $guidance['disabled_hint'];
            }

            if (filled($guidance['permission_hint'] ?? null)) {
                return (string) $guidance['permission_hint'];
            }

            if (filled($guidance['main_entry_label'] ?? null)) {
                $summary = (string) $guidance['main_entry_label'];

                if ($this->additionalDetailCount($guidance) > 0) {
                    $summary .= ' · '.(string) __(
                        'dberp.plugin_center.usage_guidance.more_items',
                        ['count' => $this->additionalDetailCount($guidance)],
                    );
                }

                return $summary;
            }

            if (filled($guidance['description'] ?? null)) {
                return Str::limit((string) $guidance['description'], 56);
            }
        }

        $featureEntries = $row['feature_entries'] ?? [];

        if (count($featureEntries) === 1) {
            return (string) ($featureEntries[0]['label'] ?? '');
        }

        if (count($featureEntries) > 1) {
            $firstLabel = (string) ($featureEntries[0]['label'] ?? '');

            return $firstLabel.' · '.(string) __(
                'dberp.plugin_center.usage_guidance.feature_entries_count',
                ['count' => count($featureEntries)],
            );
        }

        return (string) __('dberp.plugin_center.installed.no_feature_entries');
    }

    /**
     * @param  array<string, mixed>  $row
     */
    public function summaryToneForTableRow(array $row): ?string
    {
        $guidance = $row['usage_guidance'] ?? null;

        if (! is_array($guidance)) {
            return null;
        }

        if (filled($guidance['disabled_hint'] ?? null) || filled($guidance['permission_hint'] ?? null)) {
            return 'warning';
        }

        return null;
    }

    /**
     * @param  array<string, mixed>  $row
     */
    public function shouldOfferDetailAction(array $row): bool
    {
        foreach ($this->blocksForModal($row) as $block) {
            if (($block['kind'] ?? '') !== 'alert') {
                return true;
            }
        }

        return false;
    }

    /**
     * @param  array<string, mixed>  $row
     * @return list<array{
     *     kind: string,
     *     label?: string,
     *     value?: string,
     *     tone?: string,
     *     links?: list<array{label: string, url: string}>
     * }>
     */
    public function blocksForModal(array $row): array
    {
        $blocks = [];
        $guidance = $row['usage_guidance'] ?? null;

        if (is_array($guidance)) {
            if (filled($guidance['disabled_hint'] ?? null)) {
                $blocks[] = [
                    'kind' => 'alert',
                    'tone' => 'warning',
                    'value' => (string) $guidance['disabled_hint'],
                ];
            }

            if (filled($guidance['permission_hint'] ?? null)) {
                $blocks[] = [
                    'kind' => 'alert',
                    'tone' => 'warning',
                    'value' => (string) $guidance['permission_hint'],
                ];
            }

            if (filled($guidance['description'] ?? null)) {
                $blocks[] = [
                    'kind' => 'text',
                    'value' => (string) $guidance['description'],
                ];
            }

            if (filled($guidance['main_entry_label'] ?? null)) {
                $mainEntryBlock = [
                    'kind' => 'field',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.labels.main_entry'),
                    'value' => (string) $guidance['main_entry_label'],
                ];

                if (filled($guidance['main_entry_url'] ?? null)) {
                    $mainEntryBlock['url'] = (string) $guidance['main_entry_url'];
                }

                $blocks[] = $mainEntryBlock;
            }

            if (filled($guidance['import_entry_label'] ?? null)) {
                $blocks[] = [
                    'kind' => 'field',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.labels.import_entry'),
                    'value' => (string) $guidance['import_entry_label'],
                ];
            }

            if (filled($guidance['export_entry_label'] ?? null)) {
                $blocks[] = [
                    'kind' => 'field',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.labels.export_entry'),
                    'value' => (string) $guidance['export_entry_label'],
                ];
            }

            if (($guidance['host_locations'] ?? []) !== []) {
                $blocks[] = [
                    'kind' => 'field',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.labels.host_locations'),
                    'value' => implode('、', $guidance['host_locations']),
                ];
            }

            if (filled($guidance['settings_purpose'] ?? null)) {
                $blocks[] = [
                    'kind' => 'field',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.labels.settings_purpose'),
                    'value' => (string) $guidance['settings_purpose'],
                ];
            }

            if (filled($guidance['permission_status_label'] ?? null)) {
                $blocks[] = [
                    'kind' => 'badge',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.labels.permission_status'),
                    'value' => (string) $guidance['permission_status_label'],
                    'tone' => (string) ($guidance['permission_status_tone'] ?? 'gray'),
                ];
            }

            if (($guidance['quick_links'] ?? []) !== []) {
                $blocks[] = [
                    'kind' => 'links',
                    'label' => (string) __('dberp.plugin_center.usage_guidance.quick_links_heading'),
                    'links' => array_values(array_filter(
                        $guidance['quick_links'],
                        static fn (mixed $entry): bool => is_array($entry)
                            && filled($entry['label'] ?? null)
                            && filled($entry['url'] ?? null),
                    )),
                ];
            }

            return $blocks;
        }

        $featureEntries = array_values(array_filter(
            $row['feature_entries'] ?? [],
            static fn (mixed $entry): bool => is_array($entry)
                && filled($entry['label'] ?? null)
                && filled($entry['url'] ?? null),
        ));

        if ($featureEntries !== []) {
            $blocks[] = [
                'kind' => 'links',
                'label' => (string) __('dberp.plugin_center.usage_guidance.feature_entries_heading'),
                'links' => array_map(
                    static fn (array $entry): array => [
                        'label' => (string) $entry['label'],
                        'url' => (string) $entry['url'],
                    ],
                    $featureEntries,
                ),
            ];
        }

        return $blocks;
    }

    /**
     * @param  array<string, mixed>  $guidance
     */
    private function additionalDetailCount(array $guidance): int
    {
        $count = 0;

        if (filled($guidance['description'] ?? null)) {
            $count++;
        }

        if (filled($guidance['import_entry_label'] ?? null)) {
            $count++;
        }

        if (filled($guidance['export_entry_label'] ?? null)) {
            $count++;
        }

        if (($guidance['host_locations'] ?? []) !== []) {
            $count++;
        }

        if (filled($guidance['settings_purpose'] ?? null)) {
            $count++;
        }

        if (filled($guidance['permission_status_label'] ?? null)) {
            $count++;
        }

        $count += count($guidance['quick_links'] ?? []);

        return $count;
    }
}
