/* global React */
// settings-modal-shared.jsx — Composant générique de personnalisation (Règle n°6)
//
// Usage :
//   <ModuleSettingsButton storageKey="ae_audit_settings" title="Personnalisation Audit"
//     defaults={{ unit: 'kWh', tva: 20 }}
//     sections={[
//       { title: 'Section A', fields: [
//         { key: 'tva', label: 'TVA (%)', type: 'number', min: 0, max: 30 },
//         { key: 'unit', label: 'Unité', type: 'select', options: [{value:'kWh',label:'kWh'},{value:'MWh',label:'MWh'}] },
//         { key: 'autoSave', label: 'Auto-save', type: 'checkbox' },
//         { key: 'note', label: 'Note', type: 'textarea', rows: 3 },
//       ]},
//     ]}
//   />
//
// Le composant gère : persistance localStorage, reset, save, badge confirmation.

(function () {
  const { useState } = React;

  function ModuleSettingsButton({ storageKey, title, defaults, sections, buttonLabel = '⚙️ Paramètres', buttonStyle }) {
    const [open, setOpen] = useState(false);
    const defaultBtnStyle = {
      padding: '6px 10px', fontSize: 12, background: 'var(--paper)',
      border: '1px solid var(--line-2)', borderRadius: 5, cursor: 'pointer', color: 'var(--ink-3)',
    };
    return (
      <>
        <button onClick={() => setOpen(true)} title={title} style={{ ...defaultBtnStyle, ...(buttonStyle || {}) }}>
          {buttonLabel}
        </button>
        {open && (
          <ModuleSettingsModal
            storageKey={storageKey}
            title={title}
            defaults={defaults}
            sections={sections}
            onClose={() => setOpen(false)}
          />
        )}
      </>
    );
  }

  function ModuleSettingsModal({ storageKey, title, defaults, sections, onClose }) {
    const [s, setS] = useState(() => {
      try { return { ...defaults, ...(JSON.parse(localStorage.getItem(storageKey)) || {}) }; }
      catch { return { ...defaults }; }
    });
    const [saved, setSaved] = useState(false);
    const upd = (k, v) => setS(p => ({ ...p, [k]: v }));
    const save = () => {
      localStorage.setItem(storageKey, JSON.stringify(s));
      setSaved(true);
      setTimeout(() => setSaved(false), 2000);
    };
    const reset = () => {
      if (confirm('Réinitialiser tous les paramètres ?')) setS({ ...defaults });
    };
    const inp = { width: '100%', padding: '6px 10px', fontSize: 12, border: '1px solid var(--line-2)', borderRadius: 4, background: 'var(--paper-2)', color: 'var(--ink)', boxSizing: 'border-box', fontFamily: 'inherit' };
    const lbl = { fontSize: 10, color: 'var(--ink-5)', textTransform: 'uppercase', letterSpacing: '.04em', fontWeight: 600, marginBottom: 4 };

    const renderField = (f) => {
      const v = s[f.key];
      if (f.type === 'checkbox') {
        return (
          <label key={f.key} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, marginBottom: 6 }}>
            <input type="checkbox" checked={!!v} onChange={e => upd(f.key, e.target.checked)} />
            {f.label}
          </label>
        );
      }
      if (f.type === 'textarea') {
        return (
          <div key={f.key} style={{ gridColumn: '1 / -1', marginBottom: 8 }}>
            <div style={lbl}>{f.label}</div>
            <textarea value={v || ''} onChange={e => upd(f.key, e.target.value)} rows={f.rows || 3} style={{ ...inp, resize: 'vertical' }} />
            {f.hint && <div style={{ fontSize: 10, color: 'var(--ink-5)', marginTop: 4 }}>{f.hint}</div>}
          </div>
        );
      }
      if (f.type === 'select') {
        return (
          <div key={f.key}>
            <div style={lbl}>{f.label}</div>
            <select value={v ?? ''} onChange={e => upd(f.key, e.target.value)} style={inp}>
              {(f.options || []).map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </div>
        );
      }
      // number / text par défaut
      return (
        <div key={f.key}>
          <div style={lbl}>{f.label}</div>
          <input
            type={f.type || 'text'}
            value={v ?? ''}
            onChange={e => upd(f.key, f.type === 'number' ? (parseFloat(e.target.value) || 0) : e.target.value)}
            min={f.min} max={f.max} step={f.step}
            style={inp}
          />
        </div>
      );
    };

    return (
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 9999,
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
      }}>
        <div onClick={e => e.stopPropagation()} style={{
          background: 'var(--paper)', borderRadius: 10, maxWidth: 720, width: '100%',
          maxHeight: '90vh', overflowY: 'auto', boxShadow: '0 8px 40px rgba(0,0,0,.3)',
        }}>
          <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ fontSize: 16, fontWeight: 700, flex: 1 }}>⚙️ {title}</div>
            <button onClick={onClose} style={{ padding: 4, fontSize: 16 }}>×</button>
          </div>
          <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 18 }}>
            {sections.map((sec, i) => {
              const cbFields = (sec.fields || []).filter(f => f.type === 'checkbox');
              const inputFields = (sec.fields || []).filter(f => f.type !== 'checkbox' && f.type !== 'textarea');
              const taFields = (sec.fields || []).filter(f => f.type === 'textarea');
              return (
                <div key={i}>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--ink-5)', textTransform: 'uppercase', letterSpacing: '.05em', fontWeight: 700, marginBottom: 8 }}>
                    {sec.title}
                  </div>
                  {sec.description && <div style={{ fontSize: 11, color: 'var(--ink-4)', marginBottom: 8 }}>{sec.description}</div>}
                  {inputFields.length > 0 && (
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10, marginBottom: cbFields.length || taFields.length ? 10 : 0 }}>
                      {inputFields.map(renderField)}
                    </div>
                  )}
                  {taFields.length > 0 && taFields.map(renderField)}
                  {cbFields.length > 0 && (
                    <div>{cbFields.map(renderField)}</div>
                  )}
                </div>
              );
            })}
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', paddingTop: 12, borderTop: '1px solid var(--hairline)' }}>
              <button onClick={reset} style={{ padding: '8px 14px', fontSize: 12, color: 'var(--ink-3)', background: 'var(--paper)', border: '1px solid var(--line-2)', borderRadius: 5, cursor: 'pointer' }}>↺ Réinitialiser</button>
              <button onClick={save} style={{ padding: '8px 18px', fontSize: 12, fontWeight: 600, color: 'var(--paper)', background: saved ? 'var(--signal-deep)' : 'var(--ink)', border: 'none', borderRadius: 5, cursor: 'pointer' }}>
                {saved ? '✓ Enregistré' : 'Enregistrer'}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // Helper utilitaire pour lire les settings depuis le code applicatif
  function getModuleSettings(storageKey, defaults = {}) {
    try { return { ...defaults, ...(JSON.parse(localStorage.getItem(storageKey)) || {}) }; }
    catch { return { ...defaults }; }
  }

  Object.assign(window, { ModuleSettingsButton, ModuleSettingsModal, getModuleSettings });
})();
