/* ctor-questionnaire-sets.jsx — Tab «Наборы анкет» (QuestionnaireSet CRUD + defaults) · KSH-350 */
const { useState: qsUseState, useEffect: qsUseEffect } = React;

const QS_KIND_META = {
  measure_order: { label: 'Заказ на замер', icon: '📅' },
  measure_field: { label: 'Замер на объекте', icon: '📐' },
  client: { label: 'Клиентская анкета', icon: '👤' },
  dp_brief: { label: 'Бриф на ДП', icon: '🎨' },
};

const qsPanelShell = {
  background: 'var(--card)',
  borderRadius: 'var(--radius-md, 10px)',
  border: '1px solid var(--border-subtle)',
  overflow: 'hidden',
};

function QsChip({ on, label, onClick, disabled }) {
  return (
    <button type="button" onClick={onClick} disabled={disabled}
      style={{
        padding: '7px 12px', borderRadius: 980, border: '.5px solid ' + (on ? '#e8793a' : '#ece5da'),
        background: on ? '#fff0e6' : '#fff', color: on ? '#c2410c' : '#5c5249',
        font: 'inherit', fontSize: 12.5, fontWeight: 600, cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.55 : 1,
      }}>
      {label}
    </button>
  );
}

function QsTemplatePickers({ setDoc, onChange }) {
  const Q = window.QuestionnaireSetMock;
  if (!Q) return null;

  const togglePool = (poolKey, templateId) => {
    const arr = new Set(setDoc[poolKey] || []);
    if (arr.has(templateId)) arr.delete(templateId); else arr.add(templateId);
    onChange(Q.syncDefaults({ ...setDoc, [poolKey]: [...arr] }));
  };

  const toggleDefault = (templateId) => {
    const pool = new Set([
      ...(setDoc.measureOrderTemplates || []),
      ...(setDoc.measureFieldTemplates || []),
      ...(setDoc.clientFormTemplates || []),
      ...(setDoc.dpBriefTemplates || []),
    ]);
    if (!pool.has(templateId)) return;
    const defs = new Set(setDoc.defaults || []);
    if (defs.has(templateId)) defs.delete(templateId); else defs.add(templateId);
    onChange({ ...setDoc, defaults: [...defs] });
  };

  const poolAll = [
    ...(setDoc.measureOrderTemplates || []),
    ...(setDoc.measureFieldTemplates || []),
    ...(setDoc.clientFormTemplates || []),
    ...(setDoc.dpBriefTemplates || []),
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ fontSize: 12.5, color: '#8a817a', lineHeight: 1.45, padding: '0 2px' }}>
        Замеры и клиентские анкеты — по типу объекта. Брифы ДП привязываются в каждом шаблоне (поле «Типы объекта»).
      </div>
      {Q.KIND_POOLS.filter((sec) => sec.kind !== 'dp_brief').map((sec) => {
        const options = Q.templatesByKind(sec.kind);
        return (
          <div key={sec.key} style={{ padding: '14px 16px', background: '#fafafa', borderRadius: 12, border: '.5px solid #ece5da' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#1a1714', marginBottom: 8 }}>{sec.label}</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {options.map((tpl) => (
                <QsChip
                  key={tpl.id}
                  label={tpl.title}
                  on={(setDoc[sec.key] || []).includes(tpl.id)}
                  onClick={() => togglePool(sec.key, tpl.id)}
                />
              ))}
              {!options.length && <span style={{ fontSize: 12, color: '#a89e92' }}>Нет шаблонов этого типа</span>}
            </div>
          </div>
        );
      })}

      <div style={{ padding: '14px 16px', background: '#fff', borderRadius: 12, border: '.5px solid #e8793a55' }}>
        <div style={{ fontSize: 13, fontWeight: 800, color: '#c2410c', marginBottom: 4 }}>Дефолты · materialize в ЛК</div>
        <div style={{ fontSize: 12.5, color: '#8a817a', marginBottom: 10, lineHeight: 1.45 }}>
          Отмеченные формы создаются автоматически при выборе типа недвижимости в CRM.
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {poolAll.map((id) => {
            const tpl = Q.getTemplate(id);
            if (!tpl) return null;
            const meta = QS_KIND_META[tpl.kind] || {};
            return (
              <QsChip
                key={id}
                label={(meta.icon ? meta.icon + ' ' : '') + tpl.title}
                on={(setDoc.defaults || []).includes(id)}
                onClick={() => toggleDefault(id)}
              />
            );
          })}
          {!poolAll.length && <span style={{ fontSize: 12, color: '#a89e92' }}>Сначала выберите шаблоны в блоках выше</span>}
        </div>
      </div>
    </div>
  );
}

function QsSetEditor({ setDoc, onChange, onDelete, onDuplicate }) {
  return (
    <div style={{ ...qsPanelShell, padding: 0 }}>
      <div style={{ padding: '18px 22px', borderBottom: '.5px solid #f0ece5' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
            <span style={ctorStyles.fieldLabel}>Название набора</span>
            <input className="ctor-input" value={setDoc.label || ''} onChange={(e) => onChange({ ...setDoc, label: e.target.value })}
              placeholder="Жилая недвижимость" style={ctorStyles.input} />
          </label>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
            <span style={ctorStyles.fieldLabel}>propertyType (slug)</span>
            <input className="ctor-input" value={setDoc.propertyType || ''} readOnly style={{ ...ctorStyles.input, opacity: 0.75, background: '#f0ece5' }} />
          </label>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 14, marginTop: 12, alignItems: 'center' }}>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
            <input type="checkbox" checked={setDoc.active !== false} onChange={(e) => onChange({ ...setDoc, active: e.target.checked })} />
            Активен
          </label>
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, cursor: 'pointer' }}>
            <input type="checkbox" checked={setDoc.editableInDeal !== false} onChange={(e) => onChange({ ...setDoc, editableInDeal: e.target.checked })} />
            Менеджер может менять набор в сделке
          </label>
          <span style={{ fontSize: 12, color: '#8a817a', marginLeft: 'auto' }}>
            defaults: <strong>{(setDoc.defaults || []).length}</strong> · id: {setDoc.id}
          </span>
        </div>
      </div>
      <div style={{ padding: '18px 22px' }}>
        <QsTemplatePickers setDoc={setDoc} onChange={onChange} />
      </div>
      <div style={{ padding: '12px 22px 18px', borderTop: '.5px solid #f0ece5', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <button type="button" onClick={onDuplicate} style={ctorStyles.btnGhost}>{Icon.copy} Дублировать</button>
        <button type="button" onClick={onDelete} style={{ ...ctorStyles.btnGhost, color: '#f04e62', borderColor: '#fecaca' }}>{Icon.trash} Удалить набор</button>
      </div>
    </div>
  );
}

function QsModeSwitch({ mode, onChange, briefCount }) {
  const opts = [
    { v: 'briefs', label: 'Шаблоны брифов ДП', hint: briefCount + ' шабл. · заготовки в левой колонке' },
    { v: 'bind', label: 'Замеры и анкеты', hint: 'по типу объекта · жилая, дом, коммерция' },
  ];
  return (
    <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }} role="tablist" aria-label="Режим набора анкет">
      {opts.map((o) => {
        const on = mode === o.v;
        return (
          <button
            key={o.v}
            type="button"
            role="tab"
            aria-selected={on}
            onClick={() => onChange(o.v)}
            style={{
              textAlign: 'left',
              padding: '10px 14px',
              borderRadius: 11,
              cursor: 'pointer',
              font: 'inherit',
              border: '.5px solid ' + (on ? '#e8793a55' : '#ece5da'),
              background: on ? '#fff0e6' : '#fff',
              minWidth: 200,
            }}
          >
            <div style={{ fontSize: 13.5, fontWeight: 700, color: on ? '#c2410c' : '#1a1714' }}>{o.label}</div>
            <div style={{ fontSize: 11.5, color: '#8a817a', marginTop: 3 }}>{o.hint}</div>
          </button>
        );
      })}
    </div>
  );
}

function QuestionnaireSetsPanel({ dpBriefs, setDpBriefs }) {
  const Q = window.QuestionnaireSetMock;
  const [sets, setSets] = qsUseState(() => (Q ? Q.loadSetsObject() : {}));
  const keys = Object.keys(sets);
  const [activePt, setActivePt] = qsUseState(keys[0] || null);
  const [flash, setFlash] = qsUseState('');
  const [mode, setMode] = qsUseState(() => {
    try {
      const p = new URLSearchParams(window.location.search);
      if (p.get('mode') === 'briefs' || p.get('mode') === 'presets' || p.get('tab') === 'dpbriefs') return 'briefs';
    } catch (e) { /* ignore */ }
    return 'briefs';
  });
  const briefCount = (dpBriefs && dpBriefs.length) || (window.loadDpBriefs ? window.loadDpBriefs().length : 0);

  qsUseEffect(() => {
    const reload = () => { if (Q) setSets(Q.loadSetsObject()); };
    window.addEventListener('remontpro:questionnaire-sets-updated', reload);
    return () => window.removeEventListener('remontpro:questionnaire-sets-updated', reload);
  }, []);

  qsUseEffect(() => {
    if (activePt && sets[activePt]) return;
    const k = Object.keys(sets);
    if (k.length) setActivePt(k[0]);
  }, [sets, activePt]);

  if (!Q) {
    return <EmptyState icon="layers" title="QuestionnaireSetMock не загружен" text="Подключите lk/questionnaire-set-mock.js" />;
  }

  const persist = (nextSets) => {
    Q.saveSetsObject(nextSets);
    setSets({ ...nextSets });
  };

  const active = activePt ? sets[activePt] : null;

  const updateActive = (patch) => {
    if (!activePt) return;
    const next = Q.syncDefaults({ ...sets[activePt], ...patch });
    persist({ ...sets, [activePt]: next });
    setFlash('Сохранено · ' + (next.label || activePt));
    setTimeout(() => setFlash(''), 2000);
  };

  const addSet = () => {
    const created = Q.createSet({ label: 'Новый набор анкет' });
    const fresh = Q.loadSetsObject();
    persist(fresh);
    setActivePt(created.propertyType);
  };

  const delSet = () => {
    if (!activePt || !confirm('Удалить набор «' + (active && active.label) + '»?')) return;
    const next = { ...sets };
    delete next[activePt];
    Q.saveSetsObject(next);
    setSets(next);
    setActivePt(Object.keys(next)[0] || null);
  };

  const dupSet = () => {
    if (!activePt) return;
    const dup = Q.duplicateSet(activePt);
    if (!dup) return;
    const fresh = Q.loadSetsObject();
    persist(fresh);
    setActivePt(dup.propertyType);
  };

  const resetSeed = () => {
    if (!confirm('Сбросить все наборы анкет к заводским пресетам?')) return;
    const fresh = Q.resetSetsSeed();
    setSets(fresh);
    setActivePt(Object.keys(fresh)[0] || null);
    setFlash('Сброшено к seed');
    setTimeout(() => setFlash(''), 2000);
  };

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={ctorStyles.sectionLabel}>Наборы анкет · QuestionnaireSet</div>
          <div style={{ fontSize: 14, color: '#8a817a', marginTop: 6, maxWidth: 680, lineHeight: 1.45 }}>
            Брифы и заготовки полей — в левой колонке. Редактирование заготовки открывается в окне. Замеры и анкеты — во второй вкладке.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {mode === 'bind' && (
            <>
              <button type="button" onClick={resetSeed} style={ctorStyles.btnGhost}>Сброс seed</button>
              <button type="button" onClick={addSet} style={ctorStyles.btnPrimary}>{Icon.plus} Набор</button>
            </>
          )}
        </div>
      </div>

      <QsModeSwitch mode={mode} onChange={setMode} briefCount={briefCount} />

      {mode === 'briefs' && window.DpBriefsPanel && dpBriefs && setDpBriefs ? (
        <DpBriefsPanel briefs={dpBriefs} setBriefs={setDpBriefs} />
      ) : mode === 'briefs' ? (
        <div style={{ padding: 48, textAlign: 'center', color: '#a89e92', fontSize: 13.5 }}>
          Редактор брифов недоступен. Проверьте подключение ctor-dp-briefs.jsx.
        </div>
      ) : null}

      {mode === 'bind' && flash && (
        <div style={{ marginBottom: 12, padding: '10px 14px', borderRadius: 10, background: '#f0fdf4', border: '.5px solid #bbf7d0', fontSize: 13, color: '#166534' }}>
          {flash}
        </div>
      )}

      {mode === 'bind' && !keys.length ? (
        <EmptyState icon="layers" title="Нет наборов анкет"
          text="Создайте QuestionnaireSet для каждого типа недвижимости или сбросьте seed."
          action={<button onClick={addSet} style={ctorStyles.btnPrimary}>{Icon.plus} Создать набор</button>} />
      ) : mode === 'bind' ? (
        <div style={{ display: 'flex', gap: 22, alignItems: 'flex-start' }}>
          <div style={{ width: 280, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {keys.map((pt) => {
              const s = sets[pt];
              const on = pt === activePt;
              return (
                <button key={pt} type="button" onClick={() => setActivePt(pt)}
                  style={{
                    textAlign: 'left', padding: '12px 14px', borderRadius: 11, cursor: 'pointer', font: 'inherit',
                    border: '.5px solid ' + (on ? '#e8793a55' : '#ece5da'),
                    background: on ? '#fff0e6' : '#fff',
                  }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: '#1a1714' }}>{s.label || pt}</div>
                  <div style={{ fontSize: 11.5, color: '#8a817a', marginTop: 4 }}>
                    {s.active === false ? '· выкл' : '· активен'} · {(s.defaults || []).length} def · {pt}
                  </div>
                </button>
              );
            })}
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            {active
              ? <QsSetEditor setDoc={active} onChange={updateActive} onDelete={delSet} onDuplicate={dupSet} />
              : <div style={{ padding: 64, textAlign: 'center', color: '#a89e92' }}>Выберите набор</div>}
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { QuestionnaireSetsPanel });
