// Primus IQ — Create Project Modal

const CreateProjectModal = ({ open, onClose, onCreate }) => {
  const [name, setName] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [practice, setPractice] = React.useState('');
  const [matches, setMatches] = React.useState([]);
  const [joining, setJoining] = React.useState({});  // { [projectId]: 'pending' | 'joined' | 'requested' }

  // Reset fields when the modal opens.
  React.useEffect(() => {
    if (!open) return;
    setName(''); setDesc(''); setPractice(''); setJoining({}); setMatches([]);
  }, [open]);

  // Debounced trigram (fuzzy) search for similar/duplicate projects as the name is typed.
  React.useEffect(() => {
    const q = name.trim();
    if (!open || q.length < 2) { setMatches([]); return; }
    const t = setTimeout(() => {
      PrimusAPI.listProjects(q).then(d => setMatches((d || []).slice(0, 10))).catch(() => setMatches([]));
    }, 250);
    return () => clearTimeout(t);
  }, [name, open]);

  if (!open) return null;

  const practices = [
    'Public Policy Realization',
    'Sector Potential Realization',
    'Impact Realization',
    'Economic Potential Realization',
    'Data & Digital Strategy',
    'Transaction Realization',
  ];

  const trimmed = name.trim().toLowerCase();
  // Exact (case-insensitive) duplicate is always among the trigram results (similarity 1.0).
  const exactDup = matches.find(p => (p.name || '').trim().toLowerCase() === trimmed);

  const handleJoin = async (p) => {
    setJoining(j => ({ ...j, [p.id]: 'pending' }));
    try {
      const res = await PrimusAPI.joinProject(p.id);
      setJoining(j => ({ ...j, [p.id]: res && res.status === 'approved' ? 'joined' : 'requested' }));
    } catch {
      setJoining(j => ({ ...j, [p.id]: undefined }));
    }
  };

  return (
    <ModalShell onClose={onClose} width={520} title="New project" subtitle="Create a private workspace for files, chat and instructions.">
      <div style={{ padding: '0 24px 24px', display: 'flex', flexDirection: 'column', gap: 18 }}>
        <Field label="Project name">
          <input value={name} onChange={e => setName(e.target.value)} placeholder="e.g. GCC Renewables Capex 2026" style={fieldInput}/>
        </Field>

        {matches.length > 0 && (
          <div style={{ padding: '10px 12px', borderRadius: 10, background: 'var(--bg-soft)', border: '1px solid var(--line)' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: exactDup ? 'var(--maroon)' : 'var(--mute)', marginBottom: 8, letterSpacing: '0.04em', textTransform: 'uppercase' }}>
              {exactDup ? 'This project already exists' : 'Similar existing projects — join instead?'}
            </div>
            {/* ~3 rows visible, the rest scroll */}
            <div className="pi-thin-scroll" style={{ maxHeight: 150, overflowY: 'auto' }}>
            {matches.map(p => {
              const isMember = !!p.membership;
              const st = joining[p.id];
              return (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
                  padding: '7px 0', borderTop: '1px solid var(--line)' }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--mute)' }}>{p.practice}</div>
                  </div>
                  {isMember ? (
                    <span style={{ fontSize: 11, color: 'var(--mute)', fontWeight: 600, flexShrink: 0 }}>Joined</span>
                  ) : st === 'joined' ? (
                    <span style={{ fontSize: 11, color: '#2E6F40', fontWeight: 600, flexShrink: 0 }}>Joined ✓</span>
                  ) : st === 'requested' ? (
                    <span style={{ fontSize: 11, color: '#2E6F40', fontWeight: 600, flexShrink: 0 }}>Requested ✓</span>
                  ) : (
                    <button onClick={() => handleJoin(p)} disabled={st === 'pending'} style={{
                      height: 26, padding: '0 12px', borderRadius: 7, flexShrink: 0,
                      background: 'var(--maroon)', color: 'white', border: 'none',
                      fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
                    }}>{st === 'pending' ? '…' : 'Join'}</button>
                  )}
                </div>
              );
            })}
            </div>
          </div>
        )}

        <Field label="Practice">
          <select value={practice} onChange={e => setPractice(e.target.value)} style={fieldInput}>
            <option value="">Select a practice</option>
            {practices.map(p => <option key={p} value={p}>{p}</option>)}
          </select>
        </Field>
        <Field label="Description" hint={`Optional. Visible to project members. ${desc.length}/200`}>
          <textarea value={desc} onChange={e => setDesc(e.target.value.slice(0, 200))} maxLength={200} placeholder="What is this project about?" rows={3}
            style={{ ...fieldInput, height: 'auto', padding: '12px 14px', resize: 'none' }}/>
        </Field>
        {exactDup && (
          <div style={{ fontSize: 11.5, color: 'var(--maroon)', marginTop: -8 }}>
            A project named “{exactDup.name}” already exists — join it above instead of creating a duplicate.
          </div>
        )}
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
          <button className="btn-secondary" onClick={onClose}>Cancel</button>
          <button className="btn-primary" onClick={() => { onCreate({ name, desc, practice }); onClose(); }} disabled={!name.trim() || !!exactDup}>Create project</button>
        </div>
      </div>
    </ModalShell>
  );
};

Object.assign(window, {
  CreateProjectModal,
});
