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

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

class ConditionBadge extends Base
{
    /**
     * Render a condition badge, similar to WaitBadge but with a distinct visual to indicate stop conditions.
     * $cond keys:
     * - label (string) e.g., "Email opened but not ordered"
     * - icon (string) raw HTML for display
     * - index (int) optional key for editing
     * - disabled (bool)
     * - href (string) optional link
     * - attrs (array) optional attributes
     * - dropdown (array) optional dropdown config (same shape as WaitBadge)
     */
    public static function render(array $cond, array $opts = []): string
    {
        $size = $opts['size'] ?? 'md'; // xs|sm|md|lg
        $orientation = $opts['orientation'] ?? 'horizontal';
        $editable = (bool)($opts['editable'] ?? false);
        // Optional special mode: treat upper as the event (success) and lower/missing as the condition (fail)
        // When enabled, render upper label as green badge with check icon and lower label as red badge with x icon
        $upperEventLowerCondition = (bool)($opts['upper_event_lower_condition'] ?? false);
        $index = isset($cond['index']) ? (int)$cond['index'] : -1;

        // Support upper/lower labels similar to DateRangeBadge while keeping BC:
        // - If label_upper/label_lower given, use them.
        // - Else fallback to single 'label' shown as lower label (as before).
        $label = (string)($cond['label'] ?? '');
        $labelUpper = (string)($cond['label_upper'] ?? '');
        $labelLower = (string)($cond['label_lower'] ?? '');
        if ($labelUpper === '' && $labelLower === '') {
            $labelLower = $label; // backward compatibility
        }
        $labelUpperEsc = self::h($labelUpper);
        $labelLowerEsc = self::h($labelLower);
        $labelTitle = trim(($labelUpper !== '' ? $labelUpper : '') . (($labelUpper !== '' && $labelLower !== '') ? ' — ' : '') . ($labelLower !== '' ? $labelLower : ''));
        if ($labelTitle === '') { $labelTitle = $label; }
        $labelTitleEsc = self::h($labelTitle);
        $icon = (string)($cond['icon'] ??Base::SVG_PLAY);
        $isDisabled = (bool)($cond['disabled'] ?? false);

        $href = isset($cond['href']) ? (string)$cond['href'] : '';
        $extraAttrs = is_array($cond['attrs'] ?? null) ? $cond['attrs'] : [];
        $hasDropdown = !empty($cond['dropdown']) && is_array($cond['dropdown']);

        // Size presets mirror WaitBadge but align label behavior with DateRangeBadge (no mt-1, absolute labels)
        $sizes = [
            'xs' => ['iconWrap' => 'size-5 p-0.5', 'iconText' => 'text-[10px]', 'labelText' => 'hidden', 'pad' => 'px-0', 'gap' => 'mx-0'],
            'sm' => ['iconWrap' => 'size-7 p-1', 'iconText' => 'text-xs', 'labelText' => 'text-[10px] whitespace-nowrap', 'pad' => 'px-1', 'gap' => '-mx-0'],
            'md' => ['iconWrap' => 'size-8 p-2', 'iconText' => 'text-sm', 'labelText' => 'text-xs whitespace-nowrap', 'pad' => 'px-2', 'gap' => '-mx-1'],
            'lg' => ['iconWrap' => 'size-9 p-2', 'iconText' => 'text-base', 'labelText' => 'text-xs whitespace-nowrap', 'pad' => 'px-3', 'gap' => 'mx-1'],
        ];
        $sz = $sizes[$size] ?? $sizes['md'];

        $wrapBase = $orientation == 'vertical' ? 'flex flex-row items-center justify-center space-x-1' : 'flex flex-col items-center ' . $sz['gap'] . ' text-secondary shrink-0';

        // Use a danger-themed wrapper to differentiate
        $iconWrapCls = 'flex items-center justify-center ' . $sz['iconWrap'] . ' p-2 rounded-full bg-muted ring ring-flow text-secondary  font-bold transition-colors duration-100 group-hover:bg-red-100 group-hover:shadow';
        $wrapClsBase = trim($wrapBase . ' ' . $sz['pad'] . ' ' . ($opts['class'] ?? ''));
        if ($isDisabled) {
            $wrapClsBase .= ' ' . self::DISABLED_CLASSES;
        }
        $hasAttrs = !empty($cond['attrs']) && is_array($cond['attrs']);
        $hasHref = isset($cond['href']) && (string)$cond['href'] !== '';
        $willHaveDropdown = !empty($cond['dropdown']) && is_array($cond['dropdown']);
        $isInteractive = !$isDisabled && ($hasHref || $hasAttrs || $willHaveDropdown);
        if ($isInteractive) {
            $wrapClsBase .= ' cursor-pointer group';
        }
        $outerClass = trim('relative condition-badge ' . $wrapClsBase);

        $iconWrapEsc = self::h($iconWrapCls);
        // Position labels above and below the icon, like DateRangeBadge
        $upperPosCls = 'absolute -top-3';
        $lowerPosCls = 'absolute -bottom-3';

        if ($upperEventLowerCondition) {
            // Special badges: upper = EVENT palette colored + check, lower = danger colored + x
            // Determine event token from upper label text (supports mapping like date_sent -> sent)
            $upperRaw = trim((string)($cond['label_upper'] ?? ''));
            $ev = strtolower($upperRaw);
            $ev = $ev === 'date_sent' ? 'sent' : $ev; // normalize
            // Build palette-based classes for the upper badge using event-* tokens
            $palKey = $ev !== '' ? ('event-' . $ev) : '';
            $palMap = Palette::map();
            $upperBgText = $palKey !== '' ? Palette::classes($palKey, 'gray') : Palette::classes('gray');
            $upperRing = ($palMap[$palKey]['ring'] ?? ($palMap['gray']['ring'] ?? 'ring-gray-500'));

            $upperBadgeCls = 'rounded-full dark:bg-gray-900 px-1 py-0 text-[10px] ' . $sz['labelText'] . ' ring-0 ' . $upperRing . ' ' . $upperBgText . ' flex items-center';
            $lowerBadgeCls = 'rounded-full dark:bg-gray-900 px-1 py-0 text-[10px] ' . $sz['labelText'] . ' ring-0 ring-red-500 bg-red-50 text-red-600 flex items-center';

            $upperLabelInner = '';
            if ($labelUpperEsc !== '') {
                $upperLabelInner =
//                    Base::SVG_MICRO_CHECK .
                    '<span>' . $labelUpperEsc . '</span>';
            }
            // Only render upper badge if we actually have an upper label (to avoid noise)
            $upperLabelHtml = $upperLabelInner !== ''
                ? '<div class="' . self::h(trim($upperPosCls . ' ' . $upperBadgeCls)) . '">' . $upperLabelInner . '</div>'
                : '';

            // Always render a lower badge to indicate the negative/condition state; if label missing, show icon only
            $lowerLabelInner = ($labelLowerEsc !== '' ? (Base::SVG_MICRO_X_MARK . '<span>' . $labelLowerEsc . '</span>') : '');
            $lowerLabelHtml = '<div class="' . self::h(trim($lowerPosCls . ' ' . $lowerBadgeCls)) . '">' . $lowerLabelInner . '</div>';
        } else {
            $labelBaseCls = 'rounded bg-surface px-1 ' . $sz['labelText'] . ' transition-colors duration-100 group-hover:bg-elevated group-hover:shadow group-hover:ring ring-brand';
            // Keep absolute positioning also for vertical for consistency (outer wrapper is relative)
            $upperLabelHtml = $labelUpperEsc !== '' ? '<div class="' . self::h(trim($upperPosCls . ' ' . $labelBaseCls)) . '">' . $labelUpperEsc . '</div>' : '';
            $lowerLabelHtml = $labelLowerEsc !== '' ? '<div class="' . self::h(trim($lowerPosCls . ' ' . $labelBaseCls)) . '">' . $labelLowerEsc . '</div>' : '';
        }

        $badgeInner = <<<HTML
  $upperLabelHtml
  <div class="$iconWrapEsc" title="$labelTitleEsc">$icon</div>
  $lowerLabelHtml
HTML;

        if ($hasDropdown) {
            $dd = $cond['dropdown'];
            $tr = is_array($dd['trigger'] ?? null) ? $dd['trigger'] : [];
            $items = is_array($dd['items'] ?? null) ? $dd['items'] : [];

            $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',
            ]);
        }

        $outerTag = ($href !== '') ? 'a' : ((!empty($extraAttrs)) ? '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; } }
        foreach ($extraAttrs as $k => $v) { $outerAttrs[$k] = $v; }
        $outerAttrStr = self::attrs($outerAttrs);

        $html = <<<HTML
<{$outerTag}{$outerAttrStr}>
{$badgeInner}
</{$outerTag}>
HTML;
        return $html;
    }
}
