'use client';
/**
 * ImportTextModal — 导入外部文案弹窗（R4-c 轨B 补输入入口）
 * 此前"导入外部文案"按钮直接建任务跳走，没给用户贴文案的地方。
 * 这里让用户粘贴多条文案（用一行 "---" 分隔），确认后回调父组件：
 * 父组件先建任务(track=import)，再逐条调 import-text 端点，最后跳 text 页。
 */
import { useEffect, useState } from 'react';

interface Props {
  open: boolean;
  submitting: boolean;
  onClose: () => void;
  /** 返回切分后的多条文案，父组件负责建任务+逐条导入 */
  onConfirm: (contents: string[]) => void;
}

const SPLIT_HINT = '多条文案用单独一行 --- 分隔；只贴一条则整体作为一条';

function splitContents(raw: string): string[] {
  return raw
    .split(/^\s*---\s*$/m)
    .map((s) => s.trim())
    .filter((s) => s.length > 0);
}

export function ImportTextModal({ open, submitting, onClose, onConfirm }: Props) {
  const [raw, setRaw] = useState('');
  // 每次打开清空上次残留内容，避免重新打开显示旧文案+旧计数
  useEffect(() => { if (open) setRaw(''); }, [open]);
  if (!open) return null;

  const parts = splitContents(raw);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
      role="dialog"
      aria-modal="true"
      aria-label="导入外部文案"
      onClick={onClose}
    >
      <div
        className="bg-surface-primary rounded-2xl shadow-xl w-full max-w-lg p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <h3 className="text-lg font-bold text-text-primary mb-1">导入外部文案</h3>
        <p className="text-xs text-text-tertiary mb-3 leading-relaxed">
          把已有文案贴进来直接进候选池，跳过 AI 生成。{SPLIT_HINT}。
        </p>
        <textarea
          value={raw}
          onChange={(e) => setRaw(e.target.value)}
          rows={10}
          placeholder={'第一条文案…\n---\n第二条文案…'}
          className="w-full border border-border-default rounded-lg px-3 py-2 text-sm
                     focus:outline-none focus:border-brand-orange resize-y"
          aria-label="粘贴文案内容"
        />
        <div className="flex items-center justify-between mt-3">
          <span className="text-xs text-text-secondary">
            将导入 <strong className="text-text-primary">{parts.length}</strong> 条
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={onClose}
              className="text-sm px-4 py-2 rounded-lg border border-border-default text-text-secondary hover:bg-surface-tertiary"
            >
              取消
            </button>
            <button
              type="button"
              disabled={parts.length === 0 || submitting}
              onClick={() => onConfirm(parts)}
              className="text-sm px-4 py-2 rounded-lg bg-brand-orange text-white font-medium
                         hover:bg-orange-600 disabled:opacity-50"
            >
              {submitting ? '导入中…' : `导入这 ${parts.length} 条 →`}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
