/* ============================================================
   Operion WTT — Water process sections
   Primary water, Potabilization, Wastewater, Sludge line
   ============================================================ */
(function () {
  const { useState } = React;
  const { Card, CardHead, KPI, Badge, SDot, Btn, Icon, Gauge, Donut, ProgressBar, MetricRow } = window;
  const h = React.createElement;
  const xl24 = ['00', '04', '08', '12', '16', '20', ''];

  // shared: status->trend arrow
  function TrendArrow({ dir }) {
    if (dir === 'down') return h('span', { className: 'txt-run', title: 'down' }, h(Icon, { name: 'arrowDown', size: 14 }));
    if (dir === 'up') return h('span', { className: 'txt-alarm' }, h(Icon, { name: 'arrowUp', size: 14 }));
    return h('span', { className: 'muted' }, '—');
  }

  // ============================================================
  // ACQUE PRIMARIE
  // ============================================================
  function Primary() {
    const s = window.useStore();
    const { t, tl } = window.useApp();
    const sens = s.primarySensors;
    const get = (id) => sens.find((x) => x.id === id) || { val: 0 };

    const sources = [
      { it: 'Pozzo', en: 'Well', es: 'Pozo', fr: 'Puits', de: 'Brunnen', active: true },
      { it: 'Fiume', en: 'River', es: 'Río', fr: 'Rivière', de: 'Fluss', active: true },
      { it: 'Lago', en: 'Lake', es: 'Lago', fr: 'Lac', de: 'See', active: false },
      { it: 'Rete', en: 'Mains', es: 'Red', fr: 'Réseau', de: 'Netz', active: false },
      { it: 'Accumulo ind.', en: 'Ind. storage', es: 'Acumulación', fr: 'Stockage', de: 'Speicher', active: true },
    ];

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Gestione e monitoraggio delle acque grezze in ingresso: fonti, captazione, prefiltrazione e parametri di qualità.', en: 'Management and monitoring of raw water intake: sources, captation, pre-filtration and quality parameters.', es: 'Gestión y monitoreo del agua bruta de entrada.', fr: 'Gestion et suivi des eaux brutes en entrée.', de: 'Verwaltung und Überwachung des Rohwasserzulaufs.' })),

      h('div', { className: 'grid g4', style: { marginBottom: 'var(--gap)' } },
        h(Card, { cls: 'col-2' },
          h(CardHead, { icon: 'mapPin', title: t('m.source') }),
          h('div', { className: 'row wrap', style: { gap: 8 } },
            sources.map((src, i) => h('div', { key: i, className: 'chip', style: src.active ? { background: 'var(--status-run-bg)', color: 'var(--status-run)', borderColor: 'transparent' } : null },
              h(SDot, { status: src.active ? 'run' : 'idle' }), tl(src)))),
          h('div', { style: { marginTop: 16, display: 'flex', gap: 24, flexWrap: 'wrap' } },
            h('div', null, h('div', { className: 'kpi-label' }, t('c.flow')), h('div', { className: 'kpi-val', style: { fontSize: 24 } }, get('FI-105').val.toFixed(0), h('span', { className: 'unit' }, 'm³/h'))),
            h('div', null, h('div', { className: 'kpi-label' }, t('c.pressure')), h('div', { className: 'kpi-val', style: { fontSize: 24 } }, get('PI-106').val.toFixed(1), h('span', { className: 'unit' }, 'bar'))),
            h('div', null, h('div', { className: 'kpi-label' }, t('c.level') + ' ' + tl({ it: 'captazione', en: 'intake', es: 'captación', fr: 'captage', de: 'Entnahme' })), h('div', { className: 'kpi-val', style: { fontSize: 24 } }, get('LI-107').val.toFixed(0), h('span', { className: 'unit' }, '%'))))),
        h(Card, { style: { textAlign: 'center' } }, h(CardHead, { icon: 'gauge', title: t('p.turbidity') }),
          h(Gauge, { value: get('AI-102').val, max: 40, unit: 'NTU', thresholds: [0.5, 0.8], color: '#2E8BC0' })),
        h(Card, { style: { textAlign: 'center' } }, h(CardHead, { icon: 'activity', title: t('p.ph') }),
          h(Gauge, { value: get('AI-101').val, min: 6, max: 9, unit: 'pH', color: '#1E9E5A' }))),

      h('div', { className: 'grid g4', style: { marginBottom: 'var(--gap)' } },
        h(GaugeCard, { title: t('p.conductivity'), value: get('AI-103').val, max: 1200, unit: 'µS/cm', color: '#8B5CF6' }),
        h(GaugeCard, { title: t('p.temp'), value: get('TI-104').val, max: 30, unit: '°C', color: '#F2941F' }),
        h(GaugeCard, { title: t('p.chlorine'), value: get('AI-108').val, max: 0.6, unit: 'mg/L', color: '#2E8BC0' }),
        h(Card, null, h(CardHead, { icon: 'pump', title: tl({ it: 'Stato apparecchiature', en: 'Equipment status', es: 'Estado equipos', fr: 'État équipements', de: 'Anlagenstatus' }) }),
          h('div', null,
            [['pump', tl({ it: 'Pompe captazione', en: 'Intake pumps', es: 'Bombas', fr: 'Pompes', de: 'Pumpen' }), 'run'], ['filter', tl({ it: 'Griglie', en: 'Screens', es: 'Rejas', fr: 'Grilles', de: 'Rechen' }), 'run'], ['grid', tl({ it: 'Prefiltri', en: 'Pre-filters', es: 'Prefiltros', fr: 'Préfiltres', de: 'Vorfilter' }), 'run']].map((r, i) =>
              h('div', { key: i, className: 'metric-row' },
                h('span', { className: 'ml', style: { display: 'flex', alignItems: 'center', gap: 8 } }, h('span', { style: { color: 'var(--jit-navy)' } }, h(Icon, { name: r[0], size: 16 })), r[1]),
                h(Badge, { status: r[2] })))))),

      h(Card, { cls: 'flush' },
        h(CardHead, { bordered: true, icon: 'cpu', title: tl({ it: 'Tabella sensori', en: 'Sensor table', es: 'Tabla de sensores', fr: 'Tableau capteurs', de: 'Sensortabelle' }), sub: sens.length + ' ' + tl({ it: 'sensori', en: 'sensors', es: 'sensores', fr: 'capteurs', de: 'Sensoren' }),
          right: h(Badge, { status: 'online', label: t('st.online') }) }),
        h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
          h('thead', null, h('tr', null, ['c.sensor', 'c.param', 'c.position', 'c.current', 'c.unit', 'c.min', 'c.max', 'c.status', 'c.updated'].map((k, i) =>
            h('th', { key: i, className: i === 3 ? 'num' : '' }, t(k))))),
          h('tbody', null, sens.map((sn) => {
            const ok = sn.val >= sn.min && sn.val <= sn.max;
            return h('tr', { key: sn.id },
              h('td', { className: 'mono' }, sn.id),
              h('td', null, h('strong', null, t(sn.key))),
              h('td', null, sn.pos),
              h('td', { className: 'num mono' }, sn.val.toFixed(sn.dec)),
              h('td', { className: 'muted' }, sn.unit || '—'),
              h('td', { className: 'num mono muted' }, sn.min),
              h('td', { className: 'num mono muted' }, sn.max),
              h('td', null, h(Badge, { status: ok ? 'run' : 'warn', label: ok ? t('st.ok') : t('st.attention') })),
              h('td', { className: 'mono muted', style: { fontSize: 11 } }, fmtClock(s.clock)));
          }))))));
  }

  function GaugeCard({ title, value, max, min, unit, color }) {
    return h(Card, { style: { textAlign: 'center' } }, h(CardHead, { icon: 'gauge', title }),
      h(Gauge, { value, max, min, unit, color }));
  }
  function fmtClock(d) { return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0') + ':' + String(d.getSeconds()).padStart(2, '0'); }

  // ============================================================
  // POTABILIZZAZIONE
  // ============================================================
  function Potable() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const stages = s.potableStages;

    const quality = [
      { k: 'p.ph', v: 7.6, u: '', ok: true }, { k: 'p.turbidity', v: 0.4, u: 'NTU', ok: true },
      { k: 'p.conductivity', v: 380, u: 'µS/cm', ok: true }, { k: 'p.chlorine', v: 0.32, u: 'mg/L', ok: true },
      { k: 'p.bacteria', v: '0 UFC', u: '', ok: true }, { k: 'p.hardness', v: 18, u: '°F', ok: true },
      { k: 'p.nitrates', v: 6, u: 'mg/L', ok: true }, { k: 'p.iron', v: 0.04, u: 'mg/L', ok: true },
      { k: 'p.manganese', v: 0.01, u: 'mg/L', ok: true },
    ];

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Linea di potabilizzazione: ciascuna fase mostra stato, portata, efficienza, pressioni e qualità.', en: 'Potabilization line: each stage shows status, flow, efficiency, pressures and quality.', es: 'Línea de potabilización con estado de cada etapa.', fr: 'Filière de potabilisation, état par étape.', de: 'Trinkwasserlinie mit Status je Stufe.' })),
      h('div', { className: 'grid g3', style: { marginBottom: 'var(--gap)' } },
        stages.map((st) => h(Card, { key: st.id, style: { padding: 16 } },
          h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 10 } },
            h('div', { className: 'row', style: { gap: 8 } }, h(SDot, { status: st.state }), h('strong', { style: { fontSize: 14, color: 'var(--fg-1)' } }, st[s.lang] || st.it)),
            h('span', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, st.id)),
          h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 12 } },
            h(Badge, { status: st.state }), h(Badge, { status: st.mode, label: t('st.' + st.mode) })),
          h('div', { style: { display: 'flex', alignItems: 'center', gap: 14 } },
            h(Donut, { value: st.eff, size: 64, stroke: 8, color: st.state === 'warn' ? '#E8A317' : '#1E9E5A' }),
            h('div', { style: { flex: 1 } },
              h(MetricRow, { label: t('c.flow'), value: st.flow, unit: 'm³/h' }),
              h(MetricRow, { label: 'Δp', value: (st.pin - st.pout).toFixed(1), unit: 'bar' }),
              h(MetricRow, { label: t('p.turbidity') + ' out', value: st.qout, unit: 'NTU' }))))) ),

      h('div', { className: 'grid g2' },
        h(Card, null,
          h(CardHead, { icon: 'droplets', title: tl({ it: 'Qualità acqua potabilizzata', en: 'Potabilized water quality', es: 'Calidad del agua potable', fr: 'Qualité eau potable', de: 'Trinkwasserqualität' }),
            right: h(Badge, { status: 'conform', label: t('st.conform') }) }),
          h('div', { className: 'grid g3', style: { gap: 10 } },
            quality.map((q, i) => h('div', { key: i, style: { background: 'var(--bg-sunken)', borderRadius: 'var(--r-md)', padding: '10px 12px' } },
              h('div', { style: { fontSize: 11.5, color: 'var(--fg-2)', fontWeight: 600 } }, t(q.k)),
              h('div', { className: 'row', style: { justifyContent: 'space-between', marginTop: 4 } },
                h('span', { className: 'mono', style: { fontWeight: 600, color: 'var(--fg-1)', fontSize: 15 } }, q.v, q.u && h('span', { style: { fontSize: 11, color: 'var(--fg-3)', marginLeft: 2 } }, q.u)),
                h(SDot, { status: q.ok ? 'run' : 'warn' })))))),
        h(Card, null,
          h(CardHead, { icon: 'chart', title: tl({ it: 'Rendimento per fase', en: 'Stage efficiency', es: 'Rendimiento por etapa', fr: 'Rendement par étape', de: 'Effizienz je Stufe' }), sub: '%' }),
          h(window.BarChart, { data: stages.map((x) => x.eff), labels: stages.map((x) => x.id), horizontal: true, h: 300, color: '#23416A', fixedMax: 100 }),
          h('div', { className: 'row', style: { marginTop: 12, gap: 8 } },
            h(Btn, { variant: 'accent', icon: 'check', sm: true, onClick: () => toast('run', t('toast.cyclecomplete'), 'Potabilizzazione') }, t('toast.cyclecomplete')))))
    );
  }

  // ============================================================
  // TRATTAMENTO REFLUO
  // ============================================================
  function Waste() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const steps = s.wasteSteps;
    const params = s.wasteParams;
    const L = s.live;

    const cards = [
      { ic: 'recycle', k: 'k.flowwaste', v: L.flowWaste, u: 'm³/h', st: 'run' },
      { ic: 'flask', k: 'p.cod', v: L.codOut, u: 'mg/L', st: L.codOut > 100 ? 'warn' : 'run', sub: 'out' },
      { ic: 'flask', k: 'p.bod', v: 18, u: 'mg/L', st: 'run', sub: 'out' },
      { ic: 'layers', k: 'p.tss', v: 12, u: 'mg/L', st: 'run', sub: 'out' },
      { ic: 'droplet', k: 'p.nh4', v: 1.8, u: 'mg/L', st: 'run', sub: 'out' },
      { ic: 'droplet', k: 'p.ptot', v: 1.1, u: 'mg/L', st: 'run', sub: 'out' },
      { ic: 'wind', k: 'p.do', v: L.doO2, u: 'mg/L', st: L.doO2 < 1.6 ? 'warn' : 'run', sub: tl({ it: 'vasca bio', en: 'bio basin', es: 'biológico', fr: 'biologique', de: 'Belebung' }) },
      { ic: 'tank', k: 'c.level', v: 64, u: '%', st: 'run', sub: tl({ it: 'vasca bio', en: 'bio basin', es: 'biológico', fr: 'biologique', de: 'Belebung' }) },
    ];

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Linea di trattamento reflui: processo completo dalla grigliatura allo scarico finale con verifica dei limiti autorizzati.', en: 'Wastewater treatment line: full process from screening to final discharge with authorized-limit checks.', es: 'Línea de tratamiento de aguas residuales.', fr: 'Filière de traitement des eaux usées.', de: 'Abwasserbehandlungslinie.' })),

      // process strip
      h(Card, { cls: 'flush', style: { marginBottom: 'var(--gap)' } },
        h(CardHead, { bordered: true, icon: 'synoptic', title: tl({ it: 'Processo di trattamento', en: 'Treatment process', es: 'Proceso de tratamiento', fr: 'Procédé de traitement', de: 'Behandlungsprozess' }) }),
        h('div', { style: { padding: 16, overflowX: 'auto' } },
          h('div', { style: { display: 'flex', alignItems: 'center', gap: 0, minWidth: 'max-content' } },
            steps.map((st, i) => h(React.Fragment, { key: st.id },
              h('div', { style: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, minWidth: 78 } },
                h('div', { style: { width: 40, height: 40, borderRadius: 9, background: st.state === 'warn' ? 'var(--status-warn-bg)' : 'var(--status-run-bg)', color: st.state === 'warn' ? 'var(--status-warn)' : 'var(--status-run)', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1.5px solid ' + (st.state === 'warn' ? 'var(--status-warn)' : 'var(--status-run)') } },
                  h(Icon, { name: ['recycle', 'filter', 'layers', 'droplet', 'tank', 'tank', 'beaker', 'wind', 'activity', 'activity', 'tank', 'filter', 'power', 'droplets'][i] || 'tank', size: 19 })),
                h('div', { style: { fontSize: 10, fontWeight: 600, color: 'var(--fg-2)', textAlign: 'center', maxWidth: 78, lineHeight: 1.2 } }, st[s.lang] || st.it)),
              i < steps.length - 1 && h('div', { style: { width: 18, height: 2, background: 'var(--border-strong)', marginBottom: 16 } }))))) ),

      h('div', { className: 'grid g4', style: { marginBottom: 'var(--gap)' } },
        cards.map((c, i) => h(Card, { key: i, className: 'kpi', style: { padding: 16 } },
          h('div', { className: 'kpi-top' },
            h('span', { className: 'kpi-ic', style: { background: `var(--status-${window.statusInfo(c.st).cls}-bg)`, color: `var(--status-${window.statusInfo(c.st).cls})` } }, h(Icon, { name: c.ic, size: 20 })),
            h('div', { style: { flex: 1 } },
              h('div', { className: 'kpi-label' }, t(c.k), c.sub && h('span', { style: { color: 'var(--fg-3)' } }, ' · ' + c.sub)),
              h('div', { className: 'kpi-val', style: { fontSize: 23 } }, c.v, h('span', { className: 'unit' }, c.u)))))) ),

      h('div', { className: 'grid g2' },
        h(Card, { cls: 'flush' },
          h(CardHead, { bordered: true, icon: 'sigma', title: tl({ it: 'Parametri refluo', en: 'Wastewater parameters', es: 'Parámetros residuales', fr: 'Paramètres eaux usées', de: 'Abwasserparameter' }),
            right: h(Badge, { status: 'conform', label: t('c.compliance') + ' OK' }) }),
          h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
            h('thead', null, h('tr', null, [t('c.param'), t('c.inlet'), t('c.outlet'), t('c.limit'), t('c.status'), t('c.trend')].map((c, i) => h('th', { key: i, className: i > 0 && i < 4 ? 'num' : '' }, c)))),
            h('tbody', null, params.map((p, i) => {
              const ok = typeof p.out === 'number' && typeof p.limit === 'number' ? p.out <= p.limit : true;
              const near = ok && typeof p.out === 'number' && p.out > p.limit * 0.8;
              return h('tr', { key: i },
                h('td', null, h('strong', null, t(p.key)), ' ', h('span', { className: 'muted', style: { fontSize: 11 } }, p.unit)),
                h('td', { className: 'num mono muted' }, p.in),
                h('td', { className: 'num mono' }, p.out),
                h('td', { className: 'num mono muted' }, p.limit),
                h('td', null, h(Badge, { status: !ok ? 'alarm' : near ? 'warn' : 'run', label: !ok ? t('st.nonconform') : near ? t('st.attention') : t('st.conform') })),
                h('td', null, h(TrendArrow, { dir: p.trend })));
            }))))),
        h('div', { className: 'stack' },
          h(Card, null, h(CardHead, { icon: 'chart', title: t('ch.codbod'), sub: 'mg/L out · 24h' }),
            h(window.LineChart, { series: [{ data: s.history.codOut, color: '#F2941F' }], xLabels: xl24, h: 150, fixedMax: 90 })),
          h(Card, null, h(CardHead, { icon: 'wind', title: tl({ it: 'Soffianti & ricircolo', en: 'Blowers & recirculation', es: 'Soplantes', fr: 'Surpresseurs', de: 'Gebläse' }) }),
            h('div', null,
              h(MetricRow, { label: tl({ it: 'Soffiante B-201', en: 'Blower B-201', es: 'Soplante B-201', fr: 'Surpresseur B-201', de: 'Gebläse B-201' }), value: h(Badge, { status: 'warn' }) }),
              h(MetricRow, { label: tl({ it: 'Soffiante B-202', en: 'Blower B-202', es: 'Soplante B-202', fr: 'Surpresseur B-202', de: 'Gebläse B-202' }), value: h(Badge, { status: 'run' }) }),
              h(MetricRow, { label: tl({ it: 'Ricircolo fanghi', en: 'Sludge recirc.', es: 'Recirculación', fr: 'Recirculation', de: 'Rücklauf' }), value: '34 m³/h' }),
              h(MetricRow, { label: tl({ it: 'Spurgo fanghi', en: 'Sludge purge', es: 'Purga', fr: 'Extraction', de: 'Überschuss' }), value: h(Badge, { status: 'idle' }) })),
            h('div', { className: 'row', style: { marginTop: 12, gap: 8 } },
              h(Btn, { variant: 'run', icon: 'play', sm: true, onClick: () => toast('run', t('toast.pumpstart'), 'P-302') }, t('a.start') + ' P-302'),
              h(Btn, { variant: 'ghost', icon: 'check', sm: true, onClick: () => toast('run', t('toast.cyclecomplete'), 'Refluo') }, t('a.complete'))))))
    );
  }

  // ============================================================
  // LINEA FANGHI
  // ============================================================
  function Sludge() {
    const s = window.useStore();
    const { t, tl } = window.useApp();
    const D = window.DATA.sludge;

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Gestione della linea fanghi: produzione, ispessimento, digestione, disidratazione e smaltimento.', en: 'Sludge line management: production, thickening, digestion, dewatering and disposal.', es: 'Gestión de la línea de fangos.', fr: 'Gestion de la filière boues.', de: 'Verwaltung der Schlammlinie.' })),

      h('div', { className: 'grid g6', style: { marginBottom: 'var(--gap)' } },
        D.cards.map((c, i) => h(Card, { key: i, style: { padding: 16 } },
          h('div', { className: 'kpi-label' }, tl(c)),
          c.txt ? h('div', { className: 'kpi-val', style: { fontSize: 20, marginTop: 6 } }, c.txt)
            : h('div', { className: 'row', style: { justifyContent: 'space-between', marginTop: 6 } },
              h('span', { className: 'kpi-val', style: { fontSize: 23 } }, c.val, h('span', { className: 'unit' }, c.unit)),
              c.delta !== undefined && h('span', { className: 'kpi-delta ' + (c.delta >= 0 ? 'up' : 'down') }, h(Icon, { name: c.delta >= 0 ? 'arrowUp' : 'arrowDown', size: 12 }), Math.abs(c.delta)))))) ,

      h('div', { className: 'grid g2', style: { marginBottom: 'var(--gap)' } },
        h(Card, { cls: 'flush' },
          h(CardHead, { bordered: true, icon: 'layers', title: tl({ it: 'Processo linea fanghi', en: 'Sludge line process', es: 'Proceso línea fangos', fr: 'Procédé filière boues', de: 'Schlammlinienprozess' }) }),
          h('div', { style: { padding: 16 } },
            D.stages.map((st, i) => h('div', { key: i, className: 'metric-row' },
              h('span', { className: 'ml', style: { display: 'flex', alignItems: 'center', gap: 8 } }, h('span', { className: 'mono', style: { color: 'var(--fg-3)', fontSize: 11, width: 18 } }, i + 1), tl(st)),
              h(Badge, { status: st.state }))))),
        h('div', { className: 'stack' },
          h(Card, null, h(CardHead, { icon: 'chart', title: t('ch.sludgeprod'), sub: 't/d · 14d' }),
            h(window.BarChart, { data: s.history.sludge, color: '#8B6F47', h: 160 })),
          h(Card, { style: { textAlign: 'center' } }, h(CardHead, { icon: 'box', title: tl({ it: 'Cassone fanghi', en: 'Sludge skip', es: 'Contenedor', fr: 'Benne à boues', de: 'Schlammcontainer' }) }),
            h('div', { className: 'row', style: { justifyContent: 'center', gap: 24 } },
              h(Donut, { value: 78, size: 96, color: '#E8A317', label: tl({ it: 'pieno', en: 'full', es: 'lleno', fr: 'plein', de: 'voll' }) }),
              h('div', { style: { textAlign: 'left' } },
                h(MetricRow, { label: t('m.dryness'), value: '22.4', unit: '%' }),
                h(MetricRow, { label: t('m.nextpickup'), value: '18/06' }),
                h('div', { style: { marginTop: 8 } }, h(Badge, { status: 'warn', label: tl({ it: 'Ritiro consigliato', en: 'Pickup advised', es: 'Retirada', fr: 'Enlèvement', de: 'Abholung' }) })))))))
    );
  }

  window.Sections = window.Sections || {};
  Object.assign(window.Sections, { Primary, Potable, Waste, Sludge });
})();
