<svelte:options customElement={{ props: {} }} />

<script lang="ts">
  import NodeWrapper from '../core/NodeWrapper.svelte';
  import {
    type Edge,
    Handle,
    type NodeProps,
    Position,
    useSvelteFlow,
    useUpdateNodeInternals
  } from '@xyflow/svelte';
  import {Button, Input, MixedInput, Select} from '../base';
  import ParamTokenEditor from '../core/ParamTokenEditor.svelte';
  import {getCurrentNodeId} from '#components/utils/NodeUtils';
  import {genShortId} from '../utils/IdGen';
  import {deepEqual} from '../utils/deepEqual';
  import {useRefOptions} from '#components/utils/useRefOptions.svelte';
  import {store} from '#store/stores.svelte';
  import type {Parameter, SelectItem} from '#types';

  const SHOW_EXPRESSION_ENTRY = false;

  type ConditionOperator =
    | 'eq'
    | 'ne'
    | 'gt'
    | 'gte'
    | 'lt'
    | 'lte'
    | 'isEmpty'
    | 'isNotEmpty'
    | 'contains'
    | 'notContains';

  type RuleJoiner = 'AND' | 'OR';
  type BranchMode = 'visual' | 'expression';

  type ConditionRule = {
    id: string;
    joiner: RuleJoiner;
    leftRef: string;
    operator: ConditionOperator;
    rightType: 'fixed' | 'ref';
    rightValue: string;
    rightRef: string;
  };

  type ConditionBranch = {
    id: string;
    label: string;
    mode: BranchMode;
    expression: string;
    rules: ConditionRule[];
  };

  type ConditionNodeData = {
    branchMode: 'first_match';
    branches: ConditionBranch[];
    defaultBranchId: string;
    defaultBranchLabel: string;
  };

  const OPERATOR_ITEMS = [
    { value: 'eq', label: '等于 (==)' },
    { value: 'ne', label: '不等于 (!=)' },
    { value: 'gt', label: '大于 (>)' },
    { value: 'gte', label: '大于等于 (>=)' },
    { value: 'lt', label: '小于 (<)' },
    { value: 'lte', label: '小于等于 (<=)' },
    { value: 'isEmpty', label: '为空' },
    { value: 'isNotEmpty', label: '不为空' },
    { value: 'contains', label: '包含' },
    { value: 'notContains', label: '不包含' }
  ] as const;

  const {
    data,
    ...rest
  }: {
    data: NodeProps['data'] & Partial<ConditionNodeData>;
    [key: string]: any;
  } = $props();

  const currentNodeId = getCurrentNodeId();
  const { updateNodeData } = useSvelteFlow();
  const updateNodeInternals = useUpdateNodeInternals();
  const refOptions = useRefOptions(false);

  let activeBranchId = $state('');
  let editingBranchId: string | null = $state(null);

  const buildBranchCondition = (branchId: string) => `matchedBranchId === '${branchId}'`;

  const createRule = (joiner: RuleJoiner = 'AND'): ConditionRule => ({
    id: `rule_${genShortId(10)}`,
    joiner,
    leftRef: '',
    operator: 'eq',
    rightType: 'fixed',
    rightValue: '',
    rightRef: ''
  });

  const createBranch = (label = '条件分支'): ConditionBranch => ({
    id: `branch_${genShortId(10)}`,
    label,
    mode: 'visual',
    expression: '',
    rules: [createRule('AND')]
  });

  const createElseBranch = (label = 'Else'): ConditionBranch => ({
    id: `branch_else_${genShortId(8)}`,
    label,
    mode: 'visual',
    expression: '',
    rules: []
  });

  const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value || {}));

  const normalizeBranch = (branch: any, fallbackLabel: string): ConditionBranch => {
    const mode: BranchMode =
      SHOW_EXPRESSION_ENTRY && branch?.mode === 'expression' ? 'expression' : 'visual';
    const rawRules = Array.isArray(branch?.rules) ? branch.rules : [];
    const rules: ConditionRule[] = rawRules
      .map((rule: any) => ({
        id: rule?.id || `rule_${genShortId(10)}`,
        joiner: rule?.joiner === 'OR' ? 'OR' : 'AND',
        leftRef: rule?.leftRef || '',
        operator: (rule?.operator || 'eq') as ConditionOperator,
        rightType: rule?.rightType === 'ref' ? 'ref' : 'fixed',
        rightValue: rule?.rightValue || '',
        rightRef: rule?.rightRef || ''
      }))
      .filter((rule: ConditionRule) => !!rule.id);

    return {
      id: branch?.id || `branch_${genShortId(10)}`,
      label: branch?.label || fallbackLabel,
      mode,
      expression: branch?.expression || '',
      rules
    };
  };

  const normalizeConditionData = (rawData: any): ConditionNodeData => {
    const rawBranches = Array.isArray(rawData?.branches) ? rawData.branches : [];
    const normalizedBranches: ConditionBranch[] = rawBranches.map((branch: any, index: number) => {
      const b = normalizeBranch(branch, `条件分支${index + 1}`);
      if (!b.rules || b.rules.length === 0) {
        b.rules = [createRule('AND')];
      }
      return b;
    });

    let defaultBranchId = rawData?.defaultBranchId as string;
    let defaultBranch = normalizedBranches.find((branch) => branch.id === defaultBranchId);
    if (!defaultBranch) {
      defaultBranch = normalizedBranches.find((branch) => ['Else', 'else', '默认分支'].includes(branch.label));
    }
    if (!defaultBranch && normalizedBranches.length > 0) {
      defaultBranch = normalizedBranches[normalizedBranches.length - 1];
    }

    const normalBranches = normalizedBranches.filter((branch) => branch.id !== defaultBranch?.id);

    if (!defaultBranch) {
      defaultBranch = createElseBranch('Else');
    }

    if (normalBranches.length === 0) {
      normalBranches.push(createBranch('条件分支1'));
    }

    const normalizedNormals: ConditionBranch[] = normalBranches.map((branch) => {
      const next: ConditionBranch = {
        ...branch,
        mode:
          SHOW_EXPRESSION_ENTRY && branch.mode === 'expression' ? 'expression' : 'visual'
      };
      if (next.mode === 'visual' && (!next.rules || next.rules.length === 0)) {
        next.rules = [createRule('AND')];
      }
      return next;
    });

    const normalizedElse: ConditionBranch = {
      ...defaultBranch,
      label: 'Else',
      mode: 'visual',
      expression: '',
      rules: []
    };
    defaultBranch = normalizedElse;

    defaultBranchId = defaultBranch.id;

    return {
      branchMode: 'first_match',
      branches: [...normalizedNormals, defaultBranch],
      defaultBranchId,
      defaultBranchLabel: 'Else'
    };
  };

  const isOperatorNeedRight = (operator: ConditionOperator) => {
    return !['isEmpty', 'isNotEmpty'].includes(operator);
  };

  const branchKeyword = (branch: ConditionBranch, index: number, defaultId: string) => {
    if (branch.id === defaultId) {
      return 'Else';
    }
    return index === 0 ? 'If' : 'Else If';
  };

  const branchWarningLabel = (branch: ConditionBranch, index: number, defaultId: string) => {
    if (branch.id === defaultId) {
      return 'Else';
    }
    const label = String(branch.label || '').trim();
    return label || `条件分支${index + 1}`;
  };

  const isExpanded = () => Boolean(data?.expand);

  const collapsedHandleTop = (index: number, count: number) => {
    if (count <= 1) {
      return '54px';
    }
    const start = 38;
    const end = 74;
    const step = (end - start) / (count - 1);
    return `${start + index * step}px`;
  };

  const syncManagedEdges = (branches: ConditionBranch[]) => {
    const branchMap = new Map(branches.map((branch) => [branch.id, branch]));
    const currentEdges = store.getEdges();
    let changed = false;

    const nextEdges = currentEdges
      .filter((edge) => {
        if (edge.source !== currentNodeId || !edge.data?.managedByConditionNode) {
          return true;
        }

        const branchId =
          (edge.data?.branchId as string) ||
          (typeof edge.sourceHandle === 'string' && edge.sourceHandle.startsWith('branch_')
            ? edge.sourceHandle.slice(7)
            : '');

        if (!branchId || !branchMap.has(branchId)) {
          changed = true;
          return false;
        }

        return true;
      })
      .map((edge) => {
        if (edge.source !== currentNodeId || !edge.data?.managedByConditionNode) {
          return edge;
        }

        const branchId =
          (edge.data?.branchId as string) ||
          (typeof edge.sourceHandle === 'string' && edge.sourceHandle.startsWith('branch_')
            ? edge.sourceHandle.slice(7)
            : '');

        const branch = branchMap.get(branchId);
        if (!branch) {
          return edge;
        }

        const expectedData = {
          ...(edge.data || {}),
          managedByConditionNode: true,
          branchId: branch.id,
          branchLabel: branch.label,
          condition: buildBranchCondition(branch.id)
        };

        const expectedSourceHandle = `branch_${branch.id}`;

        if (!deepEqual(edge.data, expectedData) || edge.sourceHandle !== expectedSourceHandle) {
          changed = true;
          return {
            ...edge,
            sourceHandle: expectedSourceHandle,
            data: expectedData
          } as Edge;
        }

        return edge;
      });

    if (changed) {
      store.setEdges(nextEdges);
    }
  };

  const patchNodeData = (updater: (draft: ConditionNodeData) => void) => {
    updateNodeData(currentNodeId, (node) => {
      const normalized = normalizeConditionData(node.data || {});
      const draft = clone(normalized);
      updater(draft);
      const next = normalizeConditionData(draft);
      syncManagedEdges(next.branches);
      return {
        ...next
      };
    });
  };

  const addBranch = () => {
    patchNodeData((draft) => {
      const defaultBranch = draft.branches[draft.branches.length - 1];
      const normalBranches = draft.branches.slice(0, -1);
      const branch = createBranch(`条件分支${normalBranches.length + 1}`);
      activeBranchId = branch.id;
      draft.branches = [...normalBranches, branch, defaultBranch];
    });
  };

  const removeBranch = (branchId: string) => {
    patchNodeData((draft) => {
      if (branchId === draft.defaultBranchId) {
        return;
      }
      const normalCount = draft.branches.filter((branch) => branch.id !== draft.defaultBranchId).length;
      if (normalCount <= 1) {
        return;
      }
      draft.branches = draft.branches.filter((branch) => branch.id !== branchId);
    });
  };

  const moveBranch = (branchId: string, direction: 'up' | 'down') => {
    patchNodeData((draft) => {
      if (branchId === draft.defaultBranchId) {
        return;
      }

      const defaultBranch = draft.branches[draft.branches.length - 1];
      const normalBranches = draft.branches.slice(0, -1);
      const index = normalBranches.findIndex((branch) => branch.id === branchId);
      if (index === -1) {
        return;
      }

      if (direction === 'up' && index > 0) {
        const temp = normalBranches[index - 1];
        normalBranches[index - 1] = normalBranches[index];
        normalBranches[index] = temp;
      }

      if (direction === 'down' && index < normalBranches.length - 1) {
        const temp = normalBranches[index + 1];
        normalBranches[index + 1] = normalBranches[index];
        normalBranches[index] = temp;
      }

      draft.branches = [...normalBranches, defaultBranch];
    });
  };

  const updateBranchField = (branchId: string, key: string, value: any) => {
    patchNodeData((draft) => {
      draft.branches = draft.branches.map((branch) => {
        if (branch.id !== branchId) {
          return branch;
        }

        const nextBranch = { ...branch };

        if (key === 'addRule') {
          nextBranch.rules = branch.rules ? [...branch.rules] : [];
          nextBranch.rules.push(createRule(value ? (value as RuleJoiner) : 'AND'));
        } else if (key === 'removeRule') {
          nextBranch.rules = branch.rules ? branch.rules.filter((rule) => rule.id !== value) : [];
          if (nextBranch.rules.length === 0) {
            nextBranch.rules.push(createRule('AND'));
          }
        } else if (key === 'joiner') {
          nextBranch.rules = branch.rules ? branch.rules.map(r => ({ ...r, joiner: value as RuleJoiner })) : [];
        } else {
          // @ts-ignore
          nextBranch[key] = value;
        }

        if (key === 'mode' && value === 'visual' && (!nextBranch.rules || nextBranch.rules.length === 0)) {
          nextBranch.rules = [createRule('AND')];
        }

        return nextBranch;
      });
    });
  };

  const toggleMode = (branchId: string) => {
    const branch = branches.find((item) => item.id === branchId);
    if (!branch || branch.id === defaultBranchId) {
      return;
    }
    const nextMode: BranchMode = branch.mode === 'visual' ? 'expression' : 'visual';
    updateBranchField(branchId, 'mode', nextMode);
  };

  const updateRuleField = (
    branchId: string,
    ruleId: string,
    key: keyof ConditionRule,
    value: any
  ) => {
    patchNodeData((draft) => {
      draft.branches = draft.branches.map((branch) => {
        if (branch.id !== branchId) {
          return branch;
        }

        return {
          ...branch,
          rules: (branch.rules || []).map((rule) => {
            if (rule.id !== ruleId) {
              return rule;
            }

            const nextRule = {
              ...rule,
              [key]: value
            };

            if (key === 'operator' && !isOperatorNeedRight(value as ConditionOperator)) {
              nextRule.rightType = 'fixed';
              nextRule.rightRef = '';
              nextRule.rightValue = '';
            }

            if (key === 'rightValue') {
              nextRule.rightType = 'fixed';
              nextRule.rightRef = '';
            }

            if (key === 'rightRef') {
              const refText = String(value || '').trim();
              nextRule.rightRef = refText;
              const hasRef = !!refText;
              nextRule.rightType = hasRef ? 'ref' : 'fixed';
              if (hasRef) {
                nextRule.rightValue = refText;
              } else {
                nextRule.rightValue = '';
              }
            }

            return nextRule;
          })
        };
      });
    });
  };

  const switchRuleRightToRef = (branchId: string, ruleId: string) => {
    patchNodeData((draft) => {
      draft.branches = draft.branches.map((branch) => {
        if (branch.id !== branchId) {
          return branch;
        }

        return {
          ...branch,
          rules: (branch.rules || []).map((rule) => {
            if (rule.id !== ruleId) {
              return rule;
            }
            return {
              ...rule,
              rightType: 'ref',
              rightRef: '',
              rightValue: ''
            };
          })
        };
      });
    });
  };

  const normalizedData = $derived.by(() => normalizeConditionData(data || {}));
  const defaultBranchId = $derived(normalizedData.defaultBranchId);
  const branches = $derived(normalizedData.branches);
  const tokenParameters = $derived.by(() => {
    const items = (refOptions.current || []) as SelectItem[];
    const names = new Set<string>();
    const result: Parameter[] = [];

    const walk = (list: SelectItem[]) => {
      for (const item of list) {
        if (item.selectable) {
          const name = String(item.value || '').trim();
          if (name && !names.has(name)) {
            names.add(name);
            result.push({
              name,
              ref: name,
              refType: 'ref'
            });
          }
        }
        if (Array.isArray(item.children) && item.children.length > 0) {
          walk(item.children);
        }
      }
    };

    walk(items);
    return result;
  });

  const activeBranch = $derived.by(() => {
    return branches.find((branch) => branch.id === activeBranchId) || branches[0];
  });

  const activeBranchIndex = $derived.by(() => {
    if (!activeBranch) {
      return -1;
    }
    return branches.findIndex((branch) => branch.id === activeBranch.id);
  });

  const normalBranchCount = $derived.by(() => {
    return branches.filter((branch) => branch.id !== defaultBranchId).length;
  });

  const missingBranchLabels = $derived.by(() => {
    const edges = store.getEdges();
    const connected = new Set<string>();

    for (const edge of edges) {
      if (edge.source !== currentNodeId || !edge.data?.managedByConditionNode) {
        continue;
      }
      const branchId =
        (edge.data?.branchId as string) ||
        (typeof edge.sourceHandle === 'string' && edge.sourceHandle.startsWith('branch_')
          ? edge.sourceHandle.slice(7)
          : '');
      if (branchId) {
        connected.add(branchId);
      }
    }

    const missing: string[] = [];
    branches.forEach((branch, index) => {
      if (!connected.has(branch.id)) {
        missing.push(branchWarningLabel(branch, index, defaultBranchId));
      }
    });

    return missing;
  });

  $effect(() => {
    if (branches.length === 0) {
      activeBranchId = '';
      return;
    }

    const exists = branches.some((branch) => branch.id === activeBranchId);
    if (!activeBranchId || !exists) {
      activeBranchId = branches[0].id;
    }
  });

  $effect(() => {
    const normalized = normalizeConditionData(data || {});
    const currentComparable = {
      branchMode: data?.branchMode,
      branches: data?.branches,
      defaultBranchId: data?.defaultBranchId,
      defaultBranchLabel: data?.defaultBranchLabel
    };

    if (!deepEqual(currentComparable, normalized)) {
      updateNodeData(currentNodeId, normalized);
    }

    syncManagedEdges(normalized.branches);
  });

  $effect(() => {
    branches.map((branch) => branch.id).join('|');
    isExpanded();
    updateNodeInternals(currentNodeId);
  });
</script>

<NodeWrapper {data} {...rest} showSourceHandle={false} allowSettingOfCondition={false}>
    {#snippet icon()}
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
            <path d="M4 4H10V10H4V4ZM14 4H20V10H14V4ZM4 14H10V20H4V14ZM14 14H20V20H14V14ZM10 7H14V9H10V7ZM7 10H9V14H7V10ZM15 10H17V14H15V10Z"></path>
        </svg>
    {/snippet}

    {#snippet handle()}
        {#if !isExpanded()}
            {#each branches as branch, index}
                <Handle
                    type="source"
                    position={Position.Right}
                    id={`branch_${branch.id}`}
                    class="condition-branch-handle condition-branch-handle-collapsed"
                    style={`right: -28px; top: ${collapsedHandleTop(index, branches.length)};`}
                />
            {/each}
        {/if}
    {/snippet}

    <div class="condition-node-content">
    <div class="condition-rail-head">
        <div class="condition-rail-title">分支出口</div>
        <Button class="condition-icon-btn" title="新增分支" onclick={addBranch}>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M11 11V5H13V11H19V13H13V19H11V13H5V11H11Z"></path>
            </svg>
        </Button>
    </div>

    <div class="condition-branch-rail">
        {#each branches as branch, index}
            {@const isDefaultBranch = branch.id === defaultBranchId}
            {@const isActiveBranch = activeBranch?.id === branch.id}
            <div class={`condition-branch-row ${isActiveBranch ? 'active' : ''} ${isDefaultBranch ? 'default' : ''}`}
                 role="button"
                 tabindex={isDefaultBranch ? -1 : 0}
                 onclick={() => {
                     if(isDefaultBranch) return;
                     activeBranchId = branch.id;
                 }}
                 onkeydown={(event) => {
                     if(isDefaultBranch) return;
                     if (event.key === 'Enter' || event.key === ' ') {
                       event.preventDefault();
                       activeBranchId = branch.id;
                     }
                 }}>
                <div class="condition-branch-prefix">{branchKeyword(branch, index, defaultBranchId)}</div>
                {#if isDefaultBranch || (index === 0 && normalBranchCount === 1)}
                    <div class="condition-branch-name" style="padding-left: 8px">{branch.label || `条件分支${index + 1}`}</div>
                {:else}
                    {#if editingBranchId === branch.id}
                        <Input
                            value={branch.label}
                            placeholder={`条件分支${index + 1}`}
                            variant="borderless"
                            autofocus
                            onblur={(e) => {
                                updateBranchField(branch.id, 'label', (e.target as HTMLInputElement).value);
                                editingBranchId = null;
                            }}
                            onkeydown={(e) => {
                                e.stopPropagation();
                                if (e.key === 'Enter') {
                                    updateBranchField(branch.id, 'label', (e.target as HTMLInputElement).value);
                                    editingBranchId = null;
                                }
                            }}
                            style="flex: 1; height: 100%; min-width: 0;"
                        />
                    {:else}
                        <div
                            class="condition-branch-name"
                            style="padding-left: 8px"
                            role="button"
                            tabindex="0"
                            ondblclick={(e) => { e.stopPropagation(); editingBranchId = branch.id; }}
                            onkeydown={(e) => {
                                e.stopPropagation();
                                if (e.key === 'Enter' || e.key === ' ') {
                                    e.preventDefault();
                                    editingBranchId = branch.id;
                                }
                            }}
                        >
                            {branch.label || `条件分支${index + 1}`}
                        </div>
                    {/if}
                    <Button
                        class="condition-icon-btn danger"
                        title="删除分支"
                        onclick={(e) => { e.stopPropagation(); removeBranch(branch.id); }}
                        style="opacity: 0.6; padding: 2px; margin-right: 18px;"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="14" height="14">
                            <path d="M17 6H22V8H20V21C20 21.5523 19.5523 22 19 22H5C4.44772 22 4 21.5523 4 21V8H2V6H7V3C7 2.44772 7.44772 2 8 2H16C16.5523 2 17 2.44772 17 3V6ZM18 8H6V20H18V8Z"></path>
                        </svg>
                    </Button>
                {/if}
                {#if isExpanded()}
                    <Handle
                        type="source"
                        position={Position.Right}
                        id={`branch_${branch.id}`}
                        class="condition-branch-handle"
                        style="right: -28px; top: 50%; transform: translateY(-50%);"
                    />
                {/if}
            </div>
        {/each}
    </div>



    {#if activeBranch}
        {@const isDefault = activeBranch.id === defaultBranchId}
        <div class="condition-editor-card">

            {#if isDefault}
                <div class="condition-default-tip">Else 分支作为兜底执行，不配置条件。</div>
            {:else if activeBranch.mode === 'visual'}
                <div class="condition-rules-container">
                    <!-- removed condition-joiner-rail -->
                    <div class="condition-rules-wrapper">
                        <div class="condition-rules-list">
                            {#each activeBranch.rules || [] as rule, ruleIndex}
                                {#if ruleIndex > 0}
                                    <div class="condition-rule-joiner-row">
                                        <button
                                            class="tf-joiner-text-btn {rule.joiner === 'AND' ? 'active' : ''}"
                                            onclick={() => updateRuleField(activeBranch.id, rule.id, 'joiner', 'AND')}
                                        >AND</button>
                                        <span class="tf-joiner-divider">|</span>
                                        <button
                                            class="tf-joiner-text-btn {rule.joiner === 'OR' ? 'active' : ''}"
                                            onclick={() => updateRuleField(activeBranch.id, rule.id, 'joiner', 'OR')}
                                        >OR</button>
                                    </div>
                                {/if}
                                <div class="condition-simple-rule-row">
                                    <Select
                                        items={refOptions.current}
                                        variant="reference"
                                        showSelectedType={false}
                                        placeholder="左侧参数"
                                        value={rule.leftRef ? [rule.leftRef] : []}
                                        onSelect={(item) => updateRuleField(activeBranch.id, rule.id, 'leftRef', item.value)}
                                    />
                                    <Select
                                        items={OPERATOR_ITEMS as any}
                                        placeholder="条件"
                                        value={[rule.operator]}
                                        onSelect={(item) => updateRuleField(activeBranch.id, rule.id, 'operator', item.value)}
                                    />
                                    {#if isOperatorNeedRight(rule.operator)}
                                        <div class="condition-right-unified-box">
                                            <MixedInput
                                                type={rule.rightType}
                                                textValue={rule.rightValue}
                                                refValue={rule.rightRef}
                                                refOptions={refOptions.current}
                                                onTypeChange={(t) => updateRuleField(activeBranch.id, rule.id, 'rightType', t)}
                                                onTextChange={(val) => updateRuleField(activeBranch.id, rule.id, 'rightValue', val)}
                                                onRefChange={(val) => updateRuleField(activeBranch.id, rule.id, 'rightRef', val)}
                                            />
                                            {#if activeBranch.rules!.length > 1}
                                                <Button
                                                    class="condition-rule-remove-btn"
                                                    title="删除条件"
                                                    onclick={() => updateBranchField(activeBranch.id, 'removeRule', rule.id)}
                                                >
                                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                                                        <path d="M12 2C6.47 2 2 6.47 2 12C2 17.53 6.47 22 12 22C17.53 22 22 17.53 22 12C22 6.47 17.53 2 12 2ZM17 13H7V11H17V13Z"></path>
                                                    </svg>
                                                </Button>
                                            {/if}
                                        </div>
                                    {:else}
                                        <div class="condition-right-unified-box">
                                            <Input value="" placeholder="该条件无需右值" disabled style="flex: 1; min-width: 0;" />
                                            {#if activeBranch.rules!.length > 1}
                                                <Button
                                                    class="condition-rule-remove-btn"
                                                    title="删除条件"
                                                    onclick={() => updateBranchField(activeBranch.id, 'removeRule', rule.id)}
                                                >
                                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                                                        <path d="M12 2C6.47 2 2 6.47 2 12C2 17.53 6.47 22 12 22C17.53 22 22 17.53 22 12C22 6.47 17.53 2 12 2ZM17 13H7V11H17V13Z"></path>
                                                    </svg>
                                                </Button>
                                            {/if}
                                        </div>
                                    {/if}
                                </div>
                            {/each}
                        </div>
                        <div class="condition-rule-add-row">
                            <Button class="condition-rule-add-btn" onclick={() => updateBranchField(activeBranch.id, 'addRule', 'AND')}>
                                + 添加条件
                            </Button>
                        </div>
                    </div>
                </div>
            {:else if SHOW_EXPRESSION_ENTRY}
                <div class="condition-expression-panel">
                    <ParamTokenEditor
                        mode="textarea"
                        rows={9}
                        placeholder={"输入表达式，例如：{{input.amount}} >= 100 && {{user.level}} === 'vip'"}
                        parameters={tokenParameters}
                        value={(activeBranch.expression || '') as string}
                        oninput={(event:any) => updateBranchField(activeBranch.id, 'expression', event.target.value)}
                        onchange={(event:any) => updateBranchField(activeBranch.id, 'expression', event.target.value)}
                    />
                </div>
            {/if}
        </div>
    {/if}
    </div>
</NodeWrapper>

<style lang="less">
  .condition-node-content {
    width: 420px;
    min-width: 420px;
    max-width: 420px;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .condition-rail-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 4px;
    padding: 0 2px;
  }

  .condition-rail-title {
    font-size: 13px;
    color: var(--tf-text-secondary);
    font-weight: 500;
  }

  .condition-branch-rail {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-bottom: 4px;
  }

  .condition-branch-row {
    position: relative;
    min-height: 44px;
    border: 1px solid var(--tf-border-color);
    border-radius: 6px;
    display: flex;
    align-items: center;
    background: var(--tf-bg-surface);
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      border-color: var(--tf-border-color-strong);
      background: var(--tf-bg-hover);
    }

    &.active {
      border-color: var(--tf-primary-color);
      box-shadow: 0 0 0 1px var(--tf-primary-color);
      z-index: 10;
    }

    &.default {
      border-style: dashed;
      background: var(--tf-bg-hover);
      cursor: default; /* Disable pointer since default branch is non-selectable */
    }
  }

  :global(.condition-branch-row .tf-input-wrapper) {
    border: none;
    background: transparent;
    box-shadow: none;
    padding: 0;
  }

  :global(.condition-branch-row .tf-input) {
    font-size: 13px;
    color: var(--tf-text-secondary);
    padding: 0;
  }

  :global(.condition-branch-row .tf-input:focus) {
    color: var(--tf-text-primary);
  }

  .condition-branch-prefix {
    min-width: 44px;
    width: max-content;
    font-size: 13px;
    display: flex;
    align-items: center;
    padding-left: 12px;
    padding-right: 8px;
    color: var(--tf-text-secondary);
    font-weight: 600;
    white-space: nowrap;
  }

  .condition-branch-name {
    flex: 1;
    min-width: 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    font-size: 13px;
    color: var(--tf-text-primary);
    font-weight: 500;
  }

  .condition-editor-card {
    border: none;
    background: transparent;
    padding: 0;
    margin-top: 4px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    box-shadow: none;
  }

  :global(.condition-branch-handle-collapsed) {
    transform: translateY(-50%);
  }

  .condition-editor-actions-inline {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
  }



  .condition-form-row {
    margin: 0;
  }

  .condition-rules-container {
    display: flex;
    position: relative;
    padding-left: 0; /* Removed left rail padding to easily center content */
    margin-top: 4px;
    margin-bottom: 8px;
    padding-right: 28px; /* Leave space on the right for absolute remove button */
  }

  /* Removed condition-joiner-rail and condition-joiner-line */

  :global(.condition-joiner-btn) {
    position: relative;
    z-index: 2;
    padding: 0;
    width: 20px;
    height: 20px;
    min-width: 20px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
    color: var(--tf-text-secondary);
    background: var(--tf-bg-muted);
    border: 1px solid var(--tf-border-color-strong);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: none;

    &:hover {
      background: var(--tf-border-color);
      color: var(--tf-text-primary);
    }
  }

  .condition-rules-wrapper {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .condition-rules-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .condition-rule-add-row {
    display: flex;
    justify-content: center;
    margin-top: 4px;
    padding-bottom: 8px;
  }

  :global(.condition-rule-add-btn) {
    min-width: 140px;
    background: var(--tf-bg-hover);
    border: 1px dashed var(--tf-border-color-strong);
    color: var(--tf-text-secondary);
    font-size: 13px;
    padding: 6px 12px;
    height: 28px;
    font-weight: 500;
    box-shadow: none;
    border-radius: 6px;
    transition: all 0.2s;

    &:hover {
      background: var(--tf-primary-soft-bg);
      border-color: var(--tf-primary-soft-border);
      color: var(--tf-primary-color);
    }
  }

  .condition-rule-joiner-row {
    margin-top: -2px;
    margin-bottom: -2px;
    position: relative;
    z-index: 2;
    padding-left: 0;
    display: flex;
    align-items: center;
    gap: 8px;
    /* Added to left-align the OR/AND switches properly above the left select */
    color: var(--tf-text-muted);
  }

  /* Custom joiner text buttons */
  .tf-joiner-text-btn {
    background: transparent;
    border: none;
    padding: 2px 4px;
    font-size: 12px;
    font-weight: 600;
    color: var(--tf-text-muted);
    cursor: pointer;
    transition: all 0.2s;
    border-radius: 4px;

    &:hover {
      color: var(--tf-text-secondary);
      background: var(--tf-bg-muted);
    }

    &.active {
      color: var(--tf-primary-color);
      background: var(--tf-primary-soft-bg);
    }
  }

  .tf-joiner-divider {
    font-size: 12px;
    color: var(--tf-border-color-strong);
    user-select: none;
  }


  :global(.condition-rule-remove-btn) {
    /* Set to absolute so it doesn't affect grid width consistency */
    position: absolute;
    right: -28px;
    top: 50%;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    padding: 0;
    border: none;
    background: transparent;
    color: var(--tf-border-color-strong);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    box-shadow: none;
    transition: all 0.2s;

    svg {
      width: 14px;
      height: 14px;
    }

    &:hover {
      background: var(--tf-danger-soft-bg);
      color: var(--tf-danger-color);
    }
  }

  .condition-simple-rule-row {
    display: grid;
    grid-template-columns: 34% 24% 42%;
    gap: 6px;
    min-width: 0;
    align-items: stretch;
  }

  .condition-simple-rule-row > * {
    min-width: 0;
    width: 100%;
  }

  :global(.condition-simple-rule-row .tf-select),
  :global(.condition-simple-rule-row .tf-mixed-input-root) {
    width: 100%;
    min-width: 0;
  }

  :global(.condition-simple-rule-row .tf-select-input),
  :global(.condition-simple-rule-row .tf-mixed-input-root),
  :global(.condition-simple-rule-row .tf-input),
  :global(.condition-simple-rule-row .tf-textarea) {
    background: var(--tf-bg-input);
    border-color: var(--tf-border-color-strong);
    color: var(--tf-text-primary);
  }

  :global(.condition-simple-rule-row .tf-select-input:hover),
  :global(.condition-simple-rule-row .tf-mixed-input-root:hover) {
    border-color: var(--tf-border-color-strong);
  }

  :global(.condition-icon-btn) {
    width: 26px;
    height: 26px;
    min-width: 26px;
    border-color: transparent;
    border-radius: 4px;
    background: transparent;
    color: var(--tf-text-secondary);
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    box-shadow: none;

    svg {
      width: 14px;
      height: 14px;
    }
  }

  :global(.condition-icon-btn:hover:not(:disabled)) {
    background: var(--tf-border-color-strong);
    color: var(--tf-text-primary);
  }

  :global(.condition-icon-btn.danger) {
    color: var(--tf-danger-color);
  }

  :global(.condition-icon-btn.danger:hover:not(:disabled)) {
    background: var(--tf-danger-soft-bg);
    color: var(--tf-danger-hover);
  }

  :global(.condition-icon-btn:disabled),
  :global(.condition-icon-btn[disabled]) {
    color: var(--tf-border-color-strong);
    background: transparent;
    cursor: not-allowed;
  }

  .condition-default-tip {
    color: var(--tf-text-secondary);
    font-size: 12px;
    padding: 8px 10px;
    border-radius: 6px;
    background: var(--tf-bg-muted);
    border: 1px dashed var(--tf-border-color-strong);
    text-align: center;
  }

  .condition-right-unified-box {
    position: relative;
    min-width: 0;
    width: 100%;
    display: flex;
    align-items: center;
    gap: 4px;
    height: 32px;
  }

  .condition-expression-panel {
    min-height: 140px;
    display: flex;
    align-items: stretch;
  }

  @media (max-width: 768px) {
    .condition-simple-rule-row {
      grid-template-columns: 1fr;
    }

    .condition-editor-head {
      flex-wrap: wrap;
    }

    .condition-editor-actions {
      width: 100%;
      justify-content: flex-start;
    }
  }
</style>
