/* global React, Card, StatCard, StatusBadge, StatusGlyph, STATUS_META, Ic, Button, VS */

function Dashboard({ onOpenRecent }) {
  const [data, setData] = React.useState(null);
  const [recent, setRecent] = React.useState(null);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    (async () => {
      try {
        const [d, r] = await Promise.all([VS.dashboard(), VS.recentSessions(12)]);
        setData(d); setRecent(r);
      } catch (e) { setErr(e.message); }
    })();
  }, []);

  const now = new Date();
  const dayStr = now.toLocaleDateString('pl-PL', { weekday: 'long' });
  const fullDate = now.toLocaleDateString('pl-PL', { day: 'numeric', month: 'long', year: 'numeric' });

  if (err) return <ErrorState message={err} />;
  if (!data) return <LoadingState />;

  const okPct = data.total_machines ? Math.round((data.machines_ok / data.total_machines) * 100) : 0;
  const warn = data.machines_warn || 0;
  const alarm = data.machines_alarm || 0;
  const needAttention = warn + alarm;

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 1440, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="uppercase-label" style={{ marginBottom: 6 }}>{dayStr}, {fullDate}</div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 500, letterSpacing: '-0.025em' }}>
            Dzień dobry, {VS.getUsername() || 'inżynierze'}.
          </h1>
          <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 6 }}>
            System monitoruje <span className="mono" style={{ color: 'var(--fg)' }}>{fmtInt(data.total_machines)}</span> maszyn
            w <span className="mono" style={{ color: 'var(--fg)' }}>{fmtInt(data.total_sites)}</span> zakładach.
            {needAttention > 0 ? (
              <> <span className="mono" style={{ color: 'var(--alarm)' }}>{needAttention} maszyn</span> wymaga uwagi.</>
            ) : (
              <> <span className="mono" style={{ color: 'var(--ok)' }}>wszystko w normie</span>.</>
            )}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button icon={<Ic.refresh />} onClick={() => location.reload()}>Odśwież</Button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        <StatCard label="Pomiary w systemie" value={fmtInt(data.total_measurements)} />
        <StatCard label="Monitorowane maszyny" value={fmtInt(data.total_machines)} note={`w ${data.total_sites} zakładach`} />
        <StatCard label="Stan OK" value={fmtInt(data.machines_ok)} unit={`/ ${data.total_machines}`} status="ok" note={`${okPct}% parku`} />
        <StatCard label="Wymagają uwagi" value={fmtInt(needAttention)} unit={`/ ${data.total_machines}`} status={alarm ? 'alarm' : warn ? 'warn' : 'idle'} note={`${warn} ostrz. · ${alarm} alarm`} />
      </div>

      {data.daily_stats?.length > 0 && (
        <Card pad={false}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--hairline)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500 }}>Puls systemu</h3>
              <span className="mono" style={{ fontSize: 10, color: 'var(--fg-subtle)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                ostatnie {data.daily_stats.length} dni · pomiary / ostrzeżenia / alarmy
              </span>
            </div>
            <div style={{ display: 'flex', gap: 12, fontSize: 10.5, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><StatusGlyph status="ok" size={8} /> OK</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><StatusGlyph status="warn" size={8} /> Ostrz.</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><StatusGlyph status="alarm" size={8} /> Alarm</span>
            </div>
          </div>
          <div style={{ padding: 16 }}>
            <DailyBars days={data.daily_stats} />
          </div>
        </Card>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
        <Card pad={false}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--hairline)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ margin: 0, fontSize: 14, fontWeight: 500 }}>Ostatnie pomiary</h3>
            <span className="mono" style={{ fontSize: 10, color: 'var(--fg-subtle)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              {recent ? `${recent.length} sesji` : '…'}
            </span>
          </div>
          <div>
            {recent && recent.length === 0 && <div style={{ padding: 20, color: 'var(--fg-muted)', fontSize: 12 }}>Brak pomiarów.</div>}
            {recent && recent.map((r, i) => {
              const st = statusFromAlarm(r.max_alarm);
              return (
                <div key={i}
                  onClick={() => onOpenRecent && onOpenRecent(r)}
                  style={{
                    display: 'grid', gridTemplateColumns: '72px 1fr 80px 100px',
                    gap: 12, padding: '10px 16px',
                    borderBottom: i < recent.length - 1 ? '1px solid var(--hairline)' : 'none',
                    alignItems: 'center', fontSize: 12,
                    cursor: onOpenRecent ? 'pointer' : 'default',
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bg-sunken)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
                >
                  <span className="mono" style={{ color: 'var(--fg-muted)' }}>{r.time_start || '—'}</span>
                  <span style={{ fontWeight: 500 }}>{r.machine_name}</span>
                  <span className="mono" style={{ color: 'var(--fg-subtle)', fontSize: 11 }}>{r.point_count} pkt</span>
                  <StatusBadge status={st} size="sm" />
                </div>
              );
            })}
          </div>
        </Card>

        <Card style={{ background: 'var(--bg-elev)', display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div className="uppercase-label">Wskazówka dnia</div>
          <div style={{ fontSize: 14, lineHeight: 1.55, letterSpacing: '-0.005em', flex: 1 }}>
            Porównuj wartości VEL RMS (prędkości drgań w mm/s) z normą ISO&nbsp;10816-3 dla danej klasy maszyny.
            Wartości w strefie&nbsp;C (powyżej 4,5 mm/s dla maszyn klasy II) oznaczają, że praca długoterminowa
            jest niedopuszczalna — zaplanuj serwis.
          </div>
          <div style={{ display: 'flex', gap: 8, paddingTop: 8, borderTop: '1px solid var(--hairline)', fontSize: 11, color: 'var(--fg-muted)' }}>
            <span>ISO 10816-3</span>
            <span>·</span>
            <span>Klasa II &lt; 15 kW</span>
          </div>
        </Card>
      </div>
    </div>
  );
}

function DailyBars({ days }) {
  const max = Math.max(...days.map(d => d.sessions || 0), 1);
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'flex-end', height: 120 }}>
      {days.map((d, i) => {
        const total = d.sessions || 0;
        const alarms = d.alarms || 0;
        const warns = d.warnings || 0;
        const ok = Math.max(0, total - alarms - warns);
        const pct = (v) => (v / max) * 100;
        const label = d.date ? d.date.slice(5) : '';
        return (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <div style={{ fontSize: 10, color: 'var(--fg-subtle)' }} className="mono">{total}</div>
            <div style={{
              display: 'flex', flexDirection: 'column-reverse',
              width: '100%', height: 80,
              background: 'var(--bg-sunken)',
              border: '1px solid var(--hairline)',
              borderRadius: 'var(--r-sm)',
              overflow: 'hidden',
            }}>
              {ok > 0 && <div title={`OK ${ok}`} style={{ background: 'var(--ok)', opacity: 0.7, height: `${pct(ok)}%` }} />}
              {warns > 0 && <div title={`Ostrz. ${warns}`} style={{ background: 'var(--warn)', opacity: 0.85, height: `${pct(warns)}%` }} />}
              {alarms > 0 && <div title={`Alarm ${alarms}`} style={{ background: 'var(--alarm)', height: `${pct(alarms)}%` }} />}
            </div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--fg-muted)' }}>{label}</div>
          </div>
        );
      })}
    </div>
  );
}

function LoadingState() {
  return <div style={{ padding: 48, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13 }}>Ładowanie…</div>;
}

function ErrorState({ message }) {
  return (
    <div style={{ padding: 48, maxWidth: 600, margin: '0 auto' }}>
      <div style={{
        padding: 16, background: 'var(--alarm-weak)', border: '1px solid var(--alarm-border)',
        borderRadius: 'var(--r-md)', color: 'var(--alarm)', fontFamily: 'var(--font-mono)', fontSize: 12,
      }}>{message}</div>
    </div>
  );
}

function fmtInt(n) { return (n || 0).toLocaleString('pl-PL'); }

function statusFromAlarm(level) {
  if (!level && level !== 0) return 'idle';
  if (level >= 3) return 'alarm';
  if (level >= 2) return 'warn';
  return 'ok';
}

Object.assign(window, { Dashboard, LoadingState, ErrorState, statusFromAlarm, fmtInt });
