// Events & Alerts page
const EventsPage = () => {
  const [tab, setTab] = useState('active');
  const [selected, setSelected] = useState(null);
  const [sevFilter, setSevFilter] = useState('all');

  const events = ALL_EVENTS.filter(e => sevFilter === 'all' || e.sev === sevFilter);

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Events & Alerts</h1>
          <div className="page-sub">12 active · 3 critical · 2 escalated · routing engine healthy</div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="filter" size={12}/>Filter</button>
          <button className="btn"><Icon name="settings" size={12}/>Routing rules</button>
          <button className="btn primary"><Icon name="plus" size={12}/>New rule</button>
        </div>
      </div>

      <div className="tabs">
        {[
          { id: 'active', label: 'Active', count: 12 },
          { id: 'ack', label: 'Acknowledged', count: 8 },
          { id: 'resolved', label: 'Resolved', count: 184 },
          { id: 'all', label: 'All events' },
          { id: 'rules', label: 'Routing rules' },
        ].map(t => (
          <div key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={()=>setTab(t.id)}>
            {t.label}{t.count !== undefined && <span className="count">{t.count}</span>}
          </div>
        ))}
      </div>

      <div className="page-body">
        {/* Severity filter row */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 12, alignItems: 'center' }}>
          <SegControl value={sevFilter} onChange={setSevFilter} options={[
            { label: 'All', value: 'all' },
            { label: 'Critical · 3', value: 'critical' },
            { label: 'Warning · 5', value: 'warn' },
            { label: 'Info · 4', value: 'info' },
          ]}/>
          <input className="input" placeholder="Search events…" style={{ width: 240 }}/>
          <select className="select"><option>All machines</option></select>
          <select className="select"><option>All sources</option></select>
          <div style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-3)' }} className="mono">{events.length} events</div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: selected ? '1fr 440px' : '1fr', gap: 12 }}>
          <div className="card" style={{ overflow: 'hidden' }}>
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ width: 80 }}>Severity</th>
                  <th>Event</th>
                  <th>Source</th>
                  <th>Status</th>
                  <th>Assignee</th>
                  <th>Triggered</th>
                  <th>Age</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {events.map((e, i) => {
                  const c = sevConfig[e.sev];
                  return (
                    <tr key={i} className={selected === i ? 'selected' : ''} onClick={()=>setSelected(i === selected ? null : i)} style={{ cursor: 'pointer' }}>
                      <td>
                        <span className="pill" style={{ background: `color-mix(in srgb, ${c.color} 12%, transparent)`, color: c.color }}>
                          <span className="dot"/>{e.sev}
                        </span>
                      </td>
                      <td>
                        <div style={{ fontWeight: 500, fontSize: 12 }}>{e.title}</div>
                        <div style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 1 }} className="mono">{e.id}</div>
                      </td>
                      <td className="mono">{e.machine}</td>
                      <td><StatusBadge status={e.status}/></td>
                      <td>
                        {e.assignee ? (
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <div className="avatar" style={{ width: 18, height: 18, fontSize: 9, background: e.color || 'var(--accent)' }}>{e.assignee.split(' ').map(s=>s[0]).join('')}</div>
                            <span style={{ fontSize: 11.5 }}>{e.assignee}</span>
                          </div>
                        ) : <span style={{ color: 'var(--text-3)', fontSize: 11 }}>Unassigned</span>}
                      </td>
                      <td className="mono" style={{ fontSize: 11 }}>{e.time}</td>
                      <td className="mono" style={{ fontSize: 11, color: 'var(--text-2)' }}>{e.age}</td>
                      <td><button className="btn ghost icon sm" onClick={ev=>ev.stopPropagation()}><Icon name="more" size={12}/></button></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {selected !== null && <EventDetail event={events[selected]} onClose={()=>setSelected(null)}/>}
        </div>

        {/* Timeline visualization */}
        <div className="card" style={{ marginTop: 12 }}>
          <div className="card-header">
            <div className="card-title">Event timeline · last 6 hours</div>
            <div style={{ display: 'flex', gap: 12, fontSize: 11, marginLeft: 16 }}>
              <Legend color="var(--red)" label="Critical"/>
              <Legend color="var(--accent)" label="Warning"/>
              <Legend color="var(--blue)" label="Info"/>
            </div>
          </div>
          <div style={{ padding: 14 }}>
            <Timeline/>
          </div>
        </div>
      </div>
    </>
  );
};

const StatusBadge = ({ status }) => {
  const map = {
    'open': { c: 'var(--red)', l: 'OPEN' },
    'acknowledged': { c: 'var(--accent)', l: 'ACK' },
    'investigating': { c: 'var(--blue)', l: 'INVESTIGATING' },
    'escalated': { c: 'var(--purple)', l: 'ESCALATED' },
    'resolved': { c: 'var(--green)', l: 'RESOLVED' },
  };
  const m = map[status] || map.open;
  return <span className="pill" style={{ background: `color-mix(in srgb, ${m.c} 12%, transparent)`, color: m.c }}><span className="dot"/>{m.l}</span>;
};

const ALL_EVENTS = [
  { id: 'EVT-2024-08471', sev: 'critical', title: 'Spindle temperature exceeded 85°C', machine: 'CNC-04', status: 'escalated', assignee: 'P. Kulkarni', time: '14:31:02', age: '2m', color: '#7c3aed' },
  { id: 'EVT-2024-08470', sev: 'critical', title: 'Emergency stop activated', machine: 'WELD-07', status: 'investigating', assignee: 'P. Kulkarni', time: '14:18:44', age: '14m', color: '#7c3aed' },
  { id: 'EVT-2024-08469', sev: 'critical', title: 'Servo drive fault — code E-0312', machine: 'CNC-01', status: 'acknowledged', assignee: 'R. Mehta', time: '13:30:18', age: '1h 2m', color: '#2563eb' },
  { id: 'EVT-2024-08468', sev: 'warn', title: 'Cycle time variance > 8%', machine: 'PRESS-12', status: 'investigating', assignee: 'A. Desai', time: '14:28:11', age: '4m', color: '#16a34a' },
  { id: 'EVT-2024-08467', sev: 'warn', title: 'Tool wear > 78% threshold', machine: 'CNC-02', status: 'open', assignee: null, time: '14:11:38', age: '21m' },
  { id: 'EVT-2024-08466', sev: 'warn', title: 'Coolant level low — 18%', machine: 'CNC-04', status: 'acknowledged', assignee: 'A. Desai', time: '13:52:05', age: '40m', color: '#16a34a' },
  { id: 'EVT-2024-08465', sev: 'warn', title: 'Vibration above baseline', machine: 'PRESS-08', status: 'open', assignee: null, time: '13:42:00', age: '50m' },
  { id: 'EVT-2024-08464', sev: 'warn', title: 'Quality drift detected', machine: 'ASM-02', status: 'investigating', assignee: 'S. Joshi', time: '13:14:27', age: '1h 18m', color: '#dc2626' },
  { id: 'EVT-2024-08463', sev: 'info', title: 'Shift changeover complete', machine: 'PACK-03', status: 'resolved', assignee: 'S. Joshi', time: '14:22:00', age: '10m', color: '#dc2626' },
  { id: 'EVT-2024-08462', sev: 'info', title: 'Material refill request', machine: 'PACK-01', status: 'open', assignee: null, time: '13:58:30', age: '34m' },
  { id: 'EVT-2024-08461', sev: 'info', title: 'Operator log entry', machine: 'PRESS-08', status: 'resolved', assignee: 'R. Mehta', time: '13:38:14', age: '54m', color: '#2563eb' },
  { id: 'EVT-2024-08460', sev: 'info', title: 'Maintenance window scheduled', machine: 'CNC-03', status: 'acknowledged', assignee: 'A. Desai', time: '13:00:00', age: '1h 32m', color: '#16a34a' },
];

const EventDetail = ({ event, onClose }) => (
  <div className="card" style={{ display: 'flex', flexDirection: 'column' }}>
    <div className="card-header">
      <div className="card-title">{event.title}</div>
      <button className="btn ghost icon sm" style={{ marginLeft: 'auto' }} onClick={onClose}><Icon name="x" size={12}/></button>
    </div>
    <div style={{ padding: 14, overflowY: 'auto' }}>
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
        <span className="pill" style={{ background: `color-mix(in srgb, ${sevConfig[event.sev].color} 12%, transparent)`, color: sevConfig[event.sev].color }}>
          <span className="dot"/>{event.sev}
        </span>
        <StatusBadge status={event.status}/>
        <span className="pill mono">{event.id}</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 14, fontSize: 11.5 }}>
        <DetailRow label="Source" value={event.machine}/>
        <DetailRow label="Triggered" value={event.time}/>
        <DetailRow label="Age" value={event.age}/>
        <DetailRow label="Assignee" value={event.assignee || 'Unassigned'}/>
        <DetailRow label="Sensor" value="TC-04 / spindle"/>
        <DetailRow label="Threshold" value="85.0 °C"/>
        <DetailRow label="Last value" value="87.3 °C"/>
        <DetailRow label="Rule" value="High temp escalation"/>
      </div>

      <div className="sec-heading">Escalation chain</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
        <EscalationStep n={1} who="Operator on duty" status="notified" time="14:31:05"/>
        <EscalationStep n={2} who="Maintenance lead" status="notified" time="14:32:30" current/>
        <EscalationStep n={3} who="Plant supervisor" status="pending" eta="14:36:30"/>
        <EscalationStep n={4} who="Plant manager" status="pending" eta="14:41:30"/>
      </div>

      <div className="sec-heading">Telemetry at trigger</div>
      <div style={{ marginBottom: 16, padding: 10, border: '1px solid var(--line)', borderRadius: 4, background: 'var(--panel-2)' }}>
        <LineChart w={380} h={100} data={series(40, 99, 75, 8, 0.4)} color="var(--red)"/>
      </div>

      <div className="sec-heading">Activity</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 11.5 }}>
        <ActivityItem time="14:32" who="System" action="Notification routed to maintenance lead via SMS, Slack"/>
        <ActivityItem time="14:31" who="System" action="Auto-escalated — temp >2°C above threshold for 30s"/>
        <ActivityItem time="14:31" who="System" action="Event triggered by rule 'High temp escalation' v3"/>
      </div>

      <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
        <button className="btn primary"><Icon name="check" size={12}/>Acknowledge</button>
        <button className="btn"><Icon name="users" size={12}/>Assign</button>
        <button className="btn"><Icon name="zap" size={12}/>Escalate</button>
        <button className="btn"><Icon name="wrench" size={12}/>Create ticket</button>
      </div>
    </div>
  </div>
);

const DetailRow = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
    <div className="mono" style={{ marginTop: 2, color: 'var(--text)' }}>{value}</div>
  </div>
);

const EscalationStep = ({ n, who, status, time, eta, current }) => {
  const colors = { notified: 'var(--green)', pending: 'var(--text-4)', skipped: 'var(--text-4)' };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', background: current ? 'color-mix(in srgb, var(--accent) 6%, transparent)' : 'var(--panel-2)', border: `1px solid ${current ? 'color-mix(in srgb, var(--accent) 30%, transparent)' : 'var(--line)'}`, borderRadius: 4 }}>
      <div className="mono" style={{ width: 18, height: 18, borderRadius: 9, background: colors[status], color: 'white', fontSize: 10, display: 'grid', placeItems: 'center', fontWeight: 600 }}>{n}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 12, fontWeight: 500 }}>{who}</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)' }}>
          {status === 'notified' ? `notified ${time}` : `escalates at ${eta}`}
        </div>
      </div>
      {current && <span className="pill warn">current</span>}
    </div>
  );
};

const ActivityItem = ({ time, who, action }) => (
  <div style={{ display: 'flex', gap: 8, paddingLeft: 12, borderLeft: '2px solid var(--line)' }}>
    <div className="mono" style={{ fontSize: 10, color: 'var(--text-3)', width: 38 }}>{time}</div>
    <div>
      <span style={{ fontWeight: 500 }}>{who}</span> <span style={{ color: 'var(--text-2)' }}>{action}</span>
    </div>
  </div>
);

const Timeline = () => {
  const events = useMemo(() => {
    const r = seed(123);
    return Array.from({ length: 38 }, (_, i) => ({
      x: r() * 100,
      y: Math.floor(r() * 5),
      sev: ['critical','warn','info','warn','info'][Math.floor(r()*5)],
    }));
  }, []);
  const sevColor = { critical: 'var(--red)', warn: 'var(--accent)', info: 'var(--blue)' };
  return (
    <div style={{ position: 'relative', height: 100, paddingTop: 8 }}>
      <svg width="100%" height={88} preserveAspectRatio="none" viewBox="0 0 1000 88">
        {[0,1,2,3,4].map(y => (
          <line key={y} x1="0" y1={10 + y * 18} x2="1000" y2={10 + y * 18} stroke="var(--line)" strokeDasharray="2 4"/>
        ))}
        {events.map((e, i) => (
          <circle key={i} cx={e.x * 10} cy={10 + e.y * 18} r="4" fill={sevColor[e.sev]} opacity="0.85"/>
        ))}
      </svg>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10.5, color: 'var(--text-3)', marginTop: 6 }} className="mono">
        {['08:30','09:30','10:30','11:30','12:30','13:30','14:30'].map(t => <span key={t}>{t}</span>)}
      </div>
    </div>
  );
};

window.EventsPage = EventsPage;
