/* ============================================================
   Operion WTT — Admin sections: Users & Roles, Settings
   ============================================================ */
(function () {
  const { useState } = React;
  const { Card, CardHead, Badge, Btn, Icon, Toggle, Sel, MetricRow } = window;
  const h = React.createElement;

  // ============================================================
  // UTENTI E RUOLI
  // ============================================================
  function Users() {
    const s = window.useStore();
    const { t, tl } = window.useApp();
    const roles = window.DATA.roles, perms = window.DATA.permissions, matrix = window.DATA.permMatrix, usr = window.DATA.users;
    const roleLabel = (id) => { const r = roles.find((x) => x.id === id); return r ? (r[s.lang] || r.it) : id; };

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Gestione utenti e ruoli con matrice dei permessi per ciascun profilo operativo.', en: 'User and role management with a permission matrix per operational profile.', es: 'Gestión de usuarios y roles.', fr: 'Gestion des utilisateurs et rôles.', de: 'Benutzer- und Rollenverwaltung.' })),

      h('div', { className: 'grid g2', style: { marginBottom: 'var(--gap)', gridTemplateColumns: '1.3fr 1fr' } },
        h(Card, { cls: 'flush' },
          h(CardHead, { bordered: true, icon: 'shield', title: tl({ it: 'Matrice permessi', en: 'Permission matrix', es: 'Matriz de permisos', fr: 'Matrice des autorisations', de: 'Berechtigungsmatrix' }) }),
          h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
            h('thead', null, h('tr', null,
              h('th', null, t('c.permissions')),
              roles.map((r) => h('th', { key: r.id, style: { textAlign: 'center', writingMode: 'horizontal-tb' } }, h('span', { title: r[s.lang] || r.it }, r.id.slice(0, 4).toUpperCase()))))),
            h('tbody', null, perms.map((p) => h('tr', { key: p.id },
              h('td', null, h('strong', null, p[s.lang] || p.it)),
              roles.map((r) => h('td', { key: r.id, style: { textAlign: 'center' } },
                matrix[r.id].includes(p.id)
                  ? h('span', { style: { color: 'var(--status-run)', display: 'inline-flex' } }, h(Icon, { name: 'check', size: 16 }))
                  : h('span', { style: { color: 'var(--gray-300)', display: 'inline-flex' } }, h(Icon, { name: 'x', size: 13 })))))))))),
        h(Card, { cls: 'flush' },
          h(CardHead, { bordered: true, icon: 'users', title: t('nav.users'), sub: usr.filter((u) => u.active).length + ' ' + tl({ it: 'attivi', en: 'active', es: 'activos', fr: 'actifs', de: 'aktiv' }) }),
          h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
            h('thead', null, h('tr', null, [t('c.user'), t('c.role'), t('c.status')].map((c, i) => h('th', { key: i }, c)))),
            h('tbody', null, usr.map((u, i) => h('tr', { key: i },
              h('td', null, h('div', { className: 'row', style: { gap: 9 } },
                h('span', { className: 'avatar', style: { width: 28, height: 28, fontSize: 11 } }, u.name.split(' ').map((x) => x[0]).join('')),
                h('div', null, h('strong', null, u.name), h('div', { className: 'muted', style: { fontSize: 11 } }, u.email)))),
              h('td', null, h(Badge, { status: 'info', label: roleLabel(u.role) })),
              h('td', null, h(Badge, { status: u.active ? 'run' : 'idle', label: u.active ? t('st.online') : t('st.off') }))))))))),

      h('div', { className: 'grid g4' },
        roles.map((r) => h(Card, { key: r.id, style: { padding: 16 } },
          h('div', { className: 'row', style: { gap: 8, marginBottom: 8 } },
            h('span', { style: { color: 'var(--jit-navy)' } }, h(Icon, { name: r.id === 'admin' ? 'shield' : r.id === 'readonly' ? 'eye' : 'users', size: 18 })),
            h('strong', { style: { fontSize: 14, color: 'var(--fg-1)' } }, r[s.lang] || r.it)),
          h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 5 } },
            matrix[r.id].slice(0, 6).map((pid) => { const p = perms.find((x) => x.id === pid); return h('span', { key: pid, className: 'chip', style: { fontSize: 11, padding: '2px 8px' } }, p[s.lang] || p.it); }),
            matrix[r.id].length > 6 && h('span', { className: 'chip', style: { fontSize: 11, padding: '2px 8px' } }, '+' + (matrix[r.id].length - 6)))))));
  }

  // ============================================================
  // IMPOSTAZIONI
  // ============================================================
  function Settings() {
    const s = window.useStore();
    const { t, tl, toast, lang, setLang } = window.useApp();
    const [tog, setTog] = useState({ plc: true, scada: true, autobackup: true, emailNotif: true, smsNotif: false, pushNotif: true, twoFactor: true });
    const flip = (k) => setTog((x) => ({ ...x, [k]: !x[k] }));

    const Group = ({ icon, title, children }) => h(Card, null, h(CardHead, { icon, title }), h('div', null, children));
    const Field = ({ label, children }) => h('div', { className: 'metric-row' }, h('span', { className: 'ml' }, label), h('span', null, children));

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Impostazioni tecniche dell\u2019impianto: soglie, limiti, connessioni, notifiche e sicurezza.', en: 'Plant technical settings: thresholds, limits, connections, notifications and security.', es: 'Configuración técnica de la planta.', fr: 'Paramètres techniques de la station.', de: 'Technische Anlageneinstellungen.' })),

      h('div', { className: 'grid g3' },
        h(Group, { icon: 'settings', title: tl({ it: 'Parametri generali', en: 'General parameters', es: 'Parámetros generales', fr: 'Paramètres généraux', de: 'Allgemeine Parameter' }) },
          h(Field, { label: tl({ it: 'Nome impianto', en: 'Plant name', es: 'Nombre planta', fr: 'Nom station', de: 'Anlagenname' }) }, h('span', { className: 'mono', style: { fontSize: 12, color: 'var(--fg-1)' } }, 'Valdera-01')),
          h(Field, { label: tl({ it: 'Capacità nominale', en: 'Nominal capacity', es: 'Capacidad nominal', fr: 'Capacité nominale', de: 'Nennkapazität' }) }, h('span', { className: 'mono', style: { fontSize: 12, color: 'var(--fg-1)' } }, '32.000 AE')),
          h(Field, { label: t('c.unit') }, h(Sel, { value: 'si', onChange: () => {}, options: [{ v: 'si', label: 'SI (m³, °C, bar)' }, { v: 'imp', label: 'Imperial' }] })),
          h(Field, { label: tl({ it: 'Lingua predefinita', en: 'Default language', es: 'Idioma', fr: 'Langue', de: 'Sprache' }) }, h(Sel, { value: lang, onChange: setLang, options: window.I18N.LANGS.map((l) => ({ v: l.code, label: l.label })) }))),

        h(Group, { icon: 'alert', title: t('m.thresholds') },
          h(Field, { label: 'pH ' + t('c.min') + '/' + t('c.max') }, h('span', { className: 'mono', style: { fontSize: 12 } }, '6.5 / 8.5')),
          h(Field, { label: t('p.turbidity') + ' max' }, h('span', { className: 'mono', style: { fontSize: 12 } }, '1.0 NTU')),
          h(Field, { label: t('p.do') + ' ' + t('c.min') }, h('span', { className: 'mono', style: { fontSize: 12 } }, '1.6 mg/L')),
          h(Field, { label: tl({ it: 'Tolleranza sensori', en: 'Sensor tolerance', es: 'Tolerancia', fr: 'Tolérance', de: 'Toleranz' }) }, h('span', { className: 'mono', style: { fontSize: 12 } }, '± 2%'))),

        h(Group, { icon: 'shield', title: t('m.dischargelimits') },
          h(Field, { label: 'COD' }, h('span', { className: 'mono', style: { fontSize: 12 } }, '125 mg/L')),
          h(Field, { label: 'BOD5' }, h('span', { className: 'mono', style: { fontSize: 12 } }, '25 mg/L')),
          h(Field, { label: 'TSS' }, h('span', { className: 'mono', style: { fontSize: 12 } }, '35 mg/L')),
          h(Field, { label: t('p.ptot') }, h('span', { className: 'mono', style: { fontSize: 12 } }, '2 mg/L'))),

        h(Group, { icon: 'cpu', title: tl({ it: 'Connessioni', en: 'Connections', es: 'Conexiones', fr: 'Connexions', de: 'Verbindungen' }) },
          h(Field, { label: tl({ it: 'Connessione PLC', en: 'PLC connection', es: 'Conexión PLC', fr: 'Connexion PLC', de: 'PLC-Verbindung' }) }, h(Toggle, { on: tog.plc, onChange: () => flip('plc') })),
          h(Field, { label: tl({ it: 'Connessione SCADA', en: 'SCADA connection', es: 'Conexión SCADA', fr: 'Connexion SCADA', de: 'SCADA-Verbindung' }) }, h(Toggle, { on: tog.scada, onChange: () => flip('scada') })),
          h(Field, { label: t('m.connection') }, h(Badge, { status: 'sim', label: t('st.sim') })),
          h(Field, { label: tl({ it: 'Indirizzo gateway', en: 'Gateway address', es: 'Gateway', fr: 'Passerelle', de: 'Gateway' }) }, h('span', { className: 'mono', style: { fontSize: 11 } }, '10.0.4.12:502'))),

        h(Group, { icon: 'bell', title: tl({ it: 'Notifiche', en: 'Notifications', es: 'Notificaciones', fr: 'Notifications', de: 'Benachrichtigungen' }) },
          h(Field, { label: 'Email' }, h(Toggle, { on: tog.emailNotif, onChange: () => flip('emailNotif') })),
          h(Field, { label: 'SMS' }, h(Toggle, { on: tog.smsNotif, onChange: () => flip('smsNotif') })),
          h(Field, { label: 'Push' }, h(Toggle, { on: tog.pushNotif, onChange: () => flip('pushNotif') })),
          h(Field, { label: tl({ it: 'Email destinatario', en: 'Recipient email', es: 'Email destino', fr: 'Email destinataire', de: 'Empfänger-E-Mail' }) }, h('span', { className: 'mono', style: { fontSize: 11 } }, 'op@valdera.it'))),

        h(Group, { icon: 'lock', title: tl({ it: 'Sicurezza & dati', en: 'Security & data', es: 'Seguridad y datos', fr: 'Sécurité & données', de: 'Sicherheit & Daten' }) },
          h(Field, { label: tl({ it: 'Backup automatico', en: 'Auto backup', es: 'Copia automática', fr: 'Sauvegarde auto', de: 'Auto-Backup' }) }, h(Toggle, { on: tog.autobackup, onChange: () => flip('autobackup') })),
          h(Field, { label: tl({ it: 'Autenticazione 2FA', en: '2FA authentication', es: 'Autenticación 2FA', fr: 'Authentification 2FA', de: '2FA-Authentifizierung' }) }, h(Toggle, { on: tog.twoFactor, onChange: () => flip('twoFactor') })),
          h('div', { className: 'row', style: { gap: 6, marginTop: 12 } },
            h(Btn, { variant: 'ghost', icon: 'download', sm: true, onClick: () => toast('run', t('a.backup'), '12.4 MB') }, t('a.backup')),
            h(Btn, { variant: 'ghost', icon: 'download', sm: true, onClick: () => toast('info', tl({ it: 'Esportazione dati', en: 'Data export', es: 'Exportar datos', fr: 'Export données', de: 'Datenexport' }), 'CSV') }, 'CSV')))),

      h('div', { className: 'row', style: { marginTop: 'var(--gap)', justifyContent: 'flex-end' } },
        h(Btn, { variant: 'accent', icon: 'check', onClick: () => toast('run', t('toast.saved'), '') }, t('a.save'))));
  }

  window.Sections = window.Sections || {};
  Object.assign(window.Sections, { Users, Settings });
})();
