<?php
// components/Popover.php
namespace Components;

/**
 * Reusable Popover component using Tailwind Plus Elements (<el-popover>).
 *
 * Options (all optional unless stated otherwise):
 * - id: string             // unique ID for the popover (required for trigger connection)
 * - trigger_html: string   // raw HTML for the trigger button
 * - trigger_attrs: array   // attributes for the trigger button
 * - trigger_tag: string    // tag for the trigger (default: button)
 * - content_html: string   // raw HTML for the popover content
 * - popover_attrs: array   // attributes for the <el-popover> element
 */
class Popover extends Base
{
    /** Render popover with provided options */
    public static function render(array $opts = []): string
    {
        $id = $opts['id'] ?? 'popover-' . bin2hex(random_bytes(4));
        $triggerHtml = (string)($opts['trigger_html'] ?? '');
        $triggerTag = (string)($opts['trigger_tag'] ?? 'button');
        $triggerAttrs = is_array($opts['trigger_attrs'] ?? null) ? $opts['trigger_attrs'] : [];
        $contentHtml = (string)($opts['content_html'] ?? '');
        $popoverAttrs = is_array($opts['popover_attrs'] ?? null) ? $opts['popover_attrs'] : [];

        // Connect trigger to popover
        $triggerAttrs['popovertarget'] = $id;
        if ($triggerTag === 'button' && !isset($triggerAttrs['type'])) {
            $triggerAttrs['type'] = 'button';
        }

        // Popover defaults
        $popoverAttrs['id'] = $id;
        if (!isset($popoverAttrs['popover'])) {
            $popoverAttrs['popover'] = 'manual';
        }
        
        $popoverClassDefault = 'rounded-xl border border-divider bg-white shadow-lg dark:bg-zinc-900 transition transition-discrete data-closed:scale-95 data-closed:transform data-closed:opacity-0 data-enter:duration-100 data-enter:ease-out data-leave:duration-75 data-leave:ease-in';
        $popoverClass = trim((string)($popoverAttrs['class'] ?? ''));
        if ($popoverClass !== '') {
            $popoverAttrs['class'] = $popoverClassDefault . ' ' . $popoverClass;
        } else {
            $popoverAttrs['class'] = $popoverClassDefault;
        }

        $triggerAttrStr = self::attrs($triggerAttrs);
        $popoverAttrStr = self::attrs($popoverAttrs);

        return <<<HTML
<{$triggerTag} {$triggerAttrStr}>
    {$triggerHtml}
</{$triggerTag}>
<el-popover {$popoverAttrStr}>
    {$contentHtml}
</el-popover>
HTML;
    }
}
