/* ctor-options.jsx — Tab «Опции» (CatalogOption: переключаемые чипы в калькуляторе) */
const { useState: oUseState } = React;

const OPTIONS_SEED = [
{ id: 'opt-1', name: 'Перепланировка', key: 'replanning', icon: '🔧', color: '#e8793a', byDefault: false, active: true },
{ id: 'opt-2', name: 'Вентиляция/кондиц.', key: 'ventilation', icon: '💨', color: '#0ea5e9', byDefault: false, active: true },
{ id: 'opt-3', name: 'Тёплый пол', key: 'warm-floor', icon: '🔥', color: '#f97316', byDefault: false, active: true },
{ id: 'opt-4', name: 'Умный дом', key: 'smart-home', icon: '🏠', color: '#8b5cf6', byDefault: false, active: true },
{ id: 'opt-5', name: 'Звукоизоляция', key: 'soundproofing', icon: '🔇', color: '#6366f1', byDefault: false, active: true },
{ id: 'opt-6', name: 'Окна', key: 'windows', icon: '🪟', color: '#38bdf8', byDefault: false, active: true },
{ id: 'opt-7', name: 'Электрика (базовая)', key: 'electrics-basic', icon: '⚡', color: '#eab308', byDefault: true, active: true },
{ id: 'opt-8', name: 'Отделка стен', key: 'wall-finishing', icon: '🎨', color: '#ec4899', byDefault: true, active: true },
{ id: 'opt-9', name: 'Полы', key: 'flooring', icon: '🪵', color: '#78716c', byDefault: true, active: true }];


const oLS = 'ctor_options_v1';
function loadOptions() {
  try {const r = localStorage.getItem(oLS);if (r) return JSON.parse(r);} catch (e) {}
  return OPTIONS_SEED.map((o) => ({ ...o }));
}
function saveOptions(opts) {try {localStorage.setItem(oLS, JSON.stringify(opts));} catch (e) {}}

function OptChipPreview({ name, active }) {
  return (
    <span className={'opt-chip' + (active ? ' on' : '')}>{name || 'Опция'}</span>
  );
}

function OToggle({ value, onChange }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={value}
      onClick={() => onChange(!value)}
      style={{ width: 34, height: 21, borderRadius: 12, background: value ? '#5aad6e' : '#e4ddd2', position: 'relative', transition: 'background .2s', cursor: 'pointer', flexShrink: 0, border: 'none', padding: 0 }}
    >
      <span style={{ width: 17, height: 17, borderRadius: '50%', background: '#fff', position: 'absolute', top: 2, left: value ? 15 : 2, transition: 'left .2s cubic-bezier(.32,.72,0,1)', boxShadow: '0 1px 2px rgba(0,0,0,.15)', pointerEvents: 'none' }} />
    </button>
  );
}

function EditDrawer({ opt, onSave, onClose }) {
  const [draft, setDraft] = oUseState(opt ? { ...opt } : { id: 'opt-' + Date.now(), name: '', key: '', icon: '✨', color: '#e8793a', byDefault: false, active: true });
  const p = (k, v) => setDraft((d) => ({ ...d, [k]: v }));
  const PALETTE = ['#e8793a', '#f97316', '#8b5cf6', '#ec4899', '#0ea5e9', '#eab308', '#5aad6e', '#f04e62', '#6366f1', '#78716c', '#38bdf8'];
  const ICONS = ['🔧', '💨', '🔥', '🏠', '🔇', '🪟', '⚡', '🎨', '🪵', '♻️', '🌡️', '🔌', '🚿', '🛗'];

  return (
    <InspectorDrawer
      title={opt ? 'Редактировать опцию' : 'Новая опция'}
      onClose={onClose}
      width={480}
      footer={
        <React.Fragment>
          <button type="button" onClick={onClose} style={ctorStyles.btnGhost}>Отмена</button>
          <button type="button" onClick={() => { onSave(draft); onClose(); }} disabled={!draft.name || !draft.key}
            style={{ ...ctorStyles.btnPrimary, opacity: !draft.name || !draft.key ? 0.45 : 1 }}>Сохранить</button>
        </React.Fragment>
      }
    >
      <InspectorSection title="Идентификация">
        <FText label="Название" value={draft.name} onChange={(v) => p('name', v)} placeholder="Тёплый пол" />
        <FText label="Ключ (key)" value={draft.key} onChange={(v) => p('key', v.toLowerCase().replace(/\s+/g, '-'))} placeholder="warm-floor" mono />
        <div style={insStyles.hint}>Используется в conditionKey и API сметы</div>
      </InspectorSection>

      <InspectorSection title="Оформление">
        <div>
          <div style={{ ...insStyles.label, marginBottom: 8 }}>Иконка</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {ICONS.map((ic) => (
              <button key={ic} type="button" onClick={() => p('icon', ic)} style={{ width: 36, height: 36, borderRadius: 9, fontSize: 18, border: draft.icon === ic ? '2px solid var(--primary)' : '1px solid var(--border-subtle)', background: draft.icon === ic ? 'color-mix(in srgb, var(--primary) 10%, var(--card))' : 'transparent', cursor: 'pointer' }}>{ic}</button>
            ))}
          </div>
        </div>
        <div>
          <div style={{ ...insStyles.label, marginBottom: 8 }}>Цвет чипа</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, alignItems: 'center' }}>
            {PALETTE.map((c) => (
              <button key={c} type="button" onClick={() => p('color', c)} aria-label={'Цвет ' + c} style={{ width: 28, height: 28, borderRadius: '50%', background: c, border: draft.color === c ? '2.5px solid var(--foreground)' : '2px solid transparent', cursor: 'pointer' }} />
            ))}
            <input type="text" value={draft.color} onChange={(e) => p('color', e.target.value)}
              style={{ ...insStyles.field, width: 90, fontSize: 12, fontFamily: 'monospace', padding: '5px 9px' }} aria-label="HEX цвета" />
          </div>
        </div>
        <div>
          <div style={{ ...insStyles.label, marginBottom: 8 }}>Превью в калькуляторе</div>
          <div className="opt-preview-chips" style={{ padding: '10px 12px', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md, 10px)' }}>
            <OptChipPreview name={draft.name} active={true} />
            <OptChipPreview name={draft.name} active={false} />
          </div>
          <div style={insStyles.hint}>Слева включена по умолчанию · справа выключена</div>
        </div>
      </InspectorSection>

      <InspectorSection title="Поведение">
        <FToggle label="Включена по умолчанию" value={draft.byDefault} onChange={(v) => p('byDefault', v)} hint="Активна в новой смете автоматически" />
        <FToggle label="Активна" value={draft.active} onChange={(v) => p('active', v)} hint="Неактивные не показываются в калькуляторе" />
      </InspectorSection>
    </InspectorDrawer>
  );
}

function OptionsPanel({ options, setOptions }) {
  const [editing, setEditing] = oUseState(null);
  const move = (id, dir) => setOptions((opts) => {
    const idx = opts.findIndex((o) => o.id === id);
    if (idx < 0) return opts;
    const next = [...opts];
    const swap = idx + dir;
    if (swap < 0 || swap >= next.length) return opts;
    [next[idx], next[swap]] = [next[swap], next[idx]];
    saveOptions(next);
    return next;
  });
  const save = (opt) => {
    setOptions((opts) => {
      const existing = opts.findIndex((o) => o.id === opt.id);
      const next = existing >= 0 ? opts.map((o) => o.id === opt.id ? opt : o) : [...opts, opt];
      saveOptions(next);
      return next;
    });
  };
  const del = (id) => {
    if (!confirm('Удалить опцию?')) return;
    setOptions((opts) => {const next = opts.filter((o) => o.id !== id);saveOptions(next);return next;});
  };

  return (
    <div className="opt-panel">
      <header className="opt-toolbar">
        <div>
          <h2 className="opt-heading">Опции</h2>
          <p className="opt-lead">Переключатели разделов сметы в калькуляторе.</p>
        </div>
        <button type="button" className="opt-add-btn" onClick={() => setEditing('new')}>+ Создать опцию</button>
      </header>

      {options.some((o) => o.active) && (
        <section className="opt-preview-block" aria-label="Превью чипов">
          <p className="opt-preview-label">В калькуляторе</p>
          <div className="opt-preview-chips">
            {options.filter((o) => o.active).map((o) => (
              <OptChipPreview key={o.id} name={o.name} active={o.byDefault} />
            ))}
          </div>
          <p className="opt-preview-hint">Заливка: включена по умолчанию в новой смете.</p>
        </section>
      )}

      <div className="opt-list">
        {options.map((opt, idx) => (
            <div key={opt.id} className={'opt-row' + (opt.active ? '' : ' is-off')}>
              <div className="opt-row-name" title={opt.name}>
                {opt.name}
                {opt.byDefault && <span className="opt-row-meta"> · по умолчанию</span>}
              </div>
              <code className="opt-row-key">{opt.key}</code>
              <div className="opt-row-toggles">
                <span className="opt-toggle-label">
                  <OToggle value={opt.byDefault} onChange={(v) => save({ ...opt, byDefault: v })} />
                  По умолч.
                </span>
                <span className="opt-toggle-label">
                  <OToggle value={opt.active} onChange={(v) => save({ ...opt, active: v })} />
                  Активна
                </span>
              </div>
              <div className="opt-row-actions">
                <button type="button" onClick={() => move(opt.id, -1)} disabled={idx === 0} title="Вверх" aria-label="Поднять">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true"><polyline points="18 15 12 9 6 15"></polyline></svg>
                </button>
                <button type="button" onClick={() => move(opt.id, 1)} disabled={idx === options.length - 1} title="Вниз" aria-label="Опустить">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>
                </button>
                <button type="button" onClick={() => setEditing(opt)} title="Редактировать" aria-label="Редактировать">
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                </button>
                <button type="button" className="is-del" onClick={() => del(opt.id)} title="Удалить" aria-label="Удалить">{Icon.x}</button>
              </div>
            </div>
          ))}
        {options.length === 0 && (
          <div className="opt-empty">
            <p className="opt-empty-title">Опций нет</p>
            <p className="opt-empty-hint">Добавьте переключатели для разделов сметы.</p>
          </div>
        )}
      </div>

      {editing && <EditDrawer opt={editing === 'new' ? null : editing} onSave={save} onClose={() => setEditing(null)} />}
    </div>
  );
}

Object.assign(window, { OptionsPanel, loadOptions, OPTIONS_SEED, OptChipPreview });
