<?php
// components/Ui/PageHeader.php
namespace Components\Ui;

use Components\Base;

class PageHeader
{
    /**
     * Render a simple page header/title block.
     *
     * Options (all optional):
     * - tag:        Heading tag to use (default: 'h3')
     * - classes:    CSS classes for the heading element (default: 'text-2xl opacity-80 font-semibold')
     * - subtitle:   Secondary text in row with the title (string)
     * - subtitleClasses: CSS classes for subtitle (default: 'text-secondary opacity-80')
     * - subtitleInRow:  Whether to show subtitle in the same row (default: false)
     * - truncate:       Whether to truncate the title with ellipsis (default: true)
     * - wrapperClasses:  CSS classes for outer wrapper <div> (default: 'mb-2')
     * - attrs:      Extra HTML attributes for the outer wrapper (array key=>value)
     * - center:     Optional HTML string to render in the center section of the header row
     * - centerWrapperClasses: CSS classes for the center-side wrapper (default: '')
     * - right:      Optional HTML string to render on the right side of the title row (e.g., action buttons)
     * - rightWrapperClasses: CSS classes for the right-side wrapper (default: '')
     * - headerRowClasses: CSS classes for the header row wrapper when a right or center slot is present
     *                     (default: 'flex items-center justify-between gap-4')
     */
    public static function render(string $title, array $opts = []): string
    {
        $tag            = $opts['tag']             ?? 'h1';
        $classes        = $opts['classes']         ?? 'text-2xl opacity-80 font-semibold tracking-tight';
        $subtitle       = isset($opts['subtitle']) ? (string)$opts['subtitle'] : '';
        $subtitleClass  = $opts['subtitleClasses'] ?? 'text-secondary opacity-60 tracking-tight text-sm';
        $subtitleInRow  = $opts['subtitleInRow']   ?? false;
        $truncate       = $opts['truncate']        ?? true;
        $wrapperClasses = $opts['wrapperClasses']  ?? 'mb-2';
        $attrs          = isset($opts['attrs']) && is_array($opts['attrs']) ? $opts['attrs'] : [];
        $centerHtml     = isset($opts['center']) ? (string)$opts['center'] : '';
        $centerWrapper  = $opts['centerWrapperClasses'] ?? '';
        $rightHtml      = isset($opts['right']) ? (string)$opts['right'] : '';
        // Default to no vertical padding so header height stays consistent
        $rightWrapper   = $opts['rightWrapperClasses'] ?? '';
        $rowClasses     = $opts['headerRowClasses'] ?? 'flex items-center justify-between gap-4 min-h-9';

        // Compose wrapper attributes
        $wrapperAttr = '';
        $wrapperCls  = trim((string)$wrapperClasses);
        if ($wrapperCls !== '') {
            $attrs['class'] = isset($attrs['class']) && $attrs['class'] !== ''
                ? trim((string)$attrs['class'] . ' ' . $wrapperCls)
                : $wrapperCls;
        }
        if (!empty($attrs)) {
            $wrapperAttr = Base::attrs($attrs);
        }

        $titleEsc    = Base::h($title, ['allowed_tags' => '<br><br/><b><strong><i><em><u><a><code><span><div>']);
        $titlePlain  = Base::h(strip_tags($title), false);

        if ($truncate) {
            $classes .= ' truncate min-w-0';
        } else {
            $classes .= ' break-words';
        }

        $classesAttr = Base::h((string)$classes, false);
        $tagName     = preg_replace('~[^a-z0-9]~i', '', (string)$tag) ?: 'h1';

        $subtitleHtml = '';
        if ($subtitle !== '') {
            $subtitleEsc   = Base::h($subtitle);
            $subtitleClass = Base::h((string)$subtitleClass, false);
            if ($subtitleInRow) {
                // In-row subtitle: no extra margin-top, ensure it doesn't shrink
                $subtitleHtml = "<span class=\"{$subtitleClass} flex-none\">{$subtitleEsc}</span>";
            } else {
                // Traditional subtitle below: add some margin-top
                $subtitleHtml = "\n  <p class=\"{$subtitleClass} mt-1\">{$subtitleEsc}</p>";
            }
        }

        // Prepare the left side (title + optional in-row subtitle)
        if ($subtitleInRow && $subtitle !== '') {
            $leftSideHtml = <<<HTML
<div class="flex items-baseline gap-2 min-w-0">
  <{$tagName} class="{$classesAttr}" title="{$titlePlain}">{$titleEsc}</{$tagName}>
  {$subtitleHtml}
</div>
HTML;
        } else {
            $leftSideHtml = "<{$tagName} class=\"{$classesAttr}\" title=\"{$titlePlain}\">{$titleEsc}</{$tagName}>";
        }

        $belowSubtitle = (!$subtitleInRow && $subtitle !== '') ? $subtitleHtml : '';

        // Render header row (always uses flex for consistent alignment and height)
        $rowClsEsc    = Base::h((string)$rowClasses, false);
        $centerClsEsc = Base::h((string)$centerWrapper, false);
        $rightClsEsc  = Base::h((string)$rightWrapper, false);

        if ($centerHtml !== '') {
            // If center is present, use flex-1 on left/right to ensure true centering
            $leftOutput   = "<div class=\"flex-1 min-w-0\">{$leftSideHtml}</div>";
            $centerOutput = "<div class=\"flex-none {$centerClsEsc}\">{$centerHtml}</div>";
            $rightOutput  = "<div class=\"flex-1 flex justify-end min-w-0 {$rightClsEsc}\">{$rightHtml}</div>";
        } else {
            $leftOutput   = $leftSideHtml;
            $centerOutput = '';
            $rightOutput  = $rightHtml !== '' ? "<div class=\"{$rightClsEsc}\">{$rightHtml}</div>" : '';
        }

        return <<<HTML
<div{$wrapperAttr}>
  <div class="{$rowClsEsc}">
    {$leftOutput}
    {$centerOutput}
    {$rightOutput}
  </div>
  {$belowSubtitle}
</div>
HTML;
    }
}
