/* eslint-disable */
/* =========================================================
   TEO IoT Dashboard — Device Detail screen.
   ========================================================= */

const CommandPanel = ({ device, onCommand }) => {
  const commands = [
    { id:'restart',    label:'Restart device',       kind:'primary',  hint:'Soft reboot · ~30s downtime' },
    { id:'calibrate',  label:'Calibrate sensors',    kind:'ghost',    hint:'Re-baseline against reference' },
    { id:'diagnostics',label:'Run diagnostics',      kind:'ghost',    hint:'Full health check, ~2 min' },
    { id:'firmware',   label:'Update firmware',      kind:'ghost',    hint:'Latest: 2.4.1' },
    { id:'trip',       label:'Trip · open contactor',kind:'danger',   hint:'Emergency only · audit logged' },
  ];
  return (
    <Card pad={0}>
      <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
        <Eyebrow>Commands</Eyebrow>
        <div style={{ fontSize:16, color:'#0A0F1F', marginTop:6 }}>Issue control action</div>
      </div>
      <div style={{ padding:'16px 24px', display:'flex', flexDirection:'column', gap:10 }}>
        {commands.map(c => (
          <div key={c.id} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 0', borderBottom:'1px solid #EDEDED' }}>
            <div>
              <div style={{ fontSize:14, color:'#0A0F1F' }}>{c.label}</div>
              <div style={{ fontSize:12, color:'#5A5E6E', marginTop:2 }}>{c.hint}</div>
            </div>
            <Button kind={c.kind} onClick={() => onCommand(device, c.id)}>{c.id==='trip' ? 'Trip' : 'Run'}</Button>
          </div>
        ))}
      </div>
    </Card>
  );
};

const FirmwarePanel = ({ device }) => (
  <Card pad={0}>
    <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
      <Eyebrow>Firmware</Eyebrow>
      <div style={{ fontSize:16, color:'#0A0F1F', marginTop:6 }}>Versioning & history</div>
    </div>
    <div style={{ padding:'16px 24px' }}>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, marginBottom:16 }}>
        <div>
          <div style={{ fontSize:12, color:'#5A5E6E' }}>Current</div>
          <div style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:18, color:'#0A0F1F', marginTop:2 }}>{device.firmware}</div>
        </div>
        <div>
          <div style={{ fontSize:12, color:'#5A5E6E' }}>Available</div>
          <div style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:18, color:'#3A6FF8', marginTop:2 }}>{device.firmware.replace(/\d+$/, n => Number(n)+1)}</div>
        </div>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:8, fontSize:13, color:'#0A0F1F' }}>
        {[
          [device.firmware, 'Apr 02', 'Installed'],
          [device.firmware.replace(/\d+$/, n => Number(n)-1 + ''), 'Feb 18', 'Rolled back'],
          [device.firmware.replace(/(\d+)\.\d+\.\d+/, (_,m) => `${m}.3.0`), 'Jan 04', 'Installed'],
        ].map((r,i) => (
          <div key={i} style={{ display:'grid', gridTemplateColumns:'90px 80px 1fr', padding:'10px 0', borderBottom:'1px solid #EDEDED' }}>
            <span style={{ fontFamily:'IBM Plex Mono, monospace' }}>{r[0]}</span>
            <span style={{ color:'#5A5E6E' }}>{r[1]}</span>
            <span style={{ color:'#242739' }}>{r[2]}</span>
          </div>
        ))}
      </div>
    </div>
  </Card>
);

const IncidentsPanel = ({ device }) => (
  <Card pad={0}>
    <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
      <Eyebrow>Recent incidents</Eyebrow>
    </div>
    <div style={{ padding:0 }}>
      {[
        ['INC-8812','Latency elevated',       'Resolved','08:12'],
        ['INC-8811','Scheduled maintenance',  'Closed','Apr 12'],
        ['INC-8799','Sync drift · re-aligned','Closed','Apr 03'],
      ].map(r => (
        <div key={r[0]} style={{ display:'grid', gridTemplateColumns:'110px 1fr 120px 80px', padding:'14px 24px', borderBottom:'1px solid #EDEDED', fontSize:14, color:'#0A0F1F', alignItems:'center' }}>
          <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:13 }}>{r[0]}</span>
          <span>{r[1]}</span>
          <span style={{ color:'#242739' }}>{r[2]}</span>
          <span style={{ color:'#5A5E6E', textAlign:'right', fontSize:13 }}>{r[3]}</span>
        </div>
      ))}
    </div>
  </Card>
);

const LiveLog = ({ device }) => {
  const logs = [
    ['12:42:08','INFO', `${device.id} sync complete · ${device.metric.value} ${device.metric.unit}`],
    ['12:41:51','INFO', `Telemetry batch · ${Math.round(device.metric.value*10)} samples`],
    ['12:40:12','INFO', `Heartbeat OK · rtt 84ms`],
    ['12:38:44','WARN', `Threshold approach · ${device.metric.value} ${device.metric.unit}`],
    ['12:35:09','INFO', `Calibration drift · within tolerance`],
    ['12:32:00','INFO', `Mesh peer GW-01-01 reachable`],
  ];
  const color = { INFO:'rgba(255,255,255,.6)', WARN:'#E0A13B', ERR:'#C44A4A' };
  return (
    <Card dark pad={24} style={{ height:'100%' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
        <div>
          <div style={{ fontSize:11, letterSpacing:'0.08em', textTransform:'uppercase', color:'rgba(255,255,255,.5)' }}>Device stream</div>
          <div style={{ fontSize:18, fontWeight:400, marginTop:4, display:'flex', alignItems:'center', gap:8 }}>
            <span style={{ width:6, height:6, borderRadius:'50%', background:'#7A9CFF', boxShadow:'0 0 0 4px rgba(122,156,255,.25)' }} />
            Following · {device.id}
          </div>
        </div>
      </div>
      <div style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:12, lineHeight:1.7 }}>
        {logs.map(([t,lvl,msg],i) => (
          <div key={i} style={{ display:'grid', gridTemplateColumns:'70px 50px 1fr', gap:12, padding:'6px 0', borderBottom:'1px solid rgba(255,255,255,.08)' }}>
            <span style={{ color:'rgba(255,255,255,.4)' }}>{t}</span>
            <span style={{ color:color[lvl] }}>{lvl}</span>
            <span style={{ color:'rgba(255,255,255,.85)' }}>{msg}</span>
          </div>
        ))}
      </div>
    </Card>
  );
};

const DeviceDetail = ({ device, onBack, onCommand }) => {
  if (!device) return null;
  const [range, setRange] = React.useState('24h');
  const m = device.metric;
  const primary = MOCK.makeSeries(m.value, m.value*0.04);
  const secondary = MOCK.makeSeries(m.value*0.6, m.value*0.05);
  const series = [
    { label:m.label, unit:m.unit, color:'#3A6FF8', data: primary },
    { label:'Internal temp', unit:'°C', color:'#878787', data: secondary },
  ];

  return (
    <div data-pad-md style={{ padding:'32px', background:'#F6F7F9', minHeight:'calc(100vh - 73px)' }}>
      {/* Breadcrumb */}
      <button onClick={onBack} style={{
        background:'transparent', border:'none', color:'#0A0F1F', padding:0,
        marginBottom:24, cursor:'pointer',
        font:"400 13px 'IBM Plex Sans'", letterSpacing:'-0.027em', textTransform:'uppercase'
      }}>← All devices</button>

      {/* Header */}
      <div style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:24, alignItems:'start', marginBottom:32 }}>
        <div>
          <div style={{ fontSize:11, letterSpacing:'0.08em', textTransform:'uppercase', color:'#3A6FF8', fontFamily:'IBM Plex Mono, monospace' }}>{device.id}</div>
          <h1 style={{ fontSize:40, fontWeight:300, letterSpacing:'-0.06em', lineHeight:1.1, color:'#0A0F1F', margin:'10px 0 12px' }}>{device.name}</h1>
          <div style={{ display:'flex', gap:16, alignItems:'center', color:'#242739', fontSize:14 }}>
            <StatusPill state={device.state} />
            <Hairline vertical />
            <span style={{ textTransform:'capitalize' }}>{device.kind}</span>
            <Hairline vertical />
            <span>{device.zone}</span>
            <Hairline vertical />
            <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:12 }}>fw {device.firmware}</span>
          </div>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <Button kind="ghost" onClick={() => onCommand(device, 'diagnostics')}>Run diagnostics</Button>
          <Button kind="primary" onClick={() => onCommand(device, 'ack')}>Acknowledge</Button>
        </div>
      </div>

      {/* Top row: live gauges */}
      <div data-kpi-strip style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', background:'#FFF', border:'1px solid #EDEDED', borderBottom:'none' }}>
        <div style={{ padding:24, borderRight:'1px solid #EDEDED', display:'flex', flexDirection:'column', alignItems:'center', gap:12 }}>
          <Gauge value={m.value} min={m.min} max={m.max} unit={m.unit} label={m.label} warn={m.warn} crit={m.crit} />
        </div>
        <MetricTile label="Heartbeat"     value="84"  unit="ms"   delta="-12%" sub="rolling 5m" />
        <MetricTile label="Uptime"        value="98.7" unit="%"   delta="+0.2" sub="30-day" />
        <MetricTile label="Last sync"     value="2"   unit="s ago" sub="auto-refresh" />
      </div>

      {/* Telemetry chart */}
      <div style={{ background:'#FFF', borderTop:'1px solid #EDEDED', borderBottom:'1px solid #EDEDED' }}>
        <TimeSeriesChart series={series} height={220} range={range} onRange={setRange} />
      </div>

      {/* Lower grid */}
      <div data-collapse-md style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:24, marginTop:24 }}>
        <div style={{ display:'flex', flexDirection:'column', gap:24 }}>
          <CommandPanel device={device} onCommand={onCommand} />
          <IncidentsPanel device={device} />
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:24 }}>
          <FirmwarePanel device={device} />
          <LiveLog device={device} />
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { DeviceDetail });
