// Primus IQ — Edit Project Modal

const EditProjectModal = ({ open, project, onClose, onSave }) => {
  const [name, setName] = React.useState('');
  const [practice, setPractice] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (open && project) {
      setName(project.name || '');
      setPractice(project.practice || '');
      setDesc(project.description || project.desc || '');
    }
  }, [open, project?.id]);

  if (!open) return null;

  const handleSave = async () => {
    if (!project?.id) return;
    setSaving(true);
    try {
      await PrimusAPI.updateProject(project.id, { name, practice, description: desc });
      if (onSave) onSave({ name, practice, description: desc });
      onClose();
    } catch (ex) {
      console.error('Edit project failed:', ex);
    } finally { setSaving(false); }
  };

  return (
    <ModalShell onClose={onClose} width={520} title="Edit project" subtitle="Update project name, practice or description.">
      <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="Project name" style={fieldInput}/>
        </Field>
        <Field label="Practice">
          <select value={practice} onChange={e => setPractice(e.target.value)} style={fieldInput}>
            {PRACTICES.map(p => <option key={p} value={p}>{p}</option>)}
          </select>
        </Field>
        <Field label="Description" hint={`Optional. ${desc.length}/200`}>
          <textarea value={desc} onChange={e => setDesc(e.target.value.slice(0, 200))} maxLength={200} rows={3}
            style={{ ...fieldInput, height: 'auto', padding: '12px 14px', resize: 'none' }}/>
        </Field>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 4 }}>
          <button className="btn-secondary" onClick={onClose}>Cancel</button>
          <button className="btn-primary" onClick={handleSave} disabled={!name || saving}>
            {saving ? 'Saving…' : 'Save changes'}
          </button>
        </div>
      </div>
    </ModalShell>
  );
};

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