<?php
namespace Grav\Plugin\Shortcodes;

use Thunder\Shortcode\Shortcode\ShortcodeInterface;

class ChapterBreakShortcode extends Shortcode
{
    public function init(): void
    {
        $this->shortcode->getHandlers()->add('chapter-break', function (ShortcodeInterface $sc) {
            $plugin = $this->grav['plugins']->getPlugin('story-blocks');
            $page   = $plugin ? $plugin->getCurrentPage() : null;

            $imageName = htmlspecialchars($sc->getParameter('image', ''), ENT_QUOTES);
            $title     = htmlspecialchars($sc->getParameter('title', ''), ENT_QUOTES);
            $number    = htmlspecialchars($sc->getParameter('number', ''), ENT_QUOTES);
            $alt       = htmlspecialchars($sc->getParameter('alt', $title), ENT_QUOTES);
            $imageUrl  = ($page && $imageName) ? $page->url() . '/' . $imageName : $imageName;

            $numberHtml = $number
                ? '<span class="chapter-break__number" aria-hidden="true">' . $number . '</span>'
                : '';

            return <<<HTML
<div class="chapter-break" aria-label="Chapter: {$title}">
  <div class="chapter-break__bg">
    <img src="{$imageUrl}" alt="{$alt}" class="chapter-break__img" loading="lazy">
    <div class="chapter-break__tint" aria-hidden="true"></div>
  </div>
  <div class="chapter-break__panel">
    {$numberHtml}
    <h2 class="chapter-break__title">{$title}</h2>
    <div class="chapter-break__rule" aria-hidden="true"></div>
  </div>
</div>
HTML;
        });
    }
}
