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

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

class ConditionBadge extends FlowBadge
{
    /**
     * 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)
     * - variant (string) optional layout variant, supports 'pill'
     * - color (string) optional palette token for 'pill' (default: 'orange')
     */
    public static function render(array $cond, array $opts = []): string
    {
        $size = $opts['size'] ?? 'md'; // xs|sm|md|lg
        $orientation = $opts['orientation'] ?? 'horizontal';
        $sz = self::getSizes()[$size] ?? self::getSizes()['md'];

        // 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);

        // 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);

        // Resolve color/palette similar to DateRangeBadge/WaitBadge so visuals stay consistent
        // Accept a token via $cond['color'] or $opts['color']; default to 'muted' (non-distracting)
        $token = (string)($cond['color'] ?? ($opts['color'] ?? 'brand'));
        $paletteCls = Palette::classes($token, 'gray');
        $paletteRing = Palette::map()[$token]['ring'] ?? 'ring-gray-500';

//        $paletteCls = 'text-orange-600 bg-white';
//        $paletteRing = 'ring-orange-500';


        $iconWrapCls = self::getIconWrapClasses($cond, array_merge($opts, [
            'color' => $token,
            'palette_classes' => $paletteCls,
            'palette_ring' => $paletteRing,
        ]), $sz);
        $iconWrapEsc = self::h($iconWrapCls);

        // Position labels above and below the icon, like DateRangeBadge
        $upperPosCls = 'absolute -top-4';
        $lowerPosCls = 'absolute -bottom-4';

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

            // Always render a lower badge to indicate the negative/condition state; if label missing, show icon only
            $lowerLabelInner = '';
            if ($labelLowerEsc !== '') {
                $svg = Base::SVG_MICRO_X_MARK;
                $lowerLabelInner = <<<HTML
{$svg}<span>{$labelLowerEsc}</span>
HTML;
            }
            $clsEsc = self::h(trim($lowerPosCls . ' ' . $lowerBadgeCls));
            $lowerLabelHtml = <<<HTML
<div class="{$clsEsc}">{$lowerLabelInner}</div>
HTML;
        } 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 = '';
            if ($labelUpperEsc !== '') {
                $clsEsc = self::h(trim($upperPosCls . ' ' . $labelBaseCls));
                $upperLabelHtml = <<<HTML
<div class="{$clsEsc}">{$labelUpperEsc}</div>
HTML;
            }
            $lowerLabelHtml = '';
            if ($labelLowerEsc !== '') {
                $clsEsc = self::h(trim($lowerPosCls . ' ' . $labelBaseCls));
                $lowerLabelHtml = <<<HTML
<div class="{$clsEsc}">{$labelLowerEsc}</div>
HTML;
            }
        }

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

        return self::renderFlowBadge($cond, array_merge($opts, [
            'badge_type_class' => 'condition-badge',
            'badge_inner_html' => $badgeInner,
        ]));
    }
}
