/* =============================================================
   CoreIQ Office — Electronic Shelf Labels (ESL)
   Manage device fleet, price sync, layout templates, batch updates
   ============================================================= */
const { useState: eslUseState, useMemo: eslUseMemo } = React;

// ESL sample data
const ESL_DEVICES_SUMMARY = {
  total: 1842,
  online: 1804,
  lowBattery: 18,
  needsSync: 11,
  offline: 9,
};

const ESL_GATEWAYS = [
  { id: "GW-CMW-1", store: "S-001", model: "SES-imagotag · AP V2", devices: 720, signal: "−54 dBm", status: "online" },
  { id: "GW-CMW-2", store: "S-001", model: "SES-imagotag · AP V2", devices: 240, signal: "−61 dBm", status: "online" },
  { id: "GW-GLI-1", store: "S-002", model: "SES-imagotag · AP V2", devices: 410, signal: "−58 dBm", status: "online" },
  { id: "GW-RNG-1", store: "S-003", model: "SES-imagotag · AP V2", devices: 472, signal: "−52 dBm", status: "online" },
];

const ESL_TEMPLATES = [
  { id: "esl-shelf",   name: "Shelf-edge · 2.9″",   size: "296×128 px", uses: 1480, fields: ["name","strength","price","unitPrice","barcode"], color: false },
  { id: "esl-promo",   name: "Promo highlight · 2.9″", size: "296×128 px", uses: 142,  fields: ["promoBadge","name","priceWas","priceNow","ends"], color: true },
  { id: "esl-bin",     name: "Dispensary bin · 4.2″", size: "400×300 px", uses: 158,  fields: ["name","strength","schedule","location","barcode"], color: false },
  { id: "esl-ndss",    name: "NDSS small · 1.6″",   size: "200×96 px",  uses: 38,   fields: ["name","copay","fullPrice","eligible"], color: false },
  { id: "esl-osa",     name: "On-shelf availability · 2.9″", size: "296×128 px", uses: 24, fields: ["name","stockStatus","reorderETA"], color: true },
];

const ESL_RECENT_UPDATES = [
  { ts: "Today 14:18", title: "Summer Saver · Skincare 30%",     scope: "Skincare category · all stores", items: 142, status: "delivered", elapsed: "4m 12s" },
  { ts: "Today 11:48", title: "Atorvastatin price refresh",      scope: "Atorvastatin 40mg · all stores",  items: 3,   status: "delivered", elapsed: "52s" },
  { ts: "Today 09:14", title: "PO-4422 receive · price changes", scope: "Camberwell · 4 SKUs",             items: 4,   status: "delivered", elapsed: "1m 04s" },
  { ts: "Yesterday",   title: "Mother's Day promo · ended",      scope: "Skincare · revert to retail",     items: 142, status: "delivered", elapsed: "3m 48s" },
  { ts: "Yesterday",   title: "NDSS sensor price update",        scope: "FreeStyle Libre 2 · 3 stores",    items: 3,   status: "partial",   elapsed: "—", note: "1 ESL offline at Ringwood" },
  { ts: "23/05/2026",  title: "Vitamins · weekly refresh",       scope: "All vitamins · all stores",       items: 88,  status: "delivered", elapsed: "5m 30s" },
];

// =================================================================
// ESL MANAGEMENT
// =================================================================
function ESLs() {
  const { pushToast } = window.useOffice();
  const [tab, setTab] = eslUseState("fleet");
  const STORE_COLOURS = { "S-001": "var(--teal-700)", "S-002": "var(--navy-600)", "S-003": "var(--violet-600)" };

  return (
    <div className="off-screen">
      <header className="off-screen-header">
        <div className="off-screen-header-meta">
          <span className="off-screen-eyebrow">Head-office function · SES-imagotag</span>
          <h2 className="off-screen-title">Electronic shelf labels</h2>
        </div>
        <div className="off-screen-actions">
          <button className="btn btn--ghost btn--sm">Diagnostics</button>
          <button className="btn btn--secondary btn--sm" onClick={() => pushToast({kind:'paid', icon:'transfer', title:'Sync triggered', meta:`${ESL_DEVICES_SUMMARY.needsSync} ESLs · refreshing`})}>
            <OIcon name="transfer"/> Sync all
          </button>
          <button className="btn btn--primary btn--sm">
            <OIcon name="plus"/> Push update
          </button>
        </div>
      </header>

      <div className="off-subtabs">
        <button className={"off-subtab" + (tab === "fleet" ? " off-subtab--active" : "")} onClick={() => setTab("fleet")}>Fleet</button>
        <button className={"off-subtab" + (tab === "updates" ? " off-subtab--active" : "")} onClick={() => setTab("updates")}>Update history</button>
        <button className={"off-subtab" + (tab === "templates" ? " off-subtab--active" : "")} onClick={() => setTab("templates")}>Templates</button>
        <button className={"off-subtab" + (tab === "rules" ? " off-subtab--active" : "")} onClick={() => setTab("rules")}>Auto-sync rules</button>
      </div>

      <div className="off-screen-body">
        <div className="off-kpi-grid">
          <KpiCard label="Devices deployed"  value={ESL_DEVICES_SUMMARY.total.toLocaleString()} delta={{text: ESL_GATEWAYS.length + " gateways · 3 stores"}}/>
          <KpiCard label="Online"            value={`${Math.round(ESL_DEVICES_SUMMARY.online/ESL_DEVICES_SUMMARY.total*100)}%`} delta={{dir:"up", text: `${ESL_DEVICES_SUMMARY.online.toLocaleString()} of ${ESL_DEVICES_SUMMARY.total.toLocaleString()}`}}/>
          <KpiCard label="Needs sync"        value={ESL_DEVICES_SUMMARY.needsSync} delta={{dir:"down", text: "Price-changed since last push"}}/>
          <KpiCard label="Low battery"       value={ESL_DEVICES_SUMMARY.lowBattery} delta={{dir:"down", text: "Replace within 30d"}}/>
        </div>

        {tab === "fleet" && (
          <>
            {/* Per-store fleet cards */}
            <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14, marginBottom:14}}>
              {OD.STORES.map(s => {
                const gw = ESL_GATEWAYS.filter(g => g.store === s.id);
                const devices = gw.reduce((sum, g) => sum + g.devices, 0);
                const lowBatt = s.id === "S-001" ? 8 : s.id === "S-002" ? 4 : 6;
                const needsSync = s.id === "S-001" ? 5 : s.id === "S-002" ? 2 : 4;
                const offline = s.id === "S-003" ? 4 : s.id === "S-001" ? 3 : 2;
                return (
                  <div key={s.id} className="off-card" style={{padding:0, overflow:'hidden'}}>
                    <div style={{padding:'14px 18px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:12}}>
                      <div className="off-topbar-store-av" style={{width:34, height:34, borderRadius:8, background:STORE_COLOURS[s.id], color:'#fff'}}>{s.code}</div>
                      <div style={{flex:1}}>
                        <div style={{fontWeight:600, fontSize:15, letterSpacing:'-0.01em'}}>{s.name}</div>
                        <div className="off-cell-mono off-muted" style={{fontSize:11}}>{gw.length} {gw.length === 1 ? "gateway" : "gateways"} · {devices.toLocaleString()} ESLs</div>
                      </div>
                      {offline > 2 || lowBatt > 6
                        ? <span className="badge badge--hold"><span className="badge-dot"/> Attention</span>
                        : <span className="badge badge--paid"><span className="badge-dot"/> Healthy</span>}
                    </div>
                    <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)'}}>
                      <div style={{padding:'12px 16px', borderRight:'1px solid var(--border)'}}>
                        <div style={{fontSize:10, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Online</div>
                        <div style={{fontSize:18, fontWeight:600, fontVariantNumeric:'tabular-nums', marginTop:2, color:'var(--paid)'}}>{(devices - offline).toLocaleString()}</div>
                      </div>
                      <div style={{padding:'12px 16px', borderRight:'1px solid var(--border)'}}>
                        <div style={{fontSize:10, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Needs sync</div>
                        <div style={{fontSize:18, fontWeight:600, fontVariantNumeric:'tabular-nums', marginTop:2, color:needsSync > 0 ? 'var(--hold-text)' : 'var(--text)'}}>{needsSync}</div>
                      </div>
                      <div style={{padding:'12px 16px'}}>
                        <div style={{fontSize:10, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>Low battery</div>
                        <div style={{fontSize:18, fontWeight:600, fontVariantNumeric:'tabular-nums', marginTop:2, color:lowBatt > 6 ? 'var(--hold-text)' : 'var(--text)'}}>{lowBatt}</div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Gateway table */}
            <div className="off-table">
              <div style={{padding:'10px 14px', borderBottom:'1px solid var(--border)', background:'var(--bg-subtle)', fontSize:11, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--text-subtle)', fontWeight:500}}>
                Gateways
              </div>
              <div className="off-grid" style={{gridTemplateColumns:'130px 1fr 1fr 130px 110px 110px 110px'}}>
                <div className="off-grid-headcell">Gateway</div>
                <div className="off-grid-headcell">Store</div>
                <div className="off-grid-headcell">Model</div>
                <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Devices</div>
                <div className="off-grid-headcell">Signal</div>
                <div className="off-grid-headcell">Last beacon</div>
                <div className="off-grid-headcell">Status</div>
                {ESL_GATEWAYS.map(g => (
                  <div key={g.id} className="off-grid-row">
                    <div className="off-grid-cell off-cell-mono off-cell-strong">{g.id}</div>
                    <div className="off-grid-cell">{findS(g.store)?.name}</div>
                    <div className="off-grid-cell off-muted">{g.model}</div>
                    <div className="off-grid-cell off-cell-num off-cell-strong">{g.devices.toLocaleString()}</div>
                    <div className="off-grid-cell off-cell-mono off-muted">{g.signal}</div>
                    <div className="off-grid-cell off-cell-mono off-muted">12s ago</div>
                    <div className="off-grid-cell"><span className="badge badge--paid"><span className="badge-dot"/> Online</span></div>
                  </div>
                ))}
              </div>
            </div>

            {/* Devices needing attention */}
            <div className="off-card" style={{marginTop:14}}>
              <div className="off-card-header">
                <h3 className="off-card-title">Devices needing attention</h3>
                <div style={{display:'flex', gap:8}}>
                  <button className="btn btn--ghost btn--sm">Battery report</button>
                  <button className="btn btn--secondary btn--sm">Locate offline (LED ping)</button>
                </div>
              </div>
              <div className="off-grid" style={{gridTemplateColumns:'120px 1.4fr 110px 110px 110px 110px 110px'}}>
                <div className="off-grid-headcell">ESL ID</div>
                <div className="off-grid-headcell">Bound product</div>
                <div className="off-grid-headcell">Store</div>
                <div className="off-grid-headcell">Location</div>
                <div className="off-grid-headcell">Battery</div>
                <div className="off-grid-headcell">Last sync</div>
                <div className="off-grid-headcell">Issue</div>
                {[
                  { id:"E-0188-A22", store:"S-001", prod:"Insulin Glargine 100u/ml", loc:"Fridge-1", batt:18, sync:"Today 11:48", issue:"low-battery" },
                  { id:"E-0188-B41", store:"S-001", prod:"Atorvastatin 40mg",        loc:"Disp-B2",  batt:24, sync:"Today 11:48", issue:"low-battery" },
                  { id:"E-0188-C18", store:"S-003", prod:"FreeStyle Libre 2",        loc:"Fridge-2", batt:62, sync:"22/05 14:20", issue:"needs-sync" },
                  { id:"E-0188-D04", store:"S-003", prod:"Salbutamol Spacer",       loc:"Resp-09",  batt:81, sync:"Yesterday",  issue:"offline" },
                  { id:"E-0188-E11", store:"S-002", prod:"Esomeprazole 20mg",        loc:"Disp-C1",  batt:74, sync:"Today 10:14", issue:"needs-sync" },
                  { id:"E-0188-F02", store:"S-001", prod:"Ventolin 100mcg inhaler", loc:"Resp-04",  batt:12, sync:"Today 14:18", issue:"low-battery" },
                ].map(d => (
                  <div key={d.id} className="off-grid-row">
                    <div className="off-grid-cell off-cell-mono off-cell-strong">{d.id}</div>
                    <div className="off-grid-cell">{d.prod}</div>
                    <div className="off-grid-cell off-mono">{findS(d.store)?.code}</div>
                    <div className="off-grid-cell off-mono off-muted">{d.loc}</div>
                    <div className="off-grid-cell">
                      <div style={{display:'flex', alignItems:'center', gap:8}}>
                        <div style={{width:30, height:8, background:'var(--bg-muted)', borderRadius:2, overflow:'hidden'}}>
                          <div style={{height:'100%', width:d.batt+'%', background: d.batt < 25 ? 'var(--void)' : d.batt < 50 ? 'var(--hold)' : 'var(--paid)'}}/>
                        </div>
                        <span className="off-cell-num" style={{color: d.batt < 25 ? 'var(--void)' : 'var(--text)'}}>{d.batt}%</span>
                      </div>
                    </div>
                    <div className="off-grid-cell off-cell-mono off-muted">{d.sync}</div>
                    <div className="off-grid-cell">
                      {d.issue === "low-battery" && <span className="badge badge--hold"><span className="badge-dot"/> Low battery</span>}
                      {d.issue === "needs-sync"  && <span className="badge badge--hold"><span className="badge-dot"/> Needs sync</span>}
                      {d.issue === "offline"     && <span className="badge badge--void"><span className="badge-dot"/> Offline</span>}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}

        {tab === "updates" && (
          <div className="off-table">
            <div style={{padding:'12px 16px', borderBottom:'1px solid var(--border)', background:'var(--bg-subtle)', display:'flex', alignItems:'center', gap:14}}>
              <OIcon name="info" style={{color:'var(--brand)'}}/>
              <div style={{flex:1, fontSize:13, color:'var(--text-muted)'}}>
                Price &amp; promotion changes are sent to ESLs in batches. Most updates land in under 5 minutes. Delivery failures retry automatically up to 3×.
              </div>
            </div>
            <div className="off-grid" style={{gridTemplateColumns:'120px 1.6fr 1fr 90px 110px 110px'}}>
              <div className="off-grid-headcell">When</div>
              <div className="off-grid-headcell">Update</div>
              <div className="off-grid-headcell">Scope</div>
              <div className="off-grid-headcell" style={{justifyContent:'flex-end'}}>Items</div>
              <div className="off-grid-headcell">Time taken</div>
              <div className="off-grid-headcell">Status</div>
              {ESL_RECENT_UPDATES.map((u, i) => (
                <div key={i} className="off-grid-row">
                  <div className="off-grid-cell off-cell-mono off-muted">{u.ts}</div>
                  <div className="off-grid-cell off-cell-strong">
                    {u.title}
                    {u.note && <div className="off-cell-mono off-muted" style={{fontSize:11, marginTop:2, color:'var(--hold-text)'}}>{u.note}</div>}
                  </div>
                  <div className="off-grid-cell off-muted">{u.scope}</div>
                  <div className="off-grid-cell off-cell-num">{u.items}</div>
                  <div className="off-grid-cell off-cell-mono off-muted">{u.elapsed}</div>
                  <div className="off-grid-cell">
                    {u.status === "delivered" && <span className="badge badge--paid"><span className="badge-dot"/> Delivered</span>}
                    {u.status === "partial"   && <span className="badge badge--hold"><span className="badge-dot"/> Partial</span>}
                    {u.status === "failed"    && <span className="badge badge--void"><span className="badge-dot"/> Failed</span>}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {tab === "templates" && (
          <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:14}}>
            {ESL_TEMPLATES.map(t => (
              <div key={t.id} className="off-card" style={{padding:0, overflow:'hidden'}}>
                <div style={{padding:18, background:'#fff', minHeight:160, display:'flex', alignItems:'center', justifyContent:'center', borderBottom:'1px solid var(--border)'}}>
                  {/* Mini preview */}
                  {t.id === "esl-promo" ? (
                    <div style={{background:'#fff', width:180, height:80, display:'flex', position:'relative', boxShadow:'0 1px 4px rgba(0,0,0,0.10)', borderRadius:4, overflow:'hidden'}}>
                      <div style={{padding:'6px 8px', flex:1, color:'#000'}}>
                        <div style={{fontSize:9, fontWeight:600}}>Goldfinger banana</div>
                        <div style={{fontSize:7, color:'#888', marginTop:2}}>Honduras · per lb</div>
                      </div>
                      <div style={{background:'#e02020', color:'#fff', padding:'6px 10px', minWidth:70, display:'flex', flexDirection:'column', justifyContent:'center'}}>
                        <div style={{fontSize:6, fontWeight:600, textTransform:'uppercase'}}>Special</div>
                        <div style={{fontSize:18, fontWeight:700, letterSpacing:'-0.025em', lineHeight:1}}>$1.9<span style={{fontSize:8}}>/lb</span></div>
                      </div>
                    </div>
                  ) : (
                    <div style={{background:'#fff', width:180, height:t.id === "esl-ndss" ? 60 : t.id === "esl-bin" ? 110 : 80, padding:'8px 10px', boxShadow:'0 1px 4px rgba(0,0,0,0.10)', borderRadius:4, color:'#000', display:'flex', flexDirection:'column', justifyContent:'space-between'}}>
                      <div>
                        <div style={{fontSize:t.id === "esl-bin" ? 11 : 9, fontWeight:600, lineHeight:1.1}}>{t.id === "esl-ndss" ? "BD Pen Needles 4mm" : "Atorvastatin 40mg"}</div>
                        <div style={{fontSize:7, color:'#555', marginTop:1}}>{t.id === "esl-ndss" ? "100 pieces" : "30 tablets"}</div>
                      </div>
                      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end'}}>
                        <div style={{fontFamily:'var(--font-mono)', fontSize:5}}>9333091001284</div>
                        <div style={{fontSize:14, fontWeight:700}}>{t.id === "esl-ndss" ? "$1.20" : "$18.20"}</div>
                      </div>
                      <div style={{height:6, background:'repeating-linear-gradient(to right, #000 0, #000 1px, #fff 1px, #fff 2px)'}}></div>
                    </div>
                  )}
                </div>
                <div style={{padding:14, display:'flex', flexDirection:'column', gap:6}}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8}}>
                    <div>
                      <div style={{fontWeight:600, fontSize:14, letterSpacing:'-0.01em'}}>{t.name}</div>
                      <div className="off-cell-mono off-muted" style={{fontSize:11, marginTop:2}}>{t.size}</div>
                    </div>
                    {t.color && <span className="badge badge--brand">Colour</span>}
                  </div>
                  <div className="off-muted" style={{fontSize:12}}>Used on {t.uses.toLocaleString()} {t.uses === 1 ? "ESL" : "ESLs"}</div>
                  <div style={{display:'flex', flexWrap:'wrap', gap:4, marginTop:4}}>
                    {t.fields.map(f => <span key={f} style={{fontSize:10, padding:'2px 6px', background:'var(--bg-subtle)', border:'1px solid var(--border)', borderRadius:99, color:'var(--text-muted)', fontFamily:'var(--font-mono)'}}>{f}</span>)}
                  </div>
                  <div style={{display:'flex', gap:6, marginTop:8}}>
                    <button className="btn btn--secondary btn--sm" style={{flex:1}}>Edit</button>
                    <button className="btn btn--ghost btn--sm" style={{flex:1}}>Duplicate</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {tab === "rules" && (
          <div className="off-card" style={{maxWidth:820}}>
            <h3 className="off-card-title">Auto-sync rules</h3>
            <div style={{fontSize:13, color:'var(--text-muted)', marginBottom:14}}>When CoreIQ pushes price changes to ESLs automatically.</div>

            <div className="settings-row">
              <div>
                <div className="settings-row-title">When a price changes in Manage stock</div>
                <div className="settings-row-desc">Push affected ESLs within seconds of save.</div>
              </div>
              <label className="toggle"><input type="checkbox" defaultChecked/><span className="toggle-track"><span className="toggle-thumb"/></span><span style={{fontSize:13}}>Enabled</span></label>
            </div>
            <div className="settings-row">
              <div>
                <div className="settings-row-title">When a promotion starts or ends</div>
                <div className="settings-row-desc">Switch to / revert from the promo template automatically.</div>
              </div>
              <label className="toggle"><input type="checkbox" defaultChecked/><span className="toggle-track"><span className="toggle-thumb"/></span><span style={{fontSize:13}}>Enabled</span></label>
            </div>
            <div className="settings-row">
              <div>
                <div className="settings-row-title">When stock receives change cost / margin</div>
                <div className="settings-row-desc">Auto-flag for review — manager confirms before push.</div>
              </div>
              <select className="input select" defaultValue="review"><option value="review">Flag for review</option><option>Push immediately</option><option>Ignore</option></select>
            </div>
            <div className="settings-row">
              <div>
                <div className="settings-row-title">Out-of-stock indicator</div>
                <div className="settings-row-desc">Switch to "Out of stock · ETA" template when on-hand = 0.</div>
              </div>
              <label className="toggle"><input type="checkbox" defaultChecked/><span className="toggle-track"><span className="toggle-thumb"/></span><span style={{fontSize:13}}>Enabled</span></label>
            </div>
            <div className="settings-row">
              <div>
                <div className="settings-row-title">Daily sync window</div>
                <div className="settings-row-desc">Catch-up sync for any ESLs that missed live pushes.</div>
              </div>
              <input className="input" defaultValue="04:00 AEST" style={{maxWidth:160}}/>
            </div>
            <div className="settings-row">
              <div>
                <div className="settings-row-title">Quiet hours</div>
                <div className="settings-row-desc">No screen flashes between these times (saves battery, avoids customer disturbance).</div>
              </div>
              <div style={{display:'flex', gap:8, alignItems:'center'}}>
                <input className="input tabular" defaultValue="22:00" style={{width:80}}/>
                <span style={{color:'var(--text-subtle)'}}>→</span>
                <input className="input tabular" defaultValue="06:00" style={{width:80}}/>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.OFFICE_SCREENS = Object.assign(window.OFFICE_SCREENS || {}, {
  esls: ESLs,
});
