/* ============================================================
   Operion WTT — Operations sections
   Energy, Maintenance, Alarms, Reports
   ============================================================ */
(function () {
  const { useState } = React;
  const { Card, CardHead, KPI, Badge, SDot, Btn, Icon, Donut, MetricRow, SearchBox, Sel, Empty } = window;
  const h = React.createElement;
  const xl24 = ['00', '04', '08', '12', '16', '20', ''];

  // ============================================================
  // ENERGIA E CONSUMI
  // ============================================================
  function Energy() {
    const s = window.useStore();
    const { t, tl } = window.useApp();
    const E = window.DATA.energy;
    const months = [1620, 1710, 1580, 1690, 1840, 1920, 1780, 1650, 1730, 1810, 1842, 1760];

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Monitoraggio dell\u2019efficienza energetica e dei consumi per reparto, con stima costi ed emissioni.', en: 'Energy-efficiency and consumption monitoring by area, with cost and emission estimates.', es: 'Monitoreo de eficiencia energética.', fr: 'Suivi de l\u2019efficacité énergétique.', de: 'Überwachung der Energieeffizienz.' })),

      h('div', { className: 'grid g4', style: { marginBottom: 'var(--gap)' } },
        h(KPI, { icon: 'zap', label: t('k.energy'), value: s.live.energyToday.toLocaleString(), unit: 'kWh', delta: '+2.1%', deltaDir: 'up', spark: s.history.energy, sparkColor: '#8B5CF6' }),
        h(KPI, { icon: 'gauge', label: t('m.specific_energy'), value: E.specific, unit: 'kWh/m³', delta: '-0.02', deltaDir: 'down' }),
        h(KPI, { icon: 'signal', label: t('m.peak'), value: E.peak, unit: 'kW', delta: '14:20', deltaDir: 'flat' }),
        h(KPI, { icon: 'euro', label: t('m.cost_today'), value: '€ ' + E.cost, delta: '€ 0.24/m³', deltaDir: 'flat' })),

      h('div', { className: 'grid g2', style: { marginBottom: 'var(--gap)' } },
        h(Card, null, h(CardHead, { icon: 'chart', title: tl({ it: 'Consumo energia per ora', en: 'Energy use per hour', es: 'Consumo por hora', fr: 'Consommation horaire', de: 'Stündlicher Verbrauch' }), sub: 'kWh' }),
          h(window.AreaChart, { data: s.history.energy, color: '#8B5CF6', xLabels: xl24, h: 200 })),
        h(Card, null, h(CardHead, { icon: 'sliders', title: t('m.byDept'), sub: 'kWh' }),
          h(window.BarChart, { data: E.byDept.map((d) => d.kwh), labels: E.byDept.map((d) => tl(d)), horizontal: true, h: 200, color: ['#23416A', '#2E5286', '#4470A6', '#6E97C4', '#A7C2DE', '#C2CCD6'] }))),

      h('div', { className: 'grid g3' },
        h(Card, { style: { textAlign: 'center' } }, h(CardHead, { icon: 'leaf', title: t('m.co2') }),
          h('div', { className: 'row', style: { justifyContent: 'center', gap: 18 } },
            h(Donut, { value: 62, size: 100, color: '#1E9E5A', label: 'CO₂' }),
            h('div', { style: { textAlign: 'left' } },
              h(MetricRow, { label: t('c.today'), value: E.co2, unit: 'kg' }),
              h(MetricRow, { label: tl({ it: 'Specifico', en: 'Specific', es: 'Específico', fr: 'Spécifique', de: 'Spezifisch' }), value: '0.27', unit: 'kg/m³' })))),
        h(Card, { cls: 'col-2' }, h(CardHead, { icon: 'calendar', title: tl({ it: 'Trend mensile consumi', en: 'Monthly consumption trend', es: 'Tendencia mensual', fr: 'Tendance mensuelle', de: 'Monatlicher Verlauf' }), sub: 'kWh/d · 12m' }),
          h(window.BarChart, { data: months, labels: null, h: 160, color: '#23416A', xLabels: ['G', 'F', 'M', 'A', 'M', 'G', 'L', 'A', 'S', 'O', 'N', 'D'] }))));
  }

  // ============================================================
  // MANUTENZIONE
  // ============================================================
  function Maintenance() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const [q, setQ] = useState('');
    const [dept, setDept] = useState('all');
    const [done, setDone] = useState({});
    const assets = s.maintenance;
    const depts = ['all', 'primary', 'waste', 'sludge', 'lab', 'aux'];
    const filtered = assets.filter((a) => (dept === 'all' || a.dept === dept) && ((a[s.lang] || a.it).toLowerCase().includes(q.toLowerCase()) || a.id.toLowerCase().includes(q.toLowerCase())));

    const wos = [
      { id: 'WO-1182', it: 'Sostituzione lampada UV-401', en: 'Replace UV-401 lamp', asset: 'UV-401', prio: 'medium', tech: 'A. Verdi', due: '16/06' },
      { id: 'WO-1181', it: 'Controllo soffiante B-201', en: 'Inspect blower B-201', asset: 'B-201', prio: 'high', tech: 'L. Bianchi', due: '20/06' },
      { id: 'WO-1180', it: 'Taratura sensore torbidità', en: 'Calibrate turbidity sensor', asset: 'AI-102', prio: 'medium', tech: 'S. Conti', due: '16/06' },
      { id: 'WO-1179', it: 'Reset pompa controlavaggio', en: 'Reset backwash pump', asset: 'P-501', prio: 'high', tech: 'M. Rossi', due: '15/06' },
    ];

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Gestione manutenzione asset: registro interventi, ordini di lavoro e scadenze programmate.', en: 'Asset maintenance: intervention log, work orders and scheduled deadlines.', es: 'Mantenimiento de activos.', fr: 'Maintenance des équipements.', de: 'Anlagenwartung.' })),

      h('div', { className: 'grid g4', style: { marginBottom: 'var(--gap)' } },
        h(KPI, { icon: 'wrench', label: tl({ it: 'Asset monitorati', en: 'Monitored assets', es: 'Activos', fr: 'Équipements', de: 'Anlagen' }), value: assets.length }),
        h(KPI, { icon: 'clock', label: tl({ it: 'In scadenza (7gg)', en: 'Due (7 days)', es: 'Por vencer', fr: 'À échéance', de: 'Fällig' }), value: 4, accent: true }),
        h(KPI, { icon: 'clipboard', label: t('m.workorders'), value: wos.length }),
        h(KPI, { icon: 'alert', label: tl({ it: 'Priorità alta', en: 'High priority', es: 'Alta prioridad', fr: 'Priorité haute', de: 'Hohe Priorität' }), value: 2 })),

      h('div', { className: 'grid g2' },
        h(Card, { cls: 'flush', style: { gridColumn: 'span 1' } },
          h(CardHead, { bordered: true, icon: 'wrench', title: t('m.assetlist'),
            right: h(Btn, { variant: 'accent', icon: 'plus', sm: true, onClick: () => toast('run', t('toast.wocreated'), 'WO-1183') }, t('a.new_wo')) }),
          h('div', { style: { padding: '12px 16px', display: 'flex', gap: 8, flexWrap: 'wrap', borderBottom: '1px solid var(--border)' } },
            h(SearchBox, { value: q, onChange: setQ, placeholder: t('c.search') }),
            h(Sel, { value: dept, onChange: setDept, options: depts.map((d) => ({ v: d, label: d === 'all' ? t('c.all') : ({ primary: t('grp.primary'), waste: t('grp.waste'), sludge: tl({ it: 'Fanghi', en: 'Sludge', es: 'Fangos', fr: 'Boues', de: 'Schlamm' }), lab: tl({ it: 'Laboratorio', en: 'Lab', es: 'Lab', fr: 'Labo', de: 'Labor' }), aux: tl({ it: 'Ausiliari', en: 'Auxiliary', es: 'Auxiliar', fr: 'Auxiliaire', de: 'Hilfs' }) }[d]) })) })),
          h('div', { className: 'tbl-wrap', style: { maxHeight: 420, overflowY: 'auto' } }, h('table', { className: 'tbl' },
            h('thead', null, h('tr', null, [t('c.code'), t('c.component'), t('c.status'), t('c.runhours'), t('c.nextmaint'), t('c.priority')].map((c, i) => h('th', { key: i, className: i === 3 ? 'num' : '' }, c)))),
            h('tbody', null, filtered.map((a) => h('tr', { key: a.id },
              h('td', { className: 'mono' }, a.id),
              h('td', null, h('strong', null, a[s.lang] || a.it)),
              h('td', null, h(Badge, { status: a.state })),
              h('td', { className: 'num mono muted' }, a.hours.toLocaleString()),
              h('td', { className: 'mono', style: { fontSize: 12 } }, a.next),
              h('td', null, h(Badge, { status: a.prio === 'high' ? 'alarm' : a.prio === 'medium' ? 'warn' : 'idle', label: t('c.' + a.prio) })))))))),
        h(Card, { cls: 'flush' },
          h(CardHead, { bordered: true, icon: 'clipboard', title: t('m.workorders') }),
          h('div', { style: { padding: 8 } }, wos.map((w) => h('div', { key: w.id, style: { display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderBottom: '1px solid var(--border)', opacity: done[w.id] ? 0.5 : 1 } },
            h(SDot, { status: done[w.id] ? 'run' : w.prio === 'high' ? 'alarm' : 'warn' }),
            h('div', { style: { flex: 1, minWidth: 0 } },
              h('div', { style: { fontSize: 13.5, fontWeight: 600, color: 'var(--fg-1)' } }, w[s.lang] || w.it),
              h('div', { className: 'mono', style: { fontSize: 11, color: 'var(--fg-3)' } }, w.id + ' · ' + w.asset + ' · ' + w.tech + ' · ' + w.due)),
            done[w.id] ? h(Badge, { status: 'run', label: t('al.resolved') })
              : h(Btn, { variant: 'run', icon: 'check', sm: true, onClick: () => { setDone((d) => ({ ...d, [w.id]: true })); toast('run', t('toast.wocomplete'), w.id); } }, t('a.complete')))))))
    );
  }

  // ============================================================
  // ALLARMI
  // ============================================================
  function Alarms() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const [sev, setSev] = useState('all');
    const [area, setArea] = useState('all');
    const [q, setQ] = useState('');
    const areas = ['all', 'primary', 'waste', 'sludge', 'chem', 'lab', 'aux'];
    const list = s.alarms.filter((a) => (sev === 'all' || a.sev === sev) && (area === 'all' || a.area === area) && ((a[s.lang] || a.it).toLowerCase().includes(q.toLowerCase()) || a.code.toLowerCase().includes(q.toLowerCase()) || a.id.toLowerCase().includes(q.toLowerCase())));
    const counts = { critical: s.alarms.filter((a) => a.sev === 'critical' && a.state !== 'resolved').length, warning: s.alarms.filter((a) => a.sev === 'warning' && a.state !== 'resolved').length, info: s.alarms.filter((a) => a.sev === 'info' && a.state !== 'resolved').length, open: s.alarms.filter((a) => a.state === 'open').length };

    return h('div', { className: 'page' },
      h('div', { className: 'grid g4', style: { marginBottom: 'var(--gap)' } },
        h(KPI, { icon: 'alert', label: t('sev.critical'), value: counts.critical, accent: counts.critical > 0 }),
        h(KPI, { icon: 'bell', label: t('sev.warning'), value: counts.warning }),
        h(KPI, { icon: 'info', label: t('sev.info'), value: counts.info }),
        h(KPI, { icon: 'clock', label: t('al.open'), value: counts.open })),

      h('div', { className: 'toolbar' },
        h(SearchBox, { value: q, onChange: setQ, placeholder: t('c.search') }),
        h(Sel, { value: sev, onChange: setSev, options: [{ v: 'all', label: t('c.all') + ' · ' + t('c.severity') }, { v: 'critical', label: t('sev.critical') }, { v: 'warning', label: t('sev.warning') }, { v: 'info', label: t('sev.info') }] }),
        h(Sel, { value: area, onChange: setArea, options: areas.map((a) => ({ v: a, label: a === 'all' ? t('c.all') + ' · ' + t('c.area') : a })) }),
        h('span', { className: 'spacer' }),
        h(Btn, { variant: 'ghost', icon: 'alert', sm: true, onClick: () => { window.STORE.spawnAlarm({ sev: 'warning', area: 'lab', it: 'Allarme di test operatore', en: 'Operator test alarm', es: 'Alarma de prueba', fr: 'Alarme test', de: 'Testalarm', code: 'TEST-01', act: 'Nessuna azione, test', auto: true }); toast('warn', t('toast.testalarm'), 'TEST-01'); } }, t('sim.testalarm'))),

      h(Card, { cls: 'flush' },
        list.length === 0 ? h(Empty, { msg: t('m.noalarms') }) :
        h('div', { className: 'tbl-wrap' }, h('table', { className: 'tbl' },
          h('thead', null, h('tr', null, [t('c.code'), t('c.severity'), t('c.area'), t('c.desc'), t('c.datetime'), t('c.status'), t('c.operator'), ''].map((c, i) => h('th', { key: i }, c)))),
          h('tbody', null, list.map((a) => h('tr', { key: a.id },
            h('td', { className: 'mono' }, a.code),
            h('td', null, h(Badge, { status: a.sev, pulse: a.sev === 'critical' && a.state === 'open' })),
            h('td', { className: 'muted', style: { textTransform: 'uppercase', fontSize: 11, fontFamily: 'IBM Plex Mono,monospace' } }, a.area),
            h('td', null, h('strong', null, a[s.lang] || a.it), h('div', { className: 'muted', style: { fontSize: 11.5 } }, a.act)),
            h('td', { className: 'mono', style: { fontSize: 12 } }, a.ts),
            h('td', null, h(Badge, { status: a.state === 'open' ? 'alarm' : a.state === 'ack' ? 'warn' : 'run', label: t('al.' + a.state) })),
            h('td', { className: 'muted', style: { fontSize: 12 } }, a.op),
            h('td', null, h('div', { className: 'row', style: { gap: 4, justifyContent: 'flex-end' } },
              a.state === 'open' && h(Btn, { variant: 'warn', icon: 'check', sm: true, onClick: () => { window.STORE.ackAlarm(a.id); toast('info', t('toast.alarmack'), a.code); } }, t('a.ack')),
              a.state !== 'resolved' && h(Btn, { variant: 'run', icon: 'check', sm: true, onClick: () => { window.STORE.resolveAlarm(a.id); toast('run', t('toast.alarmresolved'), a.code); } }, t('a.resolve'))))))))))
    );
  }

  // ============================================================
  // REPORT
  // ============================================================
  function Reports() {
    const s = window.useStore();
    const { t, tl, toast } = window.useApp();
    const R = window.DATA.reports;
    const cats = { prod: { ic: 'droplet', c: '#2E8BC0' }, quality: { ic: 'flask', c: '#1E9E5A' }, compliance: { ic: 'shield', c: '#23416A' }, energy: { ic: 'zap', c: '#8B5CF6' }, ops: { ic: 'wrench', c: '#F2941F' } };

    return h('div', { className: 'page' },
      h('p', { className: 'page-intro' }, tl({ it: 'Reportistica avanzata: genera, esporta e invia report su produzione, qualità, consumi e conformità.', en: 'Advanced reporting: generate, export and send reports on production, quality, consumption and compliance.', es: 'Informes avanzados.', fr: 'Rapports avancés.', de: 'Erweiterte Berichte.' })),

      h(Card, { style: { marginBottom: 'var(--gap)' } },
        h('div', { className: 'row wrap', style: { gap: 10 } },
          h('span', { style: { fontSize: 12.5, fontWeight: 700, color: 'var(--fg-2)', fontFamily: 'IBM Plex Mono,monospace', letterSpacing: '.06em' } }, t('c.range').toUpperCase()),
          h(Sel, { value: '30', onChange: () => {}, options: [{ v: '7', label: tl({ it: 'Ultimi 7 giorni', en: 'Last 7 days', es: '7 días', fr: '7 jours', de: '7 Tage' }) }, { v: '30', label: tl({ it: 'Ultimi 30 giorni', en: 'Last 30 days', es: '30 días', fr: '30 jours', de: '30 Tage' }) }, { v: '90', label: tl({ it: 'Ultimo trimestre', en: 'Last quarter', es: 'Trimestre', fr: 'Trimestre', de: 'Quartal' }) }] }),
          h(Sel, { value: 'all', onChange: () => {}, options: [{ v: 'all', label: t('c.all') + ' · ' + t('c.area') }, { v: 'primary', label: t('grp.primary') }, { v: 'waste', label: t('grp.waste') }] }),
          h(Sel, { value: 'all', onChange: () => {}, options: [{ v: 'all', label: t('c.all') + ' · ' + t('c.compliance') }, { v: 'ok', label: t('st.conform') }] }),
          h('span', { className: 'spacer' }),
          h(Btn, { variant: 'accent', icon: 'refresh', sm: true, onClick: () => toast('run', t('toast.reportgen'), t('a.generate')) }, t('a.generate')))),

      h('div', { className: 'grid g3' },
        R.map((r) => { const cat = cats[r.cat]; return h(Card, { key: r.id, style: { padding: 18, display: 'flex', flexDirection: 'column' } },
          h('div', { className: 'row', style: { justifyContent: 'space-between', marginBottom: 14 } },
            h('span', { style: { width: 42, height: 42, borderRadius: 9, background: `color-mix(in srgb,${cat.c} 12%,var(--bg-surface))`, color: cat.c, display: 'flex', alignItems: 'center', justifyContent: 'center' } }, h(Icon, { name: cat.ic, size: 21 })),
            h('span', { className: 'mono', style: { fontSize: 10.5, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '.06em' } }, r.cat)),
          h('strong', { style: { fontSize: 15, color: 'var(--fg-1)', marginBottom: 4 } }, r[s.lang] || r.it),
          h('div', { className: 'muted', style: { fontSize: 12.5, marginBottom: 14, flex: 1 } }, tl({ it: 'Report periodico aggiornato al', en: 'Periodic report updated to', es: 'Informe actualizado al', fr: 'Rapport mis à jour au', de: 'Bericht aktualisiert am' }) + ' 15/06/26'),
          h('div', { className: 'row', style: { gap: 6, flexWrap: 'wrap' } },
            h(Btn, { variant: 'ghost', icon: 'download', sm: true, onClick: () => toast('run', t('a.export_pdf'), r[s.lang] || r.it) }, 'PDF'),
            h(Btn, { variant: 'ghost', icon: 'download', sm: true, onClick: () => toast('run', t('a.export_xls'), r[s.lang] || r.it) }, 'XLS'),
            h('button', { className: 'icon-btn', style: { width: 32, height: 32 }, title: t('a.print'), onClick: () => toast('info', t('a.print'), r[s.lang] || r.it) }, h(Icon, { name: 'printer', size: 15 })),
            h('button', { className: 'icon-btn', style: { width: 32, height: 32 }, title: t('a.email'), onClick: () => toast('info', t('a.email'), r[s.lang] || r.it) }, h(Icon, { name: 'mail', size: 15 })))); })));
  }

  window.Sections = window.Sections || {};
  Object.assign(window.Sections, { Energy, Maintenance, Alarms, Reports });
})();
