import { memo } from 'react';
import NodeShell from '../components/NodeShell.jsx';
import { NodeDraftInput } from '../components/NodeDraftField.jsx';
import { useWorkflow } from '../context/WorkflowContext.jsx';
import { getNodeAccent } from '../lib/nodeRegistry.js';

function CounterFlowNode({ id, data, selected, type }) {
  const { getNodeHandles, patchNodeData } = useWorkflow();
  const handles = getNodeHandles(type, data);
  const runtime = data.runtime || {};

  return (
    <NodeShell
      nodeId={id}
      title={data.title}
      accent={getNodeAccent(type)}
      selected={selected}
      status={runtime.status}
      inputs={handles.inputs}
      outputs={handles.outputs}
    >
      <div className="field-stack">
        <label className="field-row">
          <span>Memory key</span>
          <NodeDraftInput
            className="nodrag node-input"
            type="text"
            value={data.key || ''}
            placeholder="counter"
            onCommit={(value) => patchNodeData(id, { key: value })}
          />
        </label>

        <label className="field-row">
          <span>Limit</span>
          <NodeDraftInput
            className="nodrag node-input"
            type="number"
            min="1"
            step="1"
            value={data.limit || 3}
            onCommit={(value) => patchNodeData(id, { limit: Number(value) || 1 })}
          />
        </label>

        <div className="node-note">
          {runtime.count
            ? `Сейчас: ${runtime.count}/${runtime.limit || data.limit}. Выход: ${runtime.matchId || 'continue'}.`
            : 'Увеличивает счетчик и пропускает поток через continue до лимита, затем через done.'}
        </div>

        {runtime.error ? <div className="node-error">{runtime.error}</div> : null}
      </div>
    </NodeShell>
  );
}

export default memo(CounterFlowNode);
