<?php
// components/CampaignFlow/FlowBadge.php
namespace Components\CampaignFlow;

use Components\Base;
use Components\Support\Palette;

abstract class FlowBadge extends Base
{
    /**
     * Shared size presets for all flow badges.
     * xs|sm|md|lg
     */
    public static function getSizes(): array
    {
        return [
            'xs' => ['iconWrap' => 'size-5 p-0.5', 'iconText' => 'text-[10px]', 'labelText' => 'hidden', 'pad' => 'px-0', 'gap' => 'mx-0', 'pill' => 'h-5 px-2 text-[10px]', 'iconSvg' => '[&_svg]:size-4'],
            'sm' => ['iconWrap' => 'size-7 p-1',   'iconText' => 'text-xs',    'labelText' => 'text-[10px] whitespace-nowrap', 'pad' => 'px-1', 'gap' => '-mx-0', 'pill' => 'h-5 px-2.5 text-xs', 'iconSvg' => '[&_svg]:size-4'],
            'md' => ['iconWrap' => 'size-8 p-2',   'iconText' => 'text-sm',    'labelText' => 'text-xs whitespace-nowrap',     'pad' => 'px-2', 'gap' => '-mx-1', 'pill' => 'h-7 px-3 text-sm', 'iconSvg' => '[&_svg]:size-5'],
            'lg' => ['iconWrap' => 'size-9 p-2',   'iconText' => 'text-base',  'labelText' => 'text-xs whitespace-nowrap',     'pad' => 'px-3', 'gap' => 'mx-1',  'pill' => 'h-8 px-3.5 text-base', 'iconSvg' => '[&_svg]:size-5'],
        ];
    }

    /**
     * Determine if the badge is interactive (clickable or has a dropdown).
     */
    public static function isInteractive(array $cfg): bool
    {
        $isDisabled = (bool)($cfg['disabled'] ?? false);
        $hasAttrs = !empty($cfg['attrs']) && is_array($cfg['attrs']);
        $hasHref = isset($cfg['href']) && (string)$cfg['href'] !== '';
        $willHaveDropdown = !empty($cfg['dropdown']) && is_array($cfg['dropdown']);
        return !$isDisabled && ($hasHref || $hasAttrs || $willHaveDropdown);
    }

    /**
     * Common rendering logic for the badge wrapper, interactivity, and dropdown integration.
     */
    protected static function renderFlowBadge(array $cfg, array $opts = []): string
    {
        $size = $opts['size'] ?? 'md';
        $orientation = $opts['orientation'] ?? 'horizontal';
        $isDisabled = (bool)($cfg['disabled'] ?? false);
        $variant = (string)($cfg['variant'] ?? ($opts['variant'] ?? 'pill'));
        
        $sz = self::getSizes()[$size] ?? self::getSizes()['md'];

        // Determine the common CSS classes for the outer wrapper
        $wrapBase = $orientation == 'vertical' ? 'flex flex-row items-center justify-center space-x-1' : 'flex flex-col items-center ' . $sz['gap'] . ' text-secondary shrink-0';
        $wrapClsBase = trim($wrapBase . ' ' . $sz['pad'] . ' ' . ($opts['class'] ?? ''));
        
        if ($isDisabled) {
            $wrapClsBase .= ' ' . self::DISABLED_CLASSES;
        }

        // Interactivity handling
        $isInteractive = self::isInteractive($cfg);
        
        if ($isInteractive) {
            $wrapClsBase .= ' cursor-pointer group';
        }

        $badgeTypeClass = $opts['badge_type_class'] ?? '';
        $outerClass = trim('relative ' . $badgeTypeClass . ' ' . $wrapClsBase);
        if ($variant === 'pill') {
            $outerClass .= ' wait-variant-pill';
        }

        $badgeInner = $opts['badge_inner_html'] ?? '';

        // Dropdown integration
        if (!empty($cfg['dropdown']) && is_array($cfg['dropdown'])) {
            $dd = $cfg['dropdown'];
            $items = is_array($dd['items'] ?? null) ? $dd['items'] : [];
            $tr = is_array($dd['trigger'] ?? null) ? $dd['trigger'] : [];

            $triggerAttrs = array_merge([
                'class' => $outerClass,
                'type' => 'button'
            ], is_array($tr['attrs'] ?? null) ? $tr['attrs'] : []);
            
            if ($isDisabled) {
                $triggerAttrs['aria-disabled'] = 'true';
                $triggerAttrs['disabled'] = true;
            }

            return \Components\Dropdown::render([
                'trigger_tag' => 'button',
                'trigger_attrs' => $triggerAttrs,
                'trigger_html' => $badgeInner,
                'items' => $items,
                'anchor' => 'bottom start',
                'popover' => 'manual',
                'wrapper_class' => 'inline-flex relative',
            ]);
        }

        // Standard tag (a, button, or div)
        $href = (string)($cfg['href'] ?? '');
        $outerTag = ($href !== '') ? 'a' : ((!empty($cfg['attrs'])) ? 'button' : 'div');
        $outerAttrs = ['class' => $outerClass];
        
        if ($href !== '' && $outerTag === 'a') {
            $outerAttrs['href'] = $href;
        }
        if ($outerTag === 'button') {
            $outerAttrs['type'] = 'button';
        }
        if ($isDisabled) {
            $outerAttrs['aria-disabled'] = 'true';
            if ($outerTag === 'button') {
                $outerAttrs['disabled'] = true;
            }
        }
        
        $extraAttrs = is_array($cfg['attrs'] ?? null) ? $cfg['attrs'] : [];
        foreach ($extraAttrs as $k => $v) {
            $outerAttrs[$k] = $v;
        }
        $outerAttrStr = self::attrs($outerAttrs);

        return "<{$outerTag}{$outerAttrStr}>{$badgeInner}</{$outerTag}>";
    }

    /**
     * Resolve the icon wrapper CSS classes, unifying pill vs. default variants.
     */
    protected static function getIconWrapClasses(array $cfg, array $opts, array $sz): string
    {
        $isInteractive = self::isInteractive($cfg);
        $variant = (string)($cfg['variant'] ?? ($opts['variant'] ?? 'pill'));
        $token = (string)($cfg['color'] ?? ($opts['color'] ?? 'orange'));

        if ($variant === 'pill') {
            $pal = \Components\Support\Palette::map();
            $bg = $pal[$token]['dot'] ?? 'bg-orange-500';

            if (!$isInteractive) {
                // Strip hover effects from background if not interactive
                $bg = preg_replace('/\bhover:[^\s]+\b/', '', $bg);
            }

            $ring = $pal[$token]['ring'] ?? 'ring-orange-500';
            $text = $pal[$token]['pill-text'] ?? 'text-white';
            return ' inline-flex items-center justify-center rounded-full ' . $sz['pill'] . ' ' . $text . ' ' . trim($bg) . ' ring ' . $ring . ' shadow-sm ' . $sz['iconSvg'];
        }

        $paletteCls = $opts['palette_classes'] ?? 'bg-muted ring-flow text-secondary';
        $paletteRing = $opts['palette_ring'] ?? 'ring';
        
        return 'flex items-center justify-center ' . $sz['iconWrap'] . ' rounded-full ' . $paletteCls . ' ' . $paletteRing . ' font-bold transition-colors duration-100 group-hover:bg-elevated group-hover:shadow group-hover:ring ring-brand ' . $sz['iconSvg'];
    }
}
