<?php

/**
 * @package         Tassos Code Snippets
 * @version         1.0.1-RC2 Free
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            https://www.tassos.gr
 * @copyright       Copyright © 2026 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace Tassos\CodeSnippets\Administrator\Field;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Form\FormField;
use Joomla\CMS\Language\Text;

/**
 * Shortcode Display field with copy to clipboard button.
 */
class ShortcodeDisplayField extends FormField
{
    /**
     * The form field type.
     *
     * @var    string
     */
    protected $type = 'ShortcodeDisplay';

    /**
     * Method to get the field input markup.
     *
     * @return  string  The field input markup.
     */
    protected function getInput()
    {
        // Register the JavaScript
        $this->registerScript();

        $rawValue = $this->value;

        // Determine whether this is a real shortcode or still a placeholder
        $isRealShortcode = str_starts_with((string) $rawValue, '{tcs snippet.');

        // Extract alias key from shortcode value (strip prefix/suffix)
        $aliasKey = '';

        if ($isRealShortcode && str_ends_with((string) $rawValue, '}'))
        {
            $aliasKey = substr($rawValue, strlen('{tcs snippet.'), -1);
        }

        // Translate placeholder language keys
        $displayValue = $rawValue;

        if (empty($displayValue) || preg_match('/^[A-Z_]+$/', $displayValue))
        {
            $displayValue = Text::_($displayValue ?: (string) $this->element['default']);
        }

        $displayValue = htmlspecialchars($displayValue, ENT_COMPAT, 'UTF-8');
        $aliasKey     = htmlspecialchars($aliasKey, ENT_COMPAT, 'UTF-8');
        $id           = $this->id;
        $modalId      = 'tcs-shortcode-modal-' . $id;

        $html = [];
        $html[] = '<div class="tcs-shortcode-wrapper">';

        // ── Layer A: Read-only display ──────────────────────────────────────
        // Copy button is positioned inside the input; edit button sits outside with a gap.
        $html[] = '  <div class="d-flex align-items-center tcs-shortcode-display">';
        $html[] = '    <div class="position-relative flex-grow-1">';
        $html[] = '      <input type="text" id="' . $id . '" value="' . $displayValue . '" class="form-control" readonly style="padding-left:2.3rem; cursor:pointer;">';
        $html[] = '      <button type="button" class="btn tcs-copy-shortcode position-absolute top-50 start-0 translate-middle-y ms-2 p-1" data-field-id="' . $id . '" title="' . Text::_('COM_TASSOSCODESNIPPETS_COPY_TO_CLIPBOARD') . '">';
        $html[] = '        <span class="icon-copy" aria-hidden="true"></span>';
        $html[] = '      </button>';
        $html[] = '    </div>';

        if ($isRealShortcode)
        {
            $html[] = '    <button type="button" class="btn btn-outline-secondary ms-2 tcs-change-shortcode-btn" data-bs-toggle="modal" data-bs-target="#' . $modalId . '" title="' . Text::_('COM_TASSOSCODESNIPPETS_CHANGE_SHORTCODE') . '">';
            $html[] = '      <span class="icon-edit" aria-hidden="true"></span>';
            $html[] = '    </button>';
        }

        $html[] = '  </div>';

        if ($isRealShortcode)
        {
            // ── Layer B: Inline edit (hidden by default) ────────────────────
            $html[] = '  <div class="tcs-shortcode-edit d-none">';
            $html[] = '    <div class="d-flex gap-2 align-items-center mb-2">';
            $html[] = '      <div class="input-group flex-grow-1">';
            $html[] = '        <span class="input-group-text" style="background-color:var(--bs-body-bg);color:var(--bs-body-color);border-color:var(--bs-border-color);">{tcs snippet.</span>';
            $html[] = '        <input type="text" class="form-control tcs-shortcode-key-input" value="' . $aliasKey . '">';
            $html[] = '        <span class="input-group-text" style="background-color:var(--bs-body-bg);color:var(--bs-body-color);border-color:var(--bs-border-color);">}</span>';
            $html[] = '      </div>';
            $html[] = '      <button type="button" class="btn btn-primary tcs-shortcode-save-btn">' . Text::_('COM_TASSOSCODESNIPPETS_SHORTCODE_CONFIRM_BTN') . '</button>';
            $html[] = '      <button type="button" class="btn btn-outline-secondary tcs-shortcode-cancel-btn">' . Text::_('JCANCEL') . '</button>';
            $html[] = '    </div>';
            $html[] = '    <small class="form-text text-danger d-block">';
            $html[] = '      <span class="icon-warning" aria-hidden="true"></span> ';
            $html[] = '      ' . Text::_('COM_TASSOSCODESNIPPETS_CHANGE_SHORTCODE_WARNING');
            $html[] = '    </small>';
            $html[] = '  </div>';

            // ── Layer C: Bootstrap confirmation modal ───────────────────────
            $html[] = '  <div class="modal fade" id="' . $modalId . '" tabindex="-1" aria-modal="true" role="dialog">';
            $html[] = '    <div class="modal-dialog">';
            $html[] = '      <div class="modal-content">';
            $html[] = '        <div class="modal-header">';
            $html[] = '          <h5 class="modal-title">' . Text::_('COM_TASSOSCODESNIPPETS_CHANGE_SHORTCODE') . '</h5>';
            $html[] = '          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="' . Text::_('JCLOSE') . '"></button>';
            $html[] = '        </div>';
            $html[] = '        <div class="modal-body p-4">';
            $html[] = '          <p>' . Text::_('COM_TASSOSCODESNIPPETS_CHANGE_SHORTCODE_MODAL_BODY') . '</p>';
            $html[] = '          <code>' . $displayValue . '</code>';
            $html[] = '        </div>';
            $html[] = '        <div class="modal-footer">';
            $html[] = '          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">' . Text::_('JCANCEL') . '</button>';
            $html[] = '          <button type="button" class="btn btn-primary tcs-modal-confirm-btn" data-bs-dismiss="modal" data-field-id="' . $id . '">';
            $html[] = '            ' . Text::_('COM_TASSOSCODESNIPPETS_CHANGE_SHORTCODE_CONFIRM');
            $html[] = '          </button>';
            $html[] = '        </div>';
            $html[] = '      </div>';
            $html[] = '    </div>';
            $html[] = '  </div>';
        }

        $html[] = '</div>';

        return implode("\n", $html);
    }

    /**
     * Register all shortcode-field scripts (copy, change, inline-edit).
     *
     * @return void
     */
    private function registerScript(): void
    {
        // Check if already registered to avoid duplicates
        static $registered = false;

        if ($registered)
        {
            return;
        }

        $wa = Factory::getApplication()->getDocument()->getWebAssetManager();

        // Ensure Bootstrap's modal JS is loaded (not loaded by default on edit views)
        $wa->useScript('bootstrap.modal');

        // Shared copy-to-clipboard + field-specific edit/modal handlers
        $wa->useScript('com_tassoscodesnippets.shortcode-copy');

        $registered = true;
    }
}
