// Primus IQ — Tagging Modal

const SAMPLE_DROPPED = [
  { id: 'd1',  name: 'GCC_Market_Sizing_v4.pptx',     size: '12.0 MB', ext: 'pptx', suggest: 'strict',   pages: 28, tags: ['GCC', 'Sizing'] },
  { id: 'd2',  name: 'Acme_Financial_Model.xlsx',     size: '4.2 MB',  ext: 'xlsx', suggest: 'strict',   pages: 12, tags: ['Acme', 'Finance'] },
  { id: 'd3',  name: 'IndustryReport_Q4.pdf',         size: '8.6 MB',  ext: 'pdf',  suggest: 'public',   pages: 64, tags: ['Research'] },
  { id: 'd4',  name: 'Interview_Notes_CFO.docx',      size: '120 KB',  ext: 'docx', suggest: 'client',   pages: 4,  tags: ['Acme', 'Interview'] },
  { id: 'd5',  name: 'ESG_Compliance_Brief.pdf',      size: '2.1 MB',  ext: 'pdf',  suggest: 'internal', pages: 18, tags: ['ESG'] },
  { id: 'd6',  name: 'Pitch_Storyline_draft.pptx',    size: '6.8 MB',  ext: 'pptx', suggest: 'internal', pages: 22, tags: ['Pitch'] },
  { id: 'd7',  name: 'Supply_chain_diagram.png',      size: '880 KB',  ext: 'png',  suggest: 'internal', pages: 1,  tags: ['Diagram'] },
  { id: 'd8',  name: 'Bid_Cost_Calculator.xlsx',      size: '1.4 MB',  ext: 'xlsx', suggest: 'strict',   pages: 8,  tags: ['RFP'] },
  { id: 'd9',  name: 'Client_brief_v2.docx',          size: '340 KB',  ext: 'docx', suggest: 'client',   pages: 6,  tags: ['Acme', 'Brief'] },
  { id: 'd10', name: 'Site_visit_video.mp4',          size: '48.2 MB', ext: 'mp4',  suggest: 'internal', pages: 0,  tags: ['Field'] },
];

const CONF_OPTIONS = [
  { id: 'public',   label: 'Public',                 desc: 'Anyone' },
  { id: 'internal', label: 'Internal',               desc: 'All Employees' },
  { id: 'client',   label: 'Confidential',           desc: 'Restricted Projects' },
  { id: 'strict',   label: 'Restricted Visibility',  desc: 'Only MDs' },
];

const CONF_LABELS = {
  public:   'Public',
  internal: 'Internal',
  client:   'Confidential',
  strict:   'Restricted Visibility',
};

const SUGGESTED_TAGS = ['GCC', 'KSA', 'UAE', 'Fintech', 'Climate', 'Policy', 'Healthcare', 'TCFD', 'CSRD', 'Acme', 'Globex'];

const TaggingModal = ({ open, onClose, onCommit, pendingFiles = [], editMode = false }) => {
  const [files, setFiles] = React.useState([]);
  const [active, setActive] = React.useState(0);
  const [tagInput, setTagInput] = React.useState('');

  React.useEffect(() => {
    if (open) {
      setFiles(pendingFiles.length > 0
        ? pendingFiles
        : SAMPLE_DROPPED.map(f => ({ ...f, conf: f.suggest })));
      setActive(0);
      setTagInput('');
    }
  }, [open, pendingFiles]);

  // Must be before any early return — hooks must always run in the same order.
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowDown') setActive(a => Math.min(a + 1, files.length - 1));
      if (e.key === 'ArrowUp')   setActive(a => Math.max(a - 1, 0));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, files]);

  if (!open) return null;

  if (files.length === 0) return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 60,
      background: 'var(--bg-overlay)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        padding: '40px 48px', background: 'var(--bg-card)', borderRadius: 18,
        boxShadow: 'var(--shadow-lg)', textAlign: 'center',
      }}>
        <div style={{ fontSize: 32, marginBottom: 12 }}>📂</div>
        <div className="t-h3" style={{ marginBottom: 8 }}>No files selected</div>
        <div style={{ fontSize: 13, color: 'var(--mute)', marginBottom: 20 }}>Drop files on the zone or use the Upload button.</div>
        <button className="btn-secondary" onClick={onClose}>Close</button>
      </div>
    </div>
  );

  const f = files[active];
  const updateFile = (idx, patch) => {
    setFiles(prev => prev.map((file, i) => i === idx ? { ...file, ...patch } : file));
  };
  const addTag = (t) => {
    const tag = t.trim();
    if (!tag) return;
    if (f.tags.includes(tag)) return;
    updateFile(active, { tags: [...f.tags, tag] });
    setTagInput('');
  };
  const removeTag = (t) => updateFile(active, { tags: f.tags.filter(x => x !== t) });
  const applyAllConf = (confId) => setFiles(prev => prev.map(file => ({ ...file, conf: confId })));

  const tagged = files.filter(x => x.conf).length;

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 60,
      background: 'var(--bg-overlay)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      animation: 'fadein 0.18s ease-out',
    }}>
      <div onClick={e => e.stopPropagation()} className="tagging-modal-card" style={{
        width: 1040, maxWidth: '94vw', height: 640, maxHeight: '92vh',
        background: 'var(--bg-card)', borderRadius: 18,
        boxShadow: 'var(--shadow-lg), 0 0 0 1px var(--line)',
        animation: 'rise 0.22s ease-out',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        {/* Header */}
        <div className="tagging-modal-header">
          <div>
            <h2 className="serif" style={{ fontSize: 18, fontWeight: 500, margin: 0, letterSpacing: '-0.01em' }}>{editMode ? 'Edit visibility & tags' : 'Tag your files'}</h2>
            <div style={{ fontSize: 13, color: 'var(--mute)', marginTop: 3 }}>
              {editMode
                ? 'Update who can see this file and its tags'
                : `${files.length} files · pick visibility and add tags · ${tagged}/${files.length} ready`}
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 8, background: 'transparent', border: 'none',
            cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--mute)',
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Body */}
        <div className="tagging-modal-body">
          {/* LEFT — file queue */}
          <div className="tagging-modal-left">
            <div className="tagging-modal-left-header">
              <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--mute)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Files</span>
              <span style={{ fontSize: 11, color: 'var(--mute)' }}>{active + 1} / {files.length}</span>
            </div>
            <div className="tagging-modal-left-list">
              {files.map((file, i) => {
                const isActive = i === active;
                return (
                  <div key={file.id} onClick={() => setActive(i)} className="tagging-file-item" style={{
                    background: isActive ? 'var(--bg-card)' : 'transparent',
                    borderColor: isActive ? 'var(--maroon-20)' : 'transparent',
                    boxShadow: isActive ? '0 2px 8px rgba(60,30,20,0.06)' : 'none',
                  }}>
                    <FileBadge ext={file.ext} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)',
                                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{file.name}</div>
                      <div style={{ fontSize: 10, color: 'var(--mute)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span>{file.size}</span>
                        {file.conf && (
                          <span
                            className={`conf ${file.conf}`}
                            style={{ padding: '1px 5px', fontSize: 9 }}
                          >
                            {CONF_LABELS[file.conf] || file.conf}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* RIGHT — tag panel */}
          <div className="tagging-modal-right">
            <div className="tagging-modal-right-content">
              {/* File header */}
              <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <FileBadge ext={f.ext} size="lg" />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontSize: 18, fontWeight: 600, color: 'var(--ink)',
                    overflowWrap: 'break-word', wordBreak: 'break-word',
                  }}>{f.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--mute)', marginTop: 4, display: 'flex', gap: 10 }}>
                    <span>{f.size}</span>
                    {f.pages > 0 && <span>· {f.pages} pages</span>}
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--gold)', fontWeight: 600 }}>
                      <svg width="10" height="10" viewBox="0 0 10 10" fill="currentColor"><path d="M5 1l1.18 2.4L8.83 3.78l-1.92 1.87.45 2.65L5 7.05 2.64 8.3l.45-2.65L1.17 3.78l2.65-.38L5 1z"/></svg>
                      Suggested: {CONF_LABELS[f.suggest] || f.suggest}
                    </span>
                  </div>
                </div>
              </div>

              {/* Visibility */}
              <div>
                <div style={sectionLabel}>
                  Visibility
                  <button onClick={() => applyAllConf(f.conf)} style={miniBtn}>Apply to all</button>
                </div>
                <div className="tagging-visibility-grid">
                  {CONF_OPTIONS.map(opt => {
                    const sel = f.conf === opt.id;
                    return (
                      <button key={opt.id} onClick={() => updateFile(active, { conf: opt.id })} style={{
                        padding: '10px 12px', borderRadius: 10, textAlign: 'left',
                        background: sel ? 'var(--ink)' : 'var(--bg-card)',
                        color: sel ? 'var(--bg-card)' : 'var(--ink)',
                        border: sel ? '1px solid var(--ink)' : '1px solid var(--line-2)',
                        cursor: 'pointer', fontFamily: 'inherit',
                        display: 'flex', flexDirection: 'column', gap: 4,
                        transition: 'all 0.12s',
                      }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                          <span style={{ fontSize: 13, fontWeight: 600 }}>{opt.label}</span>
                          {sel && (
                            <svg width="12" height="12" viewBox="0 0 12 12">
                              <path d="M2 6.5l2.5 2.5L10 3.5" stroke="white" fill="none" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                            </svg>
                          )}
                        </div>
                        <span style={{ fontSize: 11, opacity: sel ? 0.75 : 0.55 }}>{opt.desc}</span>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Tags */}
              <div>
                <div style={sectionLabel}>Tags</div>
                <div style={{
                  padding: '8px 10px', borderRadius: 10,
                  border: '1px solid var(--line-2)', background: 'var(--bg-card)',
                  display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center',
                  minHeight: 44,
                }}>
                  {f.tags.map(t => (
                    <span key={t} style={chipTagStyle}>
                      {t}
                      <button onClick={() => removeTag(t)} style={chipRemoveBtn}>
                        <svg width="9" height="9" viewBox="0 0 9 9"><path d="M2 2l5 5M7 2L2 7" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
                      </button>
                    </span>
                  ))}
                  <input
                    value={tagInput}
                    onChange={e => setTagInput(e.target.value)}
                    onKeyDown={e => {
                      if (e.key === 'Enter') { e.preventDefault(); addTag(tagInput); }
                      if (e.key === 'Backspace' && !tagInput && f.tags.length > 0) removeTag(f.tags[f.tags.length - 1]);
                    }}
                    placeholder={f.tags.length === 0 ? 'Add a tag…' : ''}
                    style={{
                      flex: 1, minWidth: 100, border: 'none', outline: 'none',
                      fontSize: 13, fontFamily: 'inherit', color: 'var(--ink)', background: 'transparent',
                      padding: '4px 2px',
                    }}
                  />
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 10 }}>
                  <span style={{ fontSize: 11, color: 'var(--mute)', padding: '4px 4px 4px 0' }}>Suggested:</span>
                  {SUGGESTED_TAGS.filter(t => !f.tags.includes(t)).slice(0, 7).map(t => (
                    <button key={t} onClick={() => addTag(t)} style={suggestedTagBtn}>+ {t}</button>
                  ))}
                </div>
              </div>

              <div style={{ flex: 1 }} />

              {/* Footer banner */}
              <div style={{
                padding: '10px 12px', borderRadius: 9,
                background: 'var(--maroon-wash)', border: '1px solid var(--maroon-10)',
                fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.5,
              }}>
                <strong style={{ color: 'var(--maroon)' }}>Tip:</strong> {' '}
                Use <kbd style={kbdStyle}>↑</kbd> <kbd style={kbdStyle}>↓</kbd> to move between files, <kbd style={kbdStyle}>Enter</kbd> to add a tag.
              </div>
            </div>

            {/* Footer */}
            <div className="tagging-modal-footer">
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <button onClick={() => setActive(Math.max(0, active - 1))} disabled={active === 0} style={navBtn}>← Prev</button>
                <button onClick={() => setActive(Math.min(files.length - 1, active + 1))} disabled={active === files.length - 1} style={navBtn}>Next →</button>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={onClose} className="btn-secondary" style={{ height: 36 }}>Cancel</button>
                <button onClick={() => onCommit(files)} className="btn-primary" style={{ height: 36 }}>
                  {editMode ? 'Save changes' : `Save ${files.length} files`}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const sectionLabel = {
  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
  fontSize: 10, fontWeight: 700, color: 'var(--mute)',
  letterSpacing: '0.08em', textTransform: 'uppercase',
  marginBottom: 8,
};
const miniBtn = {
  background: 'none', border: 'none', cursor: 'pointer',
  fontSize: 11, color: 'var(--maroon)', fontFamily: 'inherit', fontWeight: 600,
  textTransform: 'none', letterSpacing: 0,
};
const chipTagStyle = {
  display: 'inline-flex', alignItems: 'center', gap: 6,
  padding: '4px 4px 4px 10px', borderRadius: 6,
  background: 'var(--maroon-06)', color: 'var(--maroon)',
  fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
};
const chipRemoveBtn = {
  width: 16, height: 16, borderRadius: 4, border: 'none', cursor: 'pointer',
  background: 'transparent', color: 'var(--maroon)',
  display: 'grid', placeItems: 'center',
};
const suggestedTagBtn = {
  padding: '4px 10px', borderRadius: 999,
  background: 'var(--bg-card)', border: '1px dashed var(--line-2)',
  fontSize: 11, color: 'var(--mute)', fontFamily: 'inherit', cursor: 'pointer',
};
const navBtn = {
  height: 32, padding: '0 12px', borderRadius: 7,
  background: 'transparent', border: '1px solid var(--line-2)',
  fontSize: 12, fontFamily: 'inherit', color: 'var(--ink-2)', cursor: 'pointer',
};
const kbdStyle = {
  display: 'inline-block', padding: '1px 6px', borderRadius: 4,
  background: 'var(--bg-card)', border: '1px solid var(--line-2)',
  fontSize: 10, fontFamily: 'ui-monospace, monospace', color: 'var(--ink)',
};

Object.assign(window, {
  TaggingModal,
  SAMPLE_DROPPED,
  CONF_OPTIONS,
  CONF_LABELS,
  SUGGESTED_TAGS,
});
