// ============================================================
// DirectoryCreateModal — 可复用新建目录弹窗
//
// 用法：
//   <DirectoryCreateModal
//       open={open}
//       title="新建项目"
//       onOk={(name) => handleCreate(name)}
//       onCancel={() => setOpen(false)}
//   />
// ============================================================

import { useState, useCallback } from 'react';
import { Modal, Input } from 'antd';

interface DirectoryCreateModalProps {
    open: boolean;
    title: string;
    onOk: (name: string) => void;
    onCancel: () => void;
}

/** 危险字符正则（Windows + 通用非法字符） */
const DANGEROUS_CHARS = /[/\\:*?"<>|]/;

export function DirectoryCreateModal({ open, title, onOk, onCancel }: DirectoryCreateModalProps) {
    const [value, setValue] = useState('');
    const [error, setError] = useState<string | null>(null);

    const handleOk = useCallback(() => {
        const trimmed = value.trim();
        if (!trimmed) {
            setError('名称不能为空');
            return;
        }
        if (DANGEROUS_CHARS.test(trimmed)) {
            setError('名称包含非法字符（/ \\ : * ? " < > |）');
            return;
        }
        setError(null);
        setValue('');
        onOk(trimmed);
    }, [value, onOk]);

    const handleCancel = useCallback(() => {
        setError(null);
        setValue('');
        onCancel();
    }, [onCancel]);

    return (
        <Modal
            title={title}
            open={open}
            onOk={handleOk}
            onCancel={handleCancel}
            okText="创建"
            cancelText="取消"
            destroyOnHidden={true}
        >
            <Input
                placeholder="请输入目录名称"
                value={value}
                onChange={(e) => {
                    setValue(e.target.value);
                    if (error) setError(null);
                }}
                onPressEnter={handleOk}
                status={error ? 'error' : undefined}
            />
            {error && <div style={{ color: '#ff4d4f', fontSize: 12, marginTop: 4 }}>{error}</div>}
        </Modal>
    );
}
