/* ============================================================
   Operion WTT — Asset & lab sections
   Tanks, Pumps & Valves, Quality analysis, Chemical dosing
   ============================================================ */
(function () {
  const { useState } = React;
  const { Card, CardHead, Badge, SDot, Btn, Icon, TankLevel, ProgressBar, MetricRow, ModeSwitch, Toggle, Drawer, DList } = window;
  const h = React.createElement;
  const xl24 = ['00', '04', '08', '12', '16', '20', ''];

  // ============================================================
  // SERBATOI E VASCHE
  // ============================================================
  function Tanks() {
    const s = window.useStore();
    const { t, tl } = window.useApp();
    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Livelli, volumi e stato di serbatoi e vasche con allarmi di alto e basso livello.', en: 'Levels, volumes and status of tanks and basins with high/low-level alarms.', es: 'Niveles y estado de depósitos y tanques.', fr: 'Niveaux et état des réservoirs et bassins.', de: 'Füllstände und Status der Tanks und Becken.' })),
      h('div', { className: 'grid g4' },
        s.tanks.map((tk) => {
          const vol = Math.round((tk.lvl / 100) * tk.cap);
          const alarm = (tk.alarm === 'high' && tk.lvl > 85) || tk.lvl > 92 ? 'warn' : tk.lvl < 12 ? 'warn' : 'run';
          return h(Card, { key: tk.id, style: { padding: 16 } },
            h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 10 } },
              h('div', null, h('strong', { style: { fontSize: 14, color: 'var(--fg-1)' } }, tk[s.lang] || tk.it), h('div', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, tk.id)),
              h(SDot, { status: alarm })),
            h('div', { style: { display: 'flex', gap: 14, alignItems: 'center' } },
              h(TankLevel, { level: tk.lvl, alarm: tk.alarm, color: tk.line === 'waste' ? '#F2941F' : tk.line === 'sludge' ? '#8B6F47' : tk.line === 'chem' ? '#8B5CF6' : '#2E8BC0' }),
              h('div', { style: { flex: 1 } },
                h(MetricRow, { label: t('c.volume'), value: vol.toLocaleString(), unit: 'm³' }),
                h(MetricRow, { label: t('c.capacity'), value: tk.cap.toLocaleString(), unit: 'm³' }),
                h(MetricRow, { label: tl({ it: 'Agitatore', en: 'Agitator', es: 'Agitador', fr: 'Agitateur', de: 'Rührwerk' }), value: tk.agit ? h(Badge, { status: 'run', label: t('st.on') }) : h(Badge, { status: 'idle', label: t('st.off') }) }))),
            h('div', { style: { marginTop: 10 } },
              h(ProgressBar, { value: tk.lvl, color: alarm === 'warn' ? 'var(--status-warn)' : tk.line === 'waste' ? '#F2941F' : '#2E8BC0' }),
              h('div', { className: 'row', style: { justifyContent: 'space-between', marginTop: 6 } },
                h('span', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, t('c.level')),
                h('span', { className: 'mono', style: { fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' } }, tk.lvl + '%'))),
            (tk.alarm === 'high' && tk.lvl > 85) && h('div', { style: { marginTop: 8 } }, h(Badge, { status: 'warn', label: tl({ it: 'Allarme alto livello', en: 'High level alarm', es: 'Alarma nivel alto', fr: 'Alarme niveau haut', de: 'Hochstandalarm' }), pulse: true })));
        })));
  }

  // ============================================================
  // POMPE E VALVOLE
  // ============================================================
  function Pumps() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const [sel, setSel] = useState(null);

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Gestione elettromeccanica: comando e supervisione di pompe e valvole con modalità automatica/manuale.', en: 'Electromechanical management: command and supervision of pumps and valves in auto/manual mode.', es: 'Gestión electromecánica de bombas y válvulas.', fr: 'Gestion électromécanique des pompes et vannes.', de: 'Elektromechanische Verwaltung von Pumpen und Ventilen.' })),

      h(Card, { cls: 'flush', style: { marginBottom: 'var(--gap)' } },
        h(CardHead, { bordered: true, icon: 'pump', title: t('m.pumps'), sub: s.pumps.filter((p) => p.state === 'run').length + '/' + s.pumps.length + ' ' + t('st.run') }),
        h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
          h('thead', null, h('tr', null, [t('c.code'), t('c.component'), t('c.status'), t('c.mode'), t('c.runhours'), t('c.current_a'), t('c.flow'), ''].map((c, i) => h('th', { key: i, className: i >= 4 && i <= 6 ? 'num' : '' }, c)))),
          h('tbody', null, s.pumps.map((p) => h('tr', { key: p.id, className: 'clickable' },
            h('td', { className: 'mono', onClick: () => setSel(p) }, p.id),
            h('td', { onClick: () => setSel(p) }, h('strong', null, p[s.lang] || p.it)),
            h('td', null, h(Badge, { status: p.state })),
            h('td', null, h(Badge, { status: p.mode, label: t('st.' + p.mode) })),
            h('td', { className: 'num mono muted' }, p.hours.toLocaleString()),
            h('td', { className: 'num mono' }, p.amp.toFixed(1), ' A'),
            h('td', { className: 'num mono' }, p.flow, ' m³/h'),
            h('td', null, h('div', { className: 'row', style: { gap: 4, justifyContent: 'flex-end' } },
              p.state === 'fault'
                ? h(Btn, { variant: 'ghost', icon: 'reset', sm: true, onClick: () => { window.STORE.togglePump(p.id); toast('info', t('a.reset'), p.id); } }, t('a.reset'))
                : p.state === 'run'
                  ? h(Btn, { variant: 'alarm', icon: 'pause', sm: true, onClick: () => { window.STORE.togglePump(p.id); toast('warn', t('toast.pumpstop'), p.id); } }, t('a.stop'))
                  : h(Btn, { variant: 'run', icon: 'play', sm: true, onClick: () => { window.STORE.togglePump(p.id); toast('run', t('toast.pumpstart'), p.id); } }, t('a.start')))))))))),

      h('div', { className: 'grid g3' },
        s.valves.map((v) => h(ValveCard, { key: v.id, valve: v }))),

      sel && h(PumpDrawer, { pump: sel, onClose: () => setSel(null) }));
  }

  function ValveCard({ valve }) {
    const { t, tl, toast } = window.useApp();
    const s = window.useStore();
    const set = (o) => { window.STORE.setValve(valve.id, o); };
    return h(Card, { style: { padding: 16 } },
      h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 8 } },
        h('div', null, h('strong', { style: { fontSize: 14, color: 'var(--fg-1)' } }, valve[s.lang] || valve.it), h('div', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, valve.id)),
        h(Badge, { status: valve.state })),
      h('div', { className: 'row', style: { gap: 10, marginBottom: 8 } },
        h('span', { style: { color: valve.open > 0 ? '#23416A' : 'var(--fg-3)' } }, h(Icon, { name: 'valve', size: 26 })),
        h('div', { style: { flex: 1 } },
          h('div', { className: 'row', style: { justifyContent: 'space-between' } }, h('span', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, t('m.opening')), h('span', { className: 'mono', style: { fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' } }, valve.open + '%')),
          h('input', { type: 'range', min: 0, max: 100, value: valve.open, onChange: (e) => set(+e.target.value), style: { width: '100%', accentColor: '#23416A', marginTop: 4 } }))),
      h('div', { className: 'row', style: { gap: 6 } },
        h(Btn, { variant: 'ghost', sm: true, onClick: () => { set(100); toast('info', t('toast.valvecmd'), valve.id + ' · ' + t('st.open')); } }, t('st.open')),
        h(Btn, { variant: 'ghost', sm: true, onClick: () => { set(0); toast('info', t('toast.valvecmd'), valve.id + ' · ' + t('st.closed')); } }, t('st.closed')),
        h('span', { className: 'spacer' }),
        h('span', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, 'fb ' + valve.open + '%')));
  }

  function PumpDrawer({ pump, onClose }) {
    const { t, tl, toast } = window.useApp();
    const s = window.useStore();
    const p = s.pumps.find((x) => x.id === pump.id) || pump;
    return h(Drawer, { title: p[s.lang] || p.it, sub: p.id, icon: 'pump', status: p.state, onClose,
      footer: [
        h(Btn, { key: 1, variant: 'run', icon: 'play', sm: true, onClick: () => { window.STORE.setPumpState(p.id, 'run'); toast('run', t('toast.pumpstart'), p.id); } }, t('a.start')),
        h(Btn, { key: 2, variant: 'alarm', icon: 'pause', sm: true, onClick: () => { window.STORE.setPumpState(p.id, 'idle'); toast('warn', t('toast.pumpstop'), p.id); } }, t('a.stop')),
        h(Btn, { key: 3, variant: 'ghost', icon: 'reset', sm: true, onClick: () => toast('info', t('a.reset'), p.id) }, t('a.reset')),
      ] },
      h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 14 } },
        h('span', { style: { fontSize: 13, color: 'var(--fg-2)' } }, t('c.mode')),
        h(ModeSwitch, { mode: p.mode, onChange: (m) => window.STORE.setPumpMode(p.id, m) })),
      h(DList, { items: [
        [t('c.status'), h(Badge, { status: p.state })],
        [t('c.runhours'), p.hours.toLocaleString() + ' h'],
        [t('c.current_a'), p.amp.toFixed(1) + ' A'],
        [t('c.flow'), p.flow + ' m³/h'],
        [t('c.laststart'), '15/06 06:12'],
        [t('c.nextmaint'), '12/07/26'],
      ] }));
  }

  // ============================================================
  // ANALISI QUALITÀ ACQUA
  // ============================================================
  function Quality() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const streams = window.DATA.qualityStreams;
    const [stream, setStream] = useState('discharge');
    const vals = window.DATA.analysisFor(stream);
    const PARAMS = ['p.ph', 'p.turbidity', 'p.conductivity', 'p.cod', 'p.bod', 'p.tss', 'p.chlorine', 'p.do', 'p.nh4', 'p.ptot', 'p.hardness', 'p.nitrates', 'p.temp', 'p.bacteria'];

    const history = [
      { d: '15/06 08:00', conf: 'conform' }, { d: '14/06 08:00', conf: 'conform' }, { d: '13/06 08:00', conf: 'attention' },
      { d: '12/06 08:00', conf: 'conform' }, { d: '11/06 08:00', conf: 'conform' }, { d: '10/06 08:00', conf: 'conform' },
    ];

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Laboratorio e controllo qualità per i cinque flussi dell\u2019impianto, con storico, campionamenti e certificati.', en: 'Laboratory and quality control for the plant\u2019s five streams, with history, sampling and certificates.', es: 'Laboratorio y control de calidad.', fr: 'Laboratoire et contrôle qualité.', de: 'Labor und Qualitätskontrolle.' })),

      h('div', { className: 'toolbar' },
        h('div', { className: 'seg' }, streams.map((st) => h('button', { key: st.id, className: stream === st.id ? 'active' : '', onClick: () => setStream(st.id) }, window.DATA.streamLabel(st, s.lang)))),
        h('span', { className: 'spacer' }),
        h(Btn, { variant: 'ghost', icon: 'plus', sm: true, onClick: () => toast('info', t('a.new_analysis'), window.DATA.streamLabel(streams.find((x) => x.id === stream), s.lang)) }, t('a.new_analysis')),
        h(Btn, { variant: 'accent', icon: 'file', sm: true, onClick: () => toast('run', t('a.certificate'), 'PDF · ' + window.DATA.streamLabel(streams.find((x) => x.id === stream), s.lang)) }, t('a.certificate'))),

      h('div', { className: 'grid g2', style: { marginBottom: 'var(--gap)' } },
        h(Card, null,
          h(CardHead, { icon: 'flask', title: t('nav.quality') + ' · ' + window.DATA.streamLabel(streams.find((x) => x.id === stream), s.lang),
            right: h(Badge, { status: 'conform', label: t('st.conform') }) }),
          h('div', { className: 'grid g3', style: { gap: 10 } },
            PARAMS.map((pk) => { const v = vals[pk]; if (v === undefined) return null;
              return h('div', { key: pk, style: { background: 'var(--bg-sunken)', borderRadius: 'var(--r-md)', padding: '9px 11px' } },
                h('div', { style: { fontSize: 11, color: 'var(--fg-2)', fontWeight: 600 } }, t(pk)),
                h('span', { className: 'mono', style: { fontWeight: 600, color: v === '—' ? 'var(--fg-3)' : 'var(--fg-1)', fontSize: 14.5 } }, v)); }))),
        h('div', { className: 'stack' },
          h(Card, null,
            h(CardHead, { icon: 'clock', title: t('m.history') }),
            h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
              h('thead', null, h('tr', null, [t('c.datetime'), t('c.compliance')].map((c, i) => h('th', { key: i }, c)))),
              h('tbody', null, history.map((r, i) => h('tr', { key: i }, h('td', { className: 'mono' }, r.d), h('td', null, h(Badge, { status: r.conf })))))) )),
          h(Card, null,
            h(CardHead, { icon: 'calendar', title: t('m.scheduled') }),
            h(MetricRow, { label: tl({ it: 'Acqua potabile', en: 'Potable water', es: 'Agua potable', fr: 'Eau potable', de: 'Trinkwasser' }), value: tl({ it: 'Giornaliero', en: 'Daily', es: 'Diario', fr: 'Journalier', de: 'Täglich' }) }),
            h(MetricRow, { label: tl({ it: 'Scarico finale', en: 'Final discharge', es: 'Vertido', fr: 'Rejet', de: 'Einleitung' }), value: tl({ it: 'Settimanale', en: 'Weekly', es: 'Semanal', fr: 'Hebdo', de: 'Wöchentlich' }) }),
            h(MetricRow, { label: t('p.bacteria'), value: tl({ it: 'Mensile', en: 'Monthly', es: 'Mensual', fr: 'Mensuel', de: 'Monatlich' }) }),
            h(MetricRow, { label: t('m.labmanager'), value: 'Sara Conti' }))))
    );
  }

  // ============================================================
  // DOSAGGIO CHIMICI
  // ============================================================
  function Chemicals() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Gestione reagenti: livelli serbatoi, dosaggi, scorte e controlli delle pompe dosatrici.', en: 'Reagent management: tank levels, dosing, stock and dosing-pump controls.', es: 'Gestión de reactivos y dosificación.', fr: 'Gestion des réactifs et dosage.', de: 'Reagenzienverwaltung und Dosierung.' })),
      h('div', { className: 'grid g3' },
        s.chemicals.map((c) => h(ChemCard, { key: c.id, chem: c }))));
  }

  function ChemCard({ chem }) {
    const { t, tl, toast } = window.useApp();
    const s = window.useStore();
    const c = s.chemicals.find((x) => x.id === chem.id) || chem;
    const low = c.lvl <= c.minPct;
    const [dose, setDose] = useState(c.dose);
    return h(Card, { style: { padding: 16 } },
      h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 10 } },
        h('div', null, h('strong', { style: { fontSize: 14, color: 'var(--fg-1)' } }, c[s.lang] || c.it), h('div', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, c.id + ' · ' + c.tank)),
        low ? h(Badge, { status: 'warn', label: tl({ it: 'Scorta bassa', en: 'Low stock', es: 'Stock bajo', fr: 'Stock bas', de: 'Niedrig' }), pulse: true }) : h(Badge, { status: 'run', label: t('st.ok') })),
      h('div', { style: { display: 'flex', gap: 14, alignItems: 'center', marginBottom: 10 } },
        h(window.TankLevel, { level: c.lvl, w: 44, h: 76, alarm: 'low', color: '#8B5CF6' }),
        h('div', { style: { flex: 1 } },
          h(MetricRow, { label: t('c.qty'), value: c.qty.toLocaleString(), unit: 'L' }),
          h(MetricRow, { label: t('c.consumption') + ' ' + t('c.daily').toLowerCase(), value: c.daily, unit: c.unit.split('/')[0] }),
          h(MetricRow, { label: t('c.supplier'), value: h('span', { style: { fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 12 } }, c.supplier) }))),
      h('div', { style: { background: 'var(--bg-sunken)', borderRadius: 'var(--r-md)', padding: 10, marginBottom: 8 } },
        h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 4 } },
          h('span', { style: { fontSize: 11.5, color: 'var(--fg-2)', fontWeight: 600 } }, t('a.set_dose')),
          h('span', { className: 'mono', style: { fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' } }, dose.toFixed(1) + ' ' + c.unit)),
        h('input', { type: 'range', min: 0, max: 10, step: 0.1, value: dose, onChange: (e) => setDose(+e.target.value), style: { width: '100%', accentColor: '#8B5CF6' } })),
      h('div', { className: 'row', style: { gap: 6 } },
        h(window.Toggle, { on: c.pump, onChange: () => { window.STORE.toggleChemPump(c.id); toast(c.pump ? 'warn' : 'run', c.pump ? t('toast.pumpstop') : t('toast.pumpstart'), c.id); } }),
        h('span', { style: { fontSize: 12, color: 'var(--fg-2)', fontWeight: 600 } }, tl({ it: 'Pompa dosatrice', en: 'Dosing pump', es: 'Bomba dosificadora', fr: 'Pompe doseuse', de: 'Dosierpumpe' })),
        h('span', { className: 'spacer' }),
        h(Btn, { variant: 'ghost', sm: true, icon: 'check', onClick: () => { window.STORE.setChemDose(c.id, dose); toast('run', t('toast.dosset'), c.id + ' · ' + dose.toFixed(1) + ' ' + c.unit); } }, t('a.apply'))));
  }

  window.Sections = window.Sections || {};
  Object.assign(window.Sections, { Tanks, Pumps, Quality, Chemicals });
})();
