<?php

namespace PpPhp\Plugins;

use PpPhp\Core\EditPlugin;

/**
 * Markdown editor edit-control (platform feature A5).
 *
 * Stores the RAW markdown in the field (e.g. body_md). It is progressive-
 * enhancement: the control is a working <textarea> on its own, and editor.js
 * adds a formatting toolbar + live preview when it loads. The stored markdown is
 * rendered to sanitised HTML for display by the matching View plugin "Markdown"
 * (\PpPhp\Core\Html\Markdown::toSafeHtml) — never trust markdown as HTML without
 * that server-side render.
 */
class MarkdownEditor implements EditPlugin
{
    public static function id(): string { return 'MarkdownEditor'; }

    public static function label(): string { return 'Markdown Editor'; }
    public static function version(): string { return '1.0.0'; }
    public static function description(): string { return 'Markdown editor with live preview; stores raw markdown (pair with the Markdown view).'; }

    public static function render(string $fieldName, mixed $value, array $settings): string
    {
        $rows = max(3, (int) ($settings['rows'] ?? 8));
        $ph   = htmlspecialchars((string) ($settings['placeholder'] ?? 'Write in Markdown — **bold**, `code`, [links](https://…), lists…'), ENT_QUOTES);
        $val  = htmlspecialchars((string) ($value ?? ''), ENT_QUOTES);
        $id   = 'md_' . preg_replace('/[^A-Za-z0-9_]/', '_', $fieldName) . '_' . substr(md5($fieldName), 0, 6);

        $flags = '';
        if (($settings['toolbar'] ?? true) === false) $flags .= ' data-no-toolbar';
        if (($settings['preview'] ?? true) === false) $flags .= ' data-no-preview';

        return '<div class="pp-md" data-pp-md' . $flags . '>'
            . '<textarea id="' . $id . '" name="' . $fieldName . '" rows="' . $rows . '"'
            . ' class="form-control pp-md-src" placeholder="' . $ph . '" spellcheck="true">' . $val . '</textarea>'
            . '</div>';
    }

    public static function settingsSchema(): array
    {
        return [
            ['key' => 'rows', 'type' => 'number', 'label' => 'Rows', 'default' => 8],
            ['key' => 'placeholder', 'type' => 'text', 'label' => 'Placeholder', 'default' => ''],
            ['key' => 'toolbar', 'type' => 'boolean', 'label' => 'Show formatting toolbar', 'default' => true],
            ['key' => 'preview', 'type' => 'boolean', 'label' => 'Show live preview', 'default' => true],
        ];
    }

    public static function assets(): array
    {
        return [
            'js'  => ['plugins/Edit/MarkdownEditor/editor.js'],
            'css' => ['plugins/Edit/MarkdownEditor/editor.css'],
        ];
    }
}
