// Upload modal with drag-drop zone, metadata, auto-tag preview, OCR routing
function DocUploadModal({ open, onClose }) {
  const T_um = window.ArbiterTokens;
  const { useState: useUS } = React;
  const [files, setFiles] = useUS([]);
  const [dragOver, setDragOver] = useUS(false);
  const [matter, setMatter] = useUS('Redstone v. Meridian');
  const [folderId, setFolderId] = useUS('F-001A');
  const [confidentiality, setConfidentiality] = useUS('Confidential');
  const [tags, setTags] = useUS('');
  const [workspace, setWorkspace] = useUS('WS-LIT');
  const [applyOCR, setApplyOCR] = useUS(true);
  const [runDLP, setRunDLP] = useUS(true);

  if (!open) return null;

  const matters = [...new Set(window.DOC_ITEMS.map(d => d.matter))];
  const folders = window.DOC_FOLDERS.filter(f => f.id !== 'F-ROOT');
  const workspaces = window.DOC_WORKSPACES;
  const levels = ['Public', 'Internal', 'Confidential', 'Work Product', 'Highly Confidential', 'Highly Confidential — AEO'];

  const pickedFiles = files.length > 0 ? files : [
    { name: 'Draft — Motion for Protective Order.docx', size: '1.2 MB', ext: 'DOCX' },
    { name: 'Harmon Deposition Exhibits 1-14.pdf', size: '18.4 MB', ext: 'PDF' },
  ];

  const suggestTags = (name) => {
    const n = name.toLowerCase();
    const t = [];
    if (n.includes('motion') || n.includes('brief')) t.push('motion');
    if (n.includes('depo')) t.push('deposition');
    if (n.includes('exhibit')) t.push('exhibit');
    if (n.includes('draft')) t.push('draft');
    if (n.includes('protective')) t.push('confidential');
    if (n.includes('harmon')) t.push('Harmon');
    return t;
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    const dropped = [...e.dataTransfer.files].map(f => ({ name: f.name, size: (f.size / 1048576).toFixed(1) + ' MB', ext: f.name.split('.').pop().toUpperCase() }));
    if (dropped.length) setFiles(dropped);
  };

  const doUpload = () => {
    const folderMatch = folders.find(f => f.id === folderId);
    const tagList = tags.split(',').map(t => t.trim()).filter(Boolean);
    pickedFiles.forEach(f => {
      window.DocStore.upload({
        name: f.name,
        size: f.size,
        ext: f.ext,
        type: f.ext === 'XLSX' ? 'Analysis' : f.ext === 'PDF' ? 'Evidence' : 'Brief',
        matter,
        matterId: folderMatch?.matterId || null,
        folderId,
        confidentiality,
        permissions: ['M. Kirkland'],
        tags: [...tagList, ...suggestTags(f.name)],
      });
    });
    onClose();
  };

  const panelStyle = { background: T_um.color.bg.card, border: `1px solid ${T_um.color.border.light}`, borderRadius: '8px', padding: '12px 14px' };
  const labelStyle = { fontSize: '10px', fontWeight: 600, color: T_um.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px', display: 'block' };
  const fieldStyle = { width: '100%', padding: '7px 10px', fontSize: '12px', border: `1px solid ${T_um.color.border.light}`, borderRadius: '6px', background: T_um.color.bg.card, color: T_um.color.text.primary, fontFamily: T_um.font.family, outline: 'none', boxSizing: 'border-box' };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.4)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '720px', maxWidth: '94vw', maxHeight: '92vh', overflow: 'auto', background: T_um.color.bg.primary, borderRadius: '12px', boxShadow: '0 20px 60px rgba(10,22,40,0.3)' }}>
        <div style={{ padding: '18px 22px', borderBottom: `1px solid ${T_um.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '16px', fontWeight: 700, color: T_um.color.text.primary }}>Upload documents</div>
            <div style={{ fontSize: '11px', color: T_um.color.text.tertiary, marginTop: '2px' }}>Apply metadata, routing and compliance at upload time.</div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: '20px', color: T_um.color.text.tertiary, cursor: 'pointer' }}>×</button>
        </div>

        <div style={{ padding: '18px 22px' }}>
          {/* Drop zone */}
          <div
            onDragOver={e => { e.preventDefault(); setDragOver(true); }}
            onDragLeave={() => setDragOver(false)}
            onDrop={handleDrop}
            style={{ border: `2px dashed ${dragOver ? '#2563EB' : T_um.color.border.medium}`, background: dragOver ? 'rgba(37,99,235,0.05)' : T_um.color.bg.secondary, borderRadius: '10px', padding: '26px', textAlign: 'center', marginBottom: '16px', transition: 'all 0.15s' }}>
            <div style={{ fontSize: '26px', color: T_um.color.text.tertiary, marginBottom: '6px' }}>⬆</div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: T_um.color.text.primary, marginBottom: '2px' }}>Drop files or click to browse</div>
            <div style={{ fontSize: '11px', color: T_um.color.text.tertiary }}>Supports PDF, DOCX, XLSX, MSG · max 100 MB</div>
            <div style={{ marginTop: '10px', fontSize: '11px', color: T_um.color.text.tertiary }}>Queued <span style={{ fontFamily: T_um.font.mono, color: '#2563EB', fontWeight: 700 }}>{pickedFiles.length}</span> file(s)</div>
          </div>

          {/* File list + auto-tag preview */}
          {pickedFiles.length > 0 && (
            <div style={{ ...panelStyle, marginBottom: '16px' }}>
              <div style={{ fontSize: '11px', fontWeight: 700, color: T_um.color.text.primary, marginBottom: '8px' }}>Files ({pickedFiles.length})</div>
              {pickedFiles.map((f, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0', borderBottom: i < pickedFiles.length - 1 ? `1px solid ${T_um.color.border.light}` : 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', minWidth: 0, flex: 1 }}>
                    <span style={{ fontSize: '9px', fontWeight: 700, padding: '2px 6px', borderRadius: '3px', background: 'rgba(37,99,235,0.1)', color: '#2563EB' }}>{f.ext}</span>
                    <span style={{ fontSize: '12px', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{f.name}</span>
                  </div>
                  <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                    {suggestTags(f.name).slice(0, 3).map(t => (
                      <span key={t} style={{ fontSize: '10px', padding: '2px 6px', borderRadius: '10px', background: 'rgba(124,58,237,0.1)', color: '#7C3AED' }}>AI: {t}</span>
                    ))}
                    <span style={{ fontSize: '11px', color: T_um.color.text.tertiary, fontFamily: T_um.font.mono }}>{f.size}</span>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Metadata grid */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
            <div>
              <label style={labelStyle}>Matter</label>
              <select value={matter} onChange={e => setMatter(e.target.value)} style={fieldStyle}>
                {matters.map(m => <option key={m} value={m}>{m}</option>)}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Folder</label>
              <select value={folderId} onChange={e => setFolderId(e.target.value)} style={fieldStyle}>
                {folders.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Workspace</label>
              <select value={workspace} onChange={e => setWorkspace(e.target.value)} style={fieldStyle}>
                {workspaces.map(w => <option key={w.id} value={w.id}>{w.name} ({w.kind})</option>)}
              </select>
            </div>
            <div>
              <label style={labelStyle}>Confidentiality</label>
              <select value={confidentiality} onChange={e => setConfidentiality(e.target.value)} style={fieldStyle}>
                {levels.map(l => <option key={l} value={l}>{l}</option>)}
              </select>
            </div>
          </div>
          <div style={{ marginBottom: '14px' }}>
            <label style={labelStyle}>Additional tags (comma-separated)</label>
            <input value={tags} onChange={e => setTags(e.target.value)} placeholder="privileged, hot, urgent" style={fieldStyle} />
          </div>

          {/* Pipeline routing preview */}
          <div style={{ ...panelStyle, marginBottom: '14px', background: T_um.color.bg.secondary }}>
            <div style={{ fontSize: '11px', fontWeight: 700, color: T_um.color.text.primary, marginBottom: '6px' }}>Processing pipeline</div>
            <label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px', color: T_um.color.text.secondary, marginBottom: '4px', cursor: 'pointer' }}>
              <input type="checkbox" checked={applyOCR} onChange={e => setApplyOCR(e.target.checked)} /> Route PDFs through OCR (Production — Native PDF queue: +{pickedFiles.filter(f => f.ext === 'PDF').length})
            </label>
            <label style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '12px', color: T_um.color.text.secondary, cursor: 'pointer' }}>
              <input type="checkbox" checked={runDLP} onChange={e => setRunDLP(e.target.checked)} /> Run DLP scan (SSN, PCI, credentials)
            </label>
          </div>
        </div>

        <div style={{ padding: '14px 22px', borderTop: `1px solid ${T_um.color.border.light}`, display: 'flex', gap: '8px', justifyContent: 'flex-end', background: T_um.color.bg.card }}>
          <button onClick={onClose} style={{ padding: '8px 16px', fontSize: '12px', fontWeight: 600, border: `1px solid ${T_um.color.border.light}`, background: T_um.color.bg.card, color: T_um.color.text.secondary, borderRadius: '6px', cursor: 'pointer' }}>Cancel</button>
          <button onClick={doUpload} style={{ padding: '8px 16px', fontSize: '12px', fontWeight: 700, border: 'none', background: '#2563EB', color: '#fff', borderRadius: '6px', cursor: 'pointer' }}>Upload {pickedFiles.length} file{pickedFiles.length !== 1 ? 's' : ''}</button>
        </div>
      </div>
    </div>
  );
}
window.DocUploadModal = DocUploadModal;
