/* eslint-disable */
/* =========================================================
   TwinPreview — functional mini digital-twin for the homepage.
   Channel toggle (Comfort/Temp/Humidity/Occupancy) recolours
   rooms by status band; rooms + devices are labelled; clicking
   a device deep-links into the full twin with it selected.
   Reads window.SITE_BUILT.
   ========================================================= */
const TwinPreview = ({ onNav }) => {
  const B = window.SITE_BUILT;
  if (!B || !B.model) return null;
  const [chan, setChan] = React.useState('comfort');
  const model = B.model, env = model.envelope_mm, W = env.width, H = env.depth, PAD = 700;
  const fy = y => H - y;
  const BANDc = {
    nominal:{ fill:'rgba(46,158,107,0.16)', stroke:'#2E9E6B', dot:'#2E9E6B', label:'Nominal' },
    watch:  { fill:'rgba(224,161,59,0.22)', stroke:'#D99A2B', dot:'#E0A13B', label:'Watch' },
    out:    { fill:'rgba(196,74,74,0.18)',  stroke:'#C44A4A', dot:'#C44A4A', label:'Alert' },
    nodata: { fill:'rgba(154,163,178,0.14)',stroke:'#B8C0CE', dot:'#9AA3B2', label:'Offline' },
  };
  const SB = { ok:'nominal', warn:'watch', crit:'out', down:'nodata', idle:'nodata' };
  const chanKey = chan === 'comfort' ? 'comfort' : chan;
  const rb = rm => (B.roomStatus[rm.id] && B.roomStatus[rm.id].band[chanKey]) || 'nodata';
  const devs = window.MOCK.DEVICES;
  const open = (id) => { if (id) window.__TWIN_SELECT = id; onNav && onNav('twin'); };
  const TYPE = { sensor:{sq:false,r:430}, door:{sq:true,r:410}, anchor:{sq:false,r:470}, gateway:{sq:true,r:470}, router:{sq:true,r:410} };
  const seg = (opts) => (
    <div style={{ display:'inline-flex', border:'1px solid #E2E5EC', borderRadius:0, overflow:'hidden' }}>
      {opts.map(o => <button key={o.k} onClick={()=>setChan(o.k)} style={{ padding:'6px 11px', border:'none', background:chan===o.k?'#0A0F1F':'#FFF', color:chan===o.k?'#FFF':'#3B4150', font:"500 12px 'IBM Plex Sans'", cursor:'pointer' }}>{o.label}</button>)}
    </div>
  );

  return (
    <Card pad={0}>
      <div style={{ padding:'14px 20px', borderBottom:'1px solid #EDEDED', display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:12 }}>
        <div>
          <Eyebrow>Live floor plan</Eyebrow>
          <div style={{ fontSize:16, color:'#0A0F1F', marginTop:4 }}>Exchange Quay — Level 02</div>
        </div>
        <div style={{ display:'flex', gap:12, alignItems:'center', flexWrap:'wrap' }}>
          {seg([{k:'comfort',label:'Comfort'},{k:'temp',label:'Temp'},{k:'humidity',label:'Humidity'},{k:'occupancy',label:'Occupancy'}])}
          <Button kind="ghost" onClick={()=>open(null)}>Open full twin →</Button>
        </div>
      </div>

      <div style={{ padding:'8px 20px', borderBottom:'1px solid #EDEDED', display:'flex', gap:14, flexWrap:'wrap' }}>
        {['nominal','watch','out','nodata'].map(k => (
          <span key={k} style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:11.5, color:'#5A5E6E' }}>
            <span style={{ width:9, height:9, borderRadius:2, background:BANDc[k].dot }} />{BANDc[k].label}
          </span>
        ))}
        <span style={{ marginLeft:'auto', fontSize:11.5, color:'#9AA3B2' }}>Click a device to inspect it</span>
      </div>

      <div style={{ padding:16, background:'#FBFCFD' }}>
        <svg viewBox={`${-PAD} ${-PAD} ${W + 2*PAD} ${H + 2*PAD}`} role="img" aria-label="Live floor plan, rooms shaded by the selected channel; click a device to open it in the full twin"
          style={{ width:'100%', height:'auto', maxHeight:'52vh', display:'block' }} preserveAspectRatio="xMidYMid meet">
          {/* rooms + labels */}
          {model.rooms.map(rm => {
            const bd = BANDc[rb(rm)], pts = rm.polygon_mm.map(p => `${p[0]},${fy(p[1])}`).join(' ');
            const topY = Math.max.apply(null, rm.polygon_mm.map(p => p[1]));
            return (
              <g key={rm.id}>
                <polygon points={pts} fill={bd.fill} stroke={bd.stroke} strokeWidth={rm.enclosed ? 42 : 30} strokeDasharray={!rm.enclosed ? '150 110' : undefined} />
                <text x={rm.centroid_mm[0]} y={fy(topY) + 430} textAnchor="middle" fill="#5A6072" style={{ font:"500 300px 'IBM Plex Sans'" }}>{rm.name}</text>
              </g>
            );
          })}
          {/* device markers (labelled, clickable) */}
          {devs.map(d => {
            const bd = BANDc[SB[d.state] || 'nominal'], t = TYPE[d.kind] || TYPE.sensor, x = d.position_mm[0], y = fy(d.position_mm[1]);
            const shift = d.kind === 'router' ? 700 : 0;
            return (
              <g key={d.id} transform={`translate(${x + shift},${y})`} style={{ cursor:'pointer' }} onClick={()=>open(d.id)}>
                <title>{d.id + ' · ' + d.zone + ' · ' + (bd.label || '')}</title>
                {t.sq
                  ? <rect x={-t.r} y={-t.r} width={t.r*2} height={t.r*2} rx={100} fill={bd.dot} stroke="#FFF" strokeWidth={70} />
                  : <circle r={t.r} fill={bd.dot} stroke="#FFF" strokeWidth={70} />}
                <text textAnchor="middle" dy={t.r*0.34} fill="#FFF" style={{ font:`600 ${Math.round(t.r*0.8)}px 'IBM Plex Sans'` }}>{d.id}</text>
              </g>
            );
          })}
        </svg>
      </div>
    </Card>
  );
};

Object.assign(window, { TwinPreview });
