/* global React, Icon, Button, Overline, PickerTrigger, SlidePicker, Field, TextField, ContactsEditor */
// Schools.ArtemenkoCRM — Add / Edit lead (заявка). Compact slide-in drawer.

function AddLeadModal({ onClose, onCreate, onSave, lead, onNavSettings }) {
  const { DIRECTIONS, MANAGERS, CONTACT_TYPES } = window.CRM_DATA;
  const editing = !!lead;
  const [shown, setShown] = React.useState(false);
  const [picker, setPicker] = React.useState(null);
  const [pickerCloseReq, setPickerCloseReq] = React.useState(0);
  const openPicker = (cfg) => setPicker(cfg);
  const [touched, setTouched] = React.useState(false);

  // Migrate legacy single channel/contact into the multi-contact model.
  const seedContacts = lead
    ? (lead.contacts && lead.contacts.length
        ? lead.contacts.map(c => ({ ...c }))
        : (lead.contact && lead.contact !== '—' ? [{ type: lead.channel || 'phone', value: lead.contact }] : [{ type: 'phone', value: '+7 ' }]))
    : [{ type: 'phone', value: '+7 ' }];

  const [name, setName] = React.useState(lead ? lead.name : '');
  const [contacts, setContacts] = React.useState(seedContacts);
  const [goal, setGoal] = React.useState(lead && lead.goal && lead.goal !== '—' ? lead.goal : '');
  const [subjects, setSubjects] = React.useState(lead ? (lead.subjects && lead.subjects.length ? lead.subjects.slice() : (lead.subject ? [lead.subject] : [])) : []);
  const addSubject = (v) => { if (!v) return; if (!window.CRM_DATA.DIRECTIONS.includes(v)) window.CRM_DATA.DIRECTIONS.push(v); setSubjects(s => s.includes(v) ? s : [...s, v]); };
  const removeSubject = (v) => setSubjects(s => s.filter(x => x !== v));
  const [price, setPrice] = React.useState(lead && lead.price != null ? String(lead.price) : String(window.DEFAULT_LESSON_PRICE || 1800));
  // Оплата в заявке — всегда «за занятие» (форматы месяц/курс убраны, см. BACKLOG).
  const priceUnit = 'зан';
  const [manager, setManager] = React.useState(lead ? lead.manager : null);

  React.useEffect(() => { const t = setTimeout(() => setShown(true), 10); return () => clearTimeout(t); }, []);
  const close = () => { setShown(false); setTimeout(onClose, 200); };

  const cleanContacts = contacts.filter(c => (c.value || '').trim() && (c.value || '').trim() !== '+7');
  const contactsOk = cleanContacts.length > 0;
  const nameOk = name.trim().length > 0;

  const submit = () => {
    const first = cleanContacts[0] || { type: 'phone', value: '—' };
    const payload = {
      name: name.trim() || 'Без имени', contacts: cleanContacts,
      channel: first.type, contact: first.value, // keep legacy fields for the table
      goal: goal.trim() || '—', subject: subjects[0] || null, subjects: subjects.slice(),
      price: price ? parseInt(price.replace(/\D/g, ''), 10) : null,
      priceUnit: price ? priceUnit : null, manager,
    };
    if (editing) onSave({ ...lead, ...payload }); else onCreate(payload);
  };
  const finish = () => {
    if (!nameOk || !contactsOk) { setTouched(true); return; }
    setPicker(null); setShown(false); setTimeout(submit, 200);
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 50 }}>
      <div onClick={close} style={{ position: 'absolute', inset: 0, background: 'rgba(21,28,46,0.45)', backdropFilter: 'blur(2px)', opacity: shown ? 1 : 0, transition: 'opacity var(--dur) var(--ease)' }} />
      <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, display: 'flex' }}>
        <div style={{ position: 'relative', width: 0, zIndex: 0 }}>
          <SlidePicker cfg={picker} onClose={() => setPicker(null)} closeReq={pickerCloseReq} />
        </div>
        <aside style={{
          width: 420, maxWidth: '100vw', background: 'var(--bg-card)', boxShadow: 'var(--shadow-lg)', position: 'relative', zIndex: 2,
          display: 'flex', flexDirection: 'column', height: '100%',
          transform: shown ? 'translateX(0)' : 'translateX(100%)', transition: 'transform 280ms cubic-bezier(0.22, 1, 0.36, 1)',
        }}>
          {/* Header */}
          <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 40, height: 40, borderRadius: 'var(--radius-md)', background: 'var(--brand-soft)', color: 'var(--brand-ink)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <Icon name="inbox" size={20} />
            </span>
            <div style={{ flex: 1 }}>
              <h2 style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.3px', margin: 0, color: 'var(--text)' }}>{editing ? 'Редактировать заявку' : 'Новая заявка'}</h2>
              <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 1 }}>{editing ? `Заявка #${lead.id}` : 'Заявка с сайта или вручную'}</div>
            </div>
            <button onClick={close} title="Закрыть" style={{ width: 34, height: 34, borderRadius: 6, border: '1px solid var(--border)', background: 'var(--bg-card)', cursor: 'pointer', color: 'var(--text-secondary)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round"><path d="M9.2 9.2l5.6 5.6M14.8 9.2l-5.6 5.6"/></svg>
            </button>
          </div>

          {/* Body */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 16 }}>
            <Field label="Имя" required><TextField value={name} onChange={setName} placeholder="Имя или кто обратился" autoFocus /></Field>
            {touched && !nameOk && <div style={{ fontSize: 12, color: 'var(--coral)', marginTop: -8 }}>Укажите имя</div>}

            <div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 6 }}>
                <label style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)' }}>Контакты<span style={{ color: 'var(--coral)' }}> *</span></label>
                <span style={{ fontSize: 12, color: 'var(--text-dim)' }}>хотя бы один</span>
              </div>
              <ContactsEditor contacts={contacts} onChange={setContacts} openPicker={openPicker} />
              {touched && !contactsOk && <div style={{ fontSize: 12, color: 'var(--coral)', marginTop: 8 }}>Добавьте хотя бы один контакт</div>}
            </div>

            <Field label="Заметка"><TextField value={goal} onChange={setGoal} placeholder="Что важно помнить: запрос, договорённости, детали" /></Field>

            <div>
              <label style={{ display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 8 }}>Предметы</label>
              {subjects.length > 0 ? (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
                  {subjects.map(s => (
                    <span key={s} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 8px 5px 11px', borderRadius: 'var(--radius-pill)', background: 'var(--brand-soft)', color: 'var(--brand-ink)', fontSize: 13, fontWeight: 600 }}>
                      {s}
                      <button onClick={() => removeSubject(s)} title="Убрать" style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--brand-ink)', display: 'inline-flex', padding: 0, opacity: 0.7 }}
                        onMouseEnter={e => { e.currentTarget.style.opacity = 1; }} onMouseLeave={e => { e.currentTarget.style.opacity = 0.7; }}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M9.2 9.2l5.6 5.6M14.8 9.2l-5.6 5.6"/></svg>
                      </button>
                    </span>
                  ))}
                </div>
              ) : <div style={{ fontSize: 12.5, color: 'var(--text-dim)', marginBottom: 8 }}>Не выбраны</div>}
              <button onClick={() => openPicker({
                title: 'Добавить предмет', value: null,
                options: DIRECTIONS.filter(s => !subjects.includes(s)).map(s => ({ value: s, label: s })).concat([{ value: '__add', label: '+ Добавить предмет в настройках…' }]),
                allowCustom: true, customPlaceholder: 'Свой предмет (напр. Python, C++)',
                onPick: (v) => { if (v === '__add') { close(); if (onNavSettings) onNavSettings('staff-directions'); return; } addSubject(v); },
              })}
                style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '9px 12px', border: '1px dashed var(--border-strong)', borderRadius: 'var(--radius-sm)', background: 'var(--bg-card)', cursor: 'pointer', color: 'var(--brand-ink)', fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-sans)' }}>
                <Icon name="plus" size={15} />Добавить предмет
              </button>
              <div style={{ fontSize: 10.5, color: 'var(--text-dim)', marginTop: 6, lineHeight: 1.35 }}>Можно указать несколько — например, Python и C++.</div>
            </div>

            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 16 }}>
              <Overline>Ожидаемая стоимость</Overline>
              <div>
                <Field label="Сумма за занятие (₽)"><TextField value={price} onChange={v => setPrice(v.replace(/\D/g, ''))} placeholder={String(window.DEFAULT_LESSON_PRICE || 1800)} mono /></Field>
              </div>
            </div>

            <Field label="Менеджер">
              <PickerTrigger label={manager} placeholder="Не назначен" onClick={() => openPicker({
                title: 'Менеджер', value: manager, options: MANAGERS.map(m => ({ value: m, label: m })), onPick: setManager,
              })} />
            </Field>
          </div>

          {/* Footer */}
          <div style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
            <Button variant="ghost" onClick={close}>Отмена</Button>
            <Button variant="primary" icon={editing ? 'check' : 'add-student'} onClick={finish}>{editing ? 'Сохранить' : 'Создать заявку'}</Button>
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { AddLeadModal });
