<?php

declare(strict_types=1);

final class MicTableResolver implements MicElementResolverInterface, MicElementSearchable
{
    public function __construct(private readonly MicTableRepository $repository)
    {
    }

    public function extractSearchText(array $blockData): ?string
    {
        $id = trim((string) ($blockData['id'] ?? ''));
        if ($id === '') {
            return null;
        }
        $table = $this->repository->findById($id);
        if ($table === null) {
            return null;
        }
        $parts = [];
        $caption = trim((string) ($table['caption'] ?? ''));
        if ($caption !== '') {
            $parts[] = $caption;
        }
        $columns = is_array($table['columns'] ?? null) ? $table['columns'] : [];
        foreach ($columns as $column) {
            $label = trim((string) ($column['label'] ?? ''));
            if ($label !== '') {
                $parts[] = $label;
            }
        }
        $rows = is_array($table['rows'] ?? null) ? $table['rows'] : [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            foreach ($row as $cell) {
                $value = trim(strip_tags((string) $cell));
                if ($value !== '') {
                    $parts[] = $value;
                }
            }
        }
        return $parts === [] ? null : implode(' ', $parts);
    }

    public function resolve(string $id, array $context): ?string
    {
        $table = $this->repository->findById($id);
        if ($table === null) {
            return null;
        }

        $columns = is_array($table['columns'] ?? null) ? $table['columns'] : [];
        $rows = is_array($table['rows'] ?? null) ? $table['rows'] : [];
        $classes = [
            'myron-mic-table',
            'myron-mic-table--header-' . myronNormalizeSlug((string) ($table['header_style'] ?? 'default')),
            'myron-mic-table--responsive-' . myronNormalizeSlug((string) ($table['responsive_strategy'] ?? 'scroll')),
        ];
        $attrs = ' class="' . myronEscape(implode(' ', $classes)) . '"';
        if ((string) ($context['channel'] ?? 'public') === 'admin-preview') {
            $attrs .= ' data-mic-table-id="' . myronEscape((string) ($table['id'] ?? '')) . '"';
        }

        $html = [];
        $html[] = '<div' . $attrs . '>';
        $html[] = '<table>';
        if (trim((string) ($table['caption'] ?? '')) !== '') {
            $html[] = '<caption>' . myronEscape((string) $table['caption']) . '</caption>';
        }
        if (($table['header_style'] ?? 'default') !== 'none') {
            $html[] = '<thead><tr>';
            foreach ($columns as $column) {
                $align = $this->alignmentClass((string) ($column['alignment'] ?? 'start'));
                $html[] = '<th class="' . $align . '">' . myronEscape((string) ($column['label'] ?? '')) . '</th>';
            }
            $html[] = '</tr></thead>';
        }
        $html[] = '<tbody>';
        foreach ($rows as $row) {
            $html[] = '<tr>';
            foreach ($columns as $index => $column) {
                $align = $this->alignmentClass((string) ($column['alignment'] ?? 'start'));
                $cell = is_array($row) ? (string) ($row[$index] ?? '') : '';
                $html[] = '<td class="' . $align . '">' . $cell . '</td>';
            }
            $html[] = '</tr>';
        }
        $html[] = '</tbody>';
        $html[] = '</table>';
        $html[] = '</div>';
        return implode('', $html);
    }

    public function describe(): array
    {
        return [
            'slug' => 'table',
            'label' => 'Table',
            'description' => 'Reusable table from Content Banks.',
            'icon' => 'table',
            'scopes' => [MyronApiScopes::CONTENT_READ],
            'bankSurface' => 'editor',
            'adminUrl' => myronBuildAdminUrl('content.contentBanks', ['bank' => 'tables']),
        ];
    }

    private function alignmentClass(string $alignment): string
    {
        return match ($alignment) {
            'center' => 'myron-mic-table__cell--center',
            'end' => 'myron-mic-table__cell--end',
            default => 'myron-mic-table__cell--start',
        };
    }
}

