// HACCP TempMon — Live monitoring screen
const { useState, useEffect } = React;

function LiveScreen({ live, device, history, activeAlerts, broker, devices, selectedDevice, onSelectDevice }) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []);

  const breachCount = Object.keys(activeAlerts).length;
  const status = !live.online   ? 'unknown'
               : breachCount > 0 ? 'breach'
               : live.lastReadingTs && now - live.lastReadingTs > 30000 ? 'stale'
               : 'safe';

  // Determine which temperature is the "primary" CCP temp
  const isCooking = live.ccpType === 'COOKING' || live.ccpType === 'HOT_HOLD';
  const primaryTemp  = isCooking ? live.cookingTempC : live.probeTempC;
  const primaryLabel = isCooking ? 'Cooking' : 'Probe';
  const primaryHist  = isCooking ? history.cookingTempC : history.probeTempC;
  const primaryColor = isCooking ? 'var(--ccp-cooking)' : 'var(--ccp-cold)';

  const deviceList = Object.keys(devices || {}).sort();

  return (
    <div>
      {/* Header */}
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Live Monitoring</div>
          <h1 className="page-title" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {selectedDevice || 'Waiting for device…'}
            {live.ccpType && <CcpBadge ccpType={live.ccpType} />}
          </h1>
          <div className="page-subtitle">
            {live.online
              ? `Last reading ${formatAge(live.lastReadingTs)} · ${device.msgCount} msgs`
              : broker === 'connected' ? 'Waiting for readings…' : `Broker: ${broker}`}
          </div>
        </div>
        <div className="row gap-8 items-center">
          <StatusBadge status={status} />
          {deviceList.length > 1 && (
            <select
              className="btn btn-sm"
              value={selectedDevice || ''}
              onChange={e => window.HACCP_STORE.setSelectedDevice(e.target.value)}
              style={{ fontFamily: 'inherit' }}>
              {deviceList.map(id => <option key={id} value={id}>{id}</option>)}
            </select>
          )}
        </div>
      </div>

      {/* Active breaches banner */}
      {breachCount > 0 && (
        <div className="card" style={{ marginBottom: 24, borderColor: 'var(--status-breach)', background: 'oklch(0.55 0.2 25 / 0.05)' }}>
          <div className="card-title" style={{ color: 'var(--status-breach)', marginBottom: 12 }}>
            Active Breach{breachCount > 1 ? 'es' : ''} — {breachCount}
          </div>
          {Object.values(activeAlerts).map(a => (
            <div key={a.alert_type} className="alert-item">
              <span className="alert-dot" />
              <span className="alert-type">{a.alert_type}</span>
              <span className="alert-temp">{formatTemp(a.temp_c)}</span>
              <span className="alert-threshold">threshold {formatTemp(a.threshold_c)}</span>
              <span className="alert-since">{new Date(a.since).toLocaleTimeString('en-GB', { hour12: false })}</span>
            </div>
          ))}
        </div>
      )}

      {/* Main temperature rings */}
      <div className="card" style={{ marginBottom: 16, padding: 40 }}>
        <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center', flexWrap: 'wrap', gap: 32 }}>
          {/* Primary CCP temperature */}
          <div className="col items-center gap-16">
            <TempRing
              tempC={primaryTemp}
              status={status}
              size={180}
              label={primaryLabel}
            />
            {primaryHist.length >= 2 && (
              <div style={{ width: 180 }}>
                <Sparkline data={primaryHist} height={36} color={primaryColor} fill />
              </div>
            )}
          </div>

          {/* Ambient temperature */}
          <div className="col items-center gap-16">
            <TempRing
              tempC={live.ambientTempC}
              status={live.online && !breachCount ? 'safe' : status}
              size={180}
              label="Ambient"
            />
            {history.ambientTempC.length >= 2 && (
              <div style={{ width: 180 }}>
                <Sparkline data={history.ambientTempC} height={36} color="var(--ccp-ambient)" fill />
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Detail metrics */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        {/* Humidity */}
        <div className="card-flat">
          <div className="card-title" style={{ marginBottom: 12 }}>Humidity</div>
          <div className="row items-baseline gap-4">
            <span className="num" style={{ fontSize: 28, fontWeight: 600 }}>
              {live.ambientRh != null ? live.ambientRh.toFixed(1) : '--'}
            </span>
            <span className="text-sm text-ink-3">%</span>
          </div>
          {history.ambientRh.length >= 2 && (
            <div style={{ marginTop: 8 }}>
              <Sparkline data={history.ambientRh} height={28} color="var(--ccp-cold)" />
            </div>
          )}
        </div>

        {/* Cooking temp (only shows for COOKING / HOT_HOLD) */}
        {(live.ccpType === 'COOKING' || live.ccpType === 'HOT_HOLD' || live.cookingTempC != null) && (
          <div className="card-flat">
            <div className="card-title" style={{ marginBottom: 12 }}>Cooking</div>
            <div className="row items-baseline gap-4">
              <span className="num" style={{ fontSize: 28, fontWeight: 600 }}>
                {live.cookingTempC != null ? live.cookingTempC.toFixed(1) : '--'}
              </span>
              <span className="text-sm text-ink-3">°C</span>
            </div>
          </div>
        )}

        {/* Battery */}
        <div className="card-flat">
          <div className="card-title" style={{ marginBottom: 12 }}>Battery</div>
          {live.batteryMv != null ? (
            <>
              <div className="row items-baseline gap-4">
                <span className="num" style={{ fontSize: 28, fontWeight: 600 }}>
                  {Math.max(0, Math.min(100, Math.round((live.batteryMv - 3300) / (4200 - 3300) * 100)))}
                </span>
                <span className="text-sm text-ink-3">%</span>
              </div>
              <div className="text-xs text-ink-3" style={{ marginTop: 4 }}>
                {(live.batteryMv / 1000).toFixed(2)} V
              </div>
            </>
          ) : (
            <div className="num" style={{ fontSize: 28, fontWeight: 600 }}>--</div>
          )}
        </div>

        {/* Signal */}
        <div className="card-flat">
          <div className="card-title" style={{ marginBottom: 12 }}>Signal</div>
          <div className="row items-baseline gap-4">
            <span className="num" style={{ fontSize: 28, fontWeight: 600 }}>
              {live.rssi != null ? live.rssi : '--'}
            </span>
            {live.rssi != null && <span className="text-sm text-ink-3">dBm</span>}
          </div>
          {device.ssid && (
            <div className="text-xs text-ink-3" style={{ marginTop: 4 }}>{device.ssid}</div>
          )}
        </div>
      </div>

      {/* Device uptime strip */}
      {live.uptimeMs != null && (
        <div className="card-flat" style={{ marginBottom: 0 }}>
          <div className="row gap-32 items-center flex-wrap">
            <div className="col gap-4">
              <div className="text-xs text-ink-4" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>Uptime</div>
              <div className="mono text-sm">{formatUptime(Math.floor(live.uptimeMs / 1000))}</div>
            </div>
            {device.fwVersion && (
              <div className="col gap-4">
                <div className="text-xs text-ink-4" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>Firmware</div>
                <div className="mono text-sm">{device.fwVersion}</div>
              </div>
            )}
            {device.ip && (
              <div className="col gap-4">
                <div className="text-xs text-ink-4" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>IP</div>
                <div className="mono text-sm">{device.ip}</div>
              </div>
            )}
            <div className="col gap-4" style={{ marginLeft: 'auto' }}>
              <div className="text-xs text-ink-4" style={{ textTransform: 'uppercase', letterSpacing: '0.1em' }}>Last reading</div>
              <div className="mono text-sm">{live.lastReadingTs ? new Date(live.lastReadingTs).toLocaleTimeString('en-GB', { hour12: false }) : '--'}</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
