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

function DialogFlowNode({ id, data, selected, type }) {
  const { getNodeHandles } = useWorkflow();
  const handles = getNodeHandles(type, data);
  const runtime = data.runtime || {};
  const messages = runtime.messages || [];
  const minHeight = Math.max((data.height || 280) - 110, 160);

  return (
    <NodeShell
      nodeId={id}
      title={data.title}
      accent={getNodeAccent(type)}
      selected={selected}
      status={runtime.status}
      inputs={handles.inputs}
      outputs={handles.outputs}
    >
      <div className="dialog-list nodrag" style={{ minHeight: `${minHeight}px` }}>
        {runtime.cleared && messages.length === 0 ? (
          <div className="dialog-empty">Ожидает выполнения...</div>
        ) : null}

        {!runtime.cleared && messages.length === 0 ? (
          <div className="dialog-empty">Подключите Script-ноду, чтобы увидеть диалог.</div>
        ) : null}

        {messages.map((message, index) => (
          <div key={`${message.type}-${index}`} className={`dialog-message dialog-message--${message.type}`}>
            <span className="dialog-message__author">{message.type === 'user' ? 'Пользователь' : 'Персонаж'}</span>
            <p>{message.text}</p>
          </div>
        ))}
      </div>
      {runtime.error ? <div className="node-error">{runtime.error}</div> : null}
    </NodeShell>
  );
}

export default memo(DialogFlowNode);
