// BHEEM Sense — Monitoring periods / log screen
//
// Shows min/avg/max for BOTH channels. The HACCP original tracked temperature
// only, and read p.started_at / p.ended_at / p.reading_count — none of which
// are real columns (they are start_time / end_time / total_readings), so those
// three columns always rendered blank. Corrected here.
const { useState } = React;

function HistoryScreen({ periods, selectedDevice, apiReachable }) {
  const [refreshing, setRefreshing] = useState(false);

  async function handleRefresh() {
    setRefreshing(true);
    await window.BHEEM_STORE.refreshPeriods();
    setRefreshing(false);
  }

  function fmtDuration(start, end) {
    if (!start || !end) return '—';
    const s = Math.round(end - start);
    if (s < 60)   return `${s}s`;
    if (s < 3600) return `${Math.floor(s / 60)}m`;
    const h = Math.floor(s / 3600);
    const m = Math.floor((s % 3600) / 60);
    return `${h}h ${m}m`;
  }

  const num = (v, unit) => v != null ? v.toFixed(1) + unit : '—';

  const HEADERS = [
    '#', 'Profile', 'Started', 'Duration', 'Readings',
    'Temp min', 'Temp avg', 'Temp max',
    'RH min', 'RH avg', 'RH max', 'Breaches',
  ];

  const cell = { padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 13 };

  return (
    <div>
      {/* Header */}
      <div className="page-header">
        <div>
          <div className="page-eyebrow">Recorded History</div>
          <h1 className="page-title">Monitoring Log</h1>
          <div className="page-subtitle">
            {selectedDevice ? `Device: ${selectedDevice}` : 'No device selected'} ·{' '}
            {apiReachable === false ? 'API offline' : `${periods.length} period${periods.length !== 1 ? 's' : ''}`}
          </div>
        </div>
        <button className="btn" onClick={handleRefresh} disabled={refreshing}>
          <Icon name="refresh" size={14} />
          {refreshing ? 'Refreshing…' : 'Refresh'}
        </button>
      </div>

      {!apiReachable && (
        <div className="card" style={{ marginBottom: 24, padding: 20 }}>
          <div className="row gap-8 items-center text-ink-3">
            <Icon name="activity" size={16} />
            <span className="text-sm">
              Backend API is offline. Start the service with the <span className="mono">--api</span> flag to see monitoring periods here.
            </span>
          </div>
        </div>
      )}

      {apiReachable && periods.length === 0 && (
        <div className="card" style={{ padding: 32, textAlign: 'center', color: 'var(--ink-3)' }}>
          <div style={{ marginBottom: 8 }}><Icon name="history" size={32} /></div>
          <div className="text-sm">No monitoring periods yet. A period is created automatically when the service receives its first reading from a device.</div>
        </div>
      )}

      {periods.length > 0 && (
        <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead style={{ background: 'var(--bg-sunken)' }}>
                <tr>
                  {HEADERS.map(h => (
                    <th key={h} style={{
                      textAlign: 'left', fontSize: 11, textTransform: 'uppercase',
                      letterSpacing: '0.08em', color: 'var(--ink-4)',
                      padding: '12px 16px', fontWeight: 600, whiteSpace: 'nowrap',
                      borderBottom: '1px solid var(--line)',
                    }}>
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {periods.map((p, i) => {
                  const hasBreach = p.breach_count > 0;
                  return (
                    <tr key={p.id || i} style={{ borderTop: i > 0 ? '1px solid var(--line)' : 'none' }}>
                      <td style={{ ...cell, fontSize: 12, color: 'var(--ink-4)' }}>{p.id}</td>
                      <td style={{ padding: '12px 16px' }}>
                        <ProfileBadge profile={p.profile} />
                      </td>
                      <td style={{ ...cell, fontSize: 12, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>
                        {formatTs(p.start_time)}
                      </td>
                      <td style={{ ...cell, fontSize: 12, color: 'var(--ink-3)' }}>
                        {fmtDuration(p.start_time, p.end_time || (Date.now() / 1000))}
                      </td>
                      <td style={cell}>{p.total_readings ?? '—'}</td>

                      <td style={{ ...cell, color: 'var(--ccp-cold)' }}>{num(p.min_temp_c, '°C')}</td>
                      <td style={cell}>{num(p.avg_temp_c, '°C')}</td>
                      <td style={{ ...cell, color: 'var(--ccp-cooking)' }}>{num(p.max_temp_c, '°C')}</td>

                      <td style={{ ...cell, color: 'var(--ccp-cold)' }}>{num(p.min_rh, '%')}</td>
                      <td style={cell}>{num(p.avg_rh, '%')}</td>
                      <td style={{ ...cell, color: 'var(--ccp-cooking)' }}>{num(p.max_rh, '%')}</td>

                      <td style={{ padding: '12px 16px' }}>
                        {hasBreach ? (
                          <span style={{
                            display: 'inline-flex', alignItems: 'center', gap: 4,
                            fontSize: 12, fontWeight: 600, padding: '2px 8px', borderRadius: 100,
                            background: 'oklch(0.55 0.2 25 / 0.1)', color: 'var(--status-breach)',
                          }}>
                            <Icon name="alert-triangle" size={11} />
                            {p.breach_count}
                          </span>
                        ) : (
                          <span style={{
                            display: 'inline-flex', alignItems: 'center', gap: 4,
                            fontSize: 12, fontWeight: 600, padding: '2px 8px', borderRadius: 100,
                            background: 'oklch(0.58 0.17 145 / 0.1)', color: 'var(--status-safe)',
                          }}>
                            <Icon name="check-circle" size={11} />
                            OK
                          </span>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
