<?php

declare(strict_types=1);

final class MyronAssetReplacementView
{
    /**
     * @param array{
     *   csrfToken:string,
     *   fileId:string,
     *   accept:string,
     *   label?:string,
     *   hint?:string,
     *   buttonLabel?:string,
     *   hidden?:array<string, string>
     * } $options
     */
    public static function render(array $options): string
    {
        $label = trim((string) ($options['label'] ?? 'Replace File'));
        $hint = trim((string) ($options['hint'] ?? 'Keeps this file ID in place and updates every page, template, logo, or component that already references it.'));
        $buttonLabel = trim((string) ($options['buttonLabel'] ?? $label));
        $hidden = is_array($options['hidden'] ?? null) ? (array) $options['hidden'] : [];

        $html = [];
        $html[] = '<form method="post" enctype="multipart/form-data" class="sg-form-grid" data-myron-asset-replacement-form>';
        $html[] = '  <input type="hidden" name="csrf_token" value="' . myronEscape((string) ($options['csrfToken'] ?? '')) . '">';
        $html[] = '  <input type="hidden" name="action" value="replace-file">';
        $html[] = '  <input type="hidden" name="file_id" value="' . myronEscape((string) ($options['fileId'] ?? '')) . '">';

        foreach ($hidden as $name => $value) {
            $safeName = preg_replace('/[^A-Za-z0-9_-]+/', '', (string) $name) ?? '';
            if ($safeName === '') {
                continue;
            }
            $html[] = '  <input type="hidden" name="' . myronEscape($safeName) . '" value="' . myronEscape((string) $value) . '">';
        }

        $html[] = '  <label class="sg-field sg-field--full">';
        $html[] = '    <span class="sg-field__label">' . myronEscape($label) . '</span>';
        $html[] = '    <input class="sg-field__control" type="file" name="replacement_file" required accept="' . myronEscape((string) ($options['accept'] ?? '')) . '">';
        if ($hint !== '') {
            $html[] = '    <span class="sg-field__hint">' . myronEscape($hint) . '</span>';
        }
        $html[] = '  </label>';
        $html[] = '  <div class="mc-side-sheet__actions">';
        $html[] = '    <button class="sg-button sg-button--secondary" type="submit">' . myronEscape($buttonLabel) . '</button>';
        $html[] = '  </div>';
        $html[] = '</form>';

        return implode(PHP_EOL, $html);
    }
}
