// Admin → Device detail page + Add/Edit Device modal

const AdminDeviceDetail = ({ deviceId, setRoute }) => {
  const d = DEVICES.find(x => x.id === deviceId);
  const t = TENANTS.find(x => x.id === d?.tenantId);
  const [tab, setTab] = React.useState('overview');
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const i = setInterval(() => setTick(x => x + 1), 3000);
    return () => clearInterval(i);
  }, []);

  if (!d) return <div>Device not found.</div>;
  const pvNow = d.pvNow + Math.sin(tick / 3) * 0.8;
  const loadNow = d.loadKwh + Math.cos(tick / 4) * 0.4;

  return (
    <>
      <div className="row" style={{ marginBottom: 14 }}>
        <button className="btn ghost sm" onClick={() => setRoute('a-devices')}>
          <Icon.ArrowL size={14} /> Back to Devices
        </button>
      </div>

      <div className="row" style={{ marginBottom: 24, alignItems: 'center' }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14, background: 'var(--teal-50)',
          color: 'var(--navy-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <Icon.Cpu size={28} />
        </div>
        <div style={{ marginLeft: 14 }}>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em' }}>{d.label}</div>
          <div className="row" style={{ gap: 12, fontSize: 13, color: 'var(--ink-500)', marginTop: 4 }}>
            <Badge tone="outline">{d.typeLabel}</Badge>
            <span><span className="mono">{d.serial}</span></span>
            <span>·</span>
            <span>{t?.name}</span>
          </div>
        </div>
        <div className="spacer" />
        <div className="row">
          <StatusBadge status={d.status} />
          <ConnDot status={d.connectivity} />
          <Button icon={<Icon.Edit size={14} />}>Edit</Button>
          <Button variant="ghost" icon={<Icon.More size={14} />}></Button>
        </div>
      </div>

      <Tabs
        tabs={[
          { id: 'overview', label: 'Overview' },
          { id: 'telemetry', label: 'Telemetry' },
          { id: 'alarms', label: 'Alarms', count: ALARMS.filter(a => a.deviceId === d.id).length },
          { id: 'history', label: 'History' },
        ]}
        active={tab} onChange={setTab}
      />

      {tab === 'overview' && (
        <>
          <div className="kpi-row cols-3">
            <KPI label="Solar Output (live)" value={pvNow.toFixed(1)} unit="kW" foot={`of ${d.pvKw} kW capacity`}
              icon={<Icon.Sun size={18} />} tone="amber"
              trend={{ dir: 'up', value: ((pvNow / d.pvKw) * 100).toFixed(0) + '%' }} />
            <KPI label="Battery SOC" value={d.soc != null ? d.soc + '%' : '—'} foot={d.batteryKwh ? `of ${d.batteryKwh} kWh` : 'no battery'}
              icon={<Icon.Battery size={18} />} tone="green" />
            <KPI label="PAYGo Credit" value={d.credit.toFixed(1)} unit="kWh" foot="energy credits"
              icon={<Icon.Wallet size={18} />} tone={d.credit < 50 ? 'amber' : ''} />
          </div>

          <div className="grid-3">
            <div className="stack">
              <Card title="Live Telemetry · last 24h" subtitle="3s tick · gentle noise on production telemetry">
                <LineChart
                  series={[
                    { label: 'Solar (kW)', color: PALETTE[0], data: genSolarCurve(96, d.pvKw, 11) },
                    { label: 'Load (kW)', color: PALETTE[1], data: genLoadCurve(96, d.maxLoadKw, 12) },
                  ]}
                  height={260}
                  ySuffix=" kW"
                  area
                />
              </Card>
              <Card title="Activity log">
                <div className="feed">
                  {ACTIVITY.filter(a => a.deviceId === d.id).map((e, i) => (
                    <div key={i} className={"item " + (e.tag === 'warn' ? 'warn' : '')}>
                      <div className="time">{e.at}</div>
                      <div className="msg">{e.msg}</div>
                      <div className="dot" />
                    </div>
                  ))}
                </div>
              </Card>
            </div>
            <div className="stack">
              <Card title="Hardware specs" action={<Button size="sm" variant="ghost" icon={<Icon.Edit size={14} />}>Edit</Button>}>
                <div className="kv">
                  <span className="k">PV Capacity</span><span className="v">{d.pvKw} kW</span>
                  <span className="k">Battery</span><span className="v">{d.batteryKwh > 0 ? d.batteryKwh + ' kWh' : '—'}</span>
                  <span className="k">Max Load</span><span className="v">{d.maxLoadKw} kW</span>
                  <span className="k">Inverter</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>{d.inverter}</span>
                  <span className="k">Firmware</span><span className="v">{d.firmware}</span>
                </div>
              </Card>
              <Card title="Location">
                <div className="kv" style={{marginBottom: 10}}>
                  <span className="k">Site</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>{d.location}</span>
                  <span className="k">Lat / Lng</span><span className="v">{d.lat.toFixed(4)} · {d.lng.toFixed(4)}</span>
                  <span className="k">Tenant</span><span className="v" style={{fontFamily:'var(--font-sans)'}}>{t?.name}</span>
                </div>
                <MapPlaceholder />
              </Card>
              <Card title="Simulation">
                <div className="kv">
                  <span className="k">Sim enabled</span>
                  <span className="v" style={{fontFamily:'var(--font-sans)', color:'var(--green-700)'}}>● {d.simEnabled ? 'Running' : 'Stopped'}</span>
                  <span className="k">Tick interval</span><span className="v">{d.tick} ms</span>
                  <span className="k">Channel</span><span className="v">device:{d.id.slice(-6)}</span>
                </div>
                <div className="row" style={{marginTop: 12, gap: 8}}>
                  <Button size="sm" variant="ghost" icon={<Icon.Refresh size={13}/>}>Reset telemetry</Button>
                  <Button size="sm" variant="danger" icon={<Icon.Trash size={13}/>}>Decommission</Button>
                </div>
              </Card>
            </div>
          </div>
        </>
      )}

      {tab === 'telemetry' && (
        <div className="stack">
          <Card title="Solar Generation · 7-day rolling">
            <LineChart series={[{label:'PV (kW)', color: PALETTE[0], data: genSolarCurve(168, d.pvKw, 13)}]} height={260} ySuffix=" kW" area />
          </Card>
          <Card title="Battery State of Charge · 7-day">
            {d.batteryKwh > 0
              ? <LineChart series={[{label:'SOC %', color: PALETTE[1], data: genSocCurve(168, 15)}]} height={240} ySuffix="%" yMin={0} yMax={100} />
              : <div className="muted center" style={{padding:36}}>No battery on this device.</div>}
          </Card>
          <Card title="Load Draw · 7-day">
            <LineChart series={[{label:'Load (kW)', color: PALETTE[6], data: genLoadCurve(168, d.maxLoadKw, 17)}]} height={240} ySuffix=" kW" area />
          </Card>
        </div>
      )}

      {tab === 'alarms' && (
        <Card padded={false}>
          <table className="tbl">
            <thead><tr><th>Triggered</th><th>Severity</th><th>Type</th><th>Message</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {ALARMS.filter(a => a.deviceId === d.id).map(a => (
                <tr key={a.id}>
                  <td className="mono">{a.at}</td>
                  <td><Badge tone={a.severity === 'alert' ? 'red' : a.severity === 'warn' ? 'amber' : 'blue'} dot>{a.severity}</Badge></td>
                  <td className="mono meta">{a.kind}</td>
                  <td>{a.msg}</td>
                  <td>{a.cleared ? <Badge tone="green">Cleared</Badge> : <Badge tone="amber">Open</Badge>}</td>
                  <td><Button size="sm" variant="ghost">Acknowledge</Button></td>
                </tr>
              ))}
              {ALARMS.filter(a => a.deviceId === d.id).length === 0 && (
                <tr><td colSpan="6" className="muted center" style={{padding:28}}>No alarms on this device.</td></tr>
              )}
            </tbody>
          </table>
        </Card>
      )}

      {tab === 'history' && (
        <Card title="Operational history" padded={false}>
          <table className="tbl">
            <thead><tr><th>Timestamp</th><th>Actor</th><th>Action</th><th>Details</th></tr></thead>
            <tbody>
              <tr><td className="mono">2026-05-13 12:14:00</td><td>operator@bleu.sd</td><td><Badge tone="amber">Maintenance</Badge></td><td>Status changed inactive → maintenance</td></tr>
              <tr><td className="mono">2026-05-08 09:02:11</td><td>system</td><td><Badge tone="blue">Firmware</Badge></td><td>Upgraded 1.3.8 → {d.firmware}</td></tr>
              <tr><td className="mono">2026-05-01 00:00:00</td><td>system</td><td><Badge tone="green">Billing</Badge></td><td>Included in invoice <span className="mono">INV-2026-04</span></td></tr>
              <tr><td className="mono">{d.installDate} 00:00:00</td><td>operator@bleu.sd</td><td><Badge tone="green">Commissioned</Badge></td><td>Initial commissioning · package {d.package}</td></tr>
            </tbody>
          </table>
        </Card>
      )}
    </>
  );
};

// --- Map placeholder ---
const MapPlaceholder = () => (
  <div style={{
    position: 'relative',
    width: '100%', height: 160,
    background: 'linear-gradient(135deg, #d9ecf3 0%, #eef6fa 100%)',
    borderRadius: 8,
    border: '1px solid var(--line)',
    overflow: 'hidden',
    backgroundImage: `repeating-linear-gradient(0deg, transparent 0 19px, rgba(27,92,142,0.06) 19px 20px),
                      repeating-linear-gradient(90deg, transparent 0 19px, rgba(27,92,142,0.06) 19px 20px)`,
  }}>
    <div style={{
      position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -100%)',
      color: 'var(--navy-700)'
    }}>
      <Icon.Pin size={28} />
    </div>
    <div style={{
      position: 'absolute', bottom: 8, right: 10, fontSize: 10, color: 'var(--ink-500)',
      fontFamily: 'var(--font-mono)'
    }}>map preview</div>
  </div>
);

// --- Add / Edit Device modal ---
const DeviceFormModal = ({ open, onClose, prefillTenant, editing, onSave }) => {
  const [form, setForm] = React.useState({
    label: '', serial: '', type: 'solar_battery_der', tenantId: prefillTenant || '',
    location: '', lat: '', lng: '',
    pvKw: '', batteryKwh: '', maxLoadKw: '',
    inverterBrand: '', inverterModel: '',
    package: 'Standard', installDate: '2026-05-13',
    status: 'inactive', tick: 3000, tz: 3.0, simEnabled: true,
  });

  React.useEffect(() => {
    if (editing) {
      const d = DEVICES.find(x => x.id === editing);
      if (d) {
        setForm({
          label: d.label, serial: d.serial, type: d.type, tenantId: d.tenantId,
          location: d.location, lat: d.lat, lng: d.lng,
          pvKw: d.pvKw, batteryKwh: d.batteryKwh, maxLoadKw: d.maxLoadKw,
          inverterBrand: '', inverterModel: d.inverter,
          package: d.package, installDate: d.installDate,
          status: d.status, tick: d.tick, tz: 3.0, simEnabled: d.simEnabled,
        });
      }
    } else if (open) {
      setForm(f => ({ ...f, tenantId: prefillTenant || '' }));
    }
  }, [editing, open, prefillTenant]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  if (!open) return null;
  return (
    <Modal
      open={open}
      onClose={onClose}
      size="lg"
      title={editing ? 'Edit Device' : 'Add Device'}
      subtitle={editing ? 'Adjust hardware spec, package or operational state' : 'Register a new DER device. It will start streaming once activated.'}
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="default" onClick={() => onSave && onSave('draft')}>Save as Draft</Button>
          <Button variant="accent" icon={<Icon.Check size={14}/>} onClick={() => onSave && onSave('active')}>Save & Activate</Button>
        </>
      }
    >
      <div className="stepper">
        <div className="step" data-on="true"><span className="num">1</span> Identity</div>
        <div className="step-sep"></div>
        <div className="step"><span className="num">2</span> Location</div>
        <div className="step-sep"></div>
        <div className="step"><span className="num">3</span> Hardware</div>
        <div className="step-sep"></div>
        <div className="step"><span className="num">4</span> Subscription</div>
        <div className="step-sep"></div>
        <div className="step"><span className="num">5</span> Operations</div>
      </div>

      <div className="form">
        <div>
          <div className="section-ttl">1 · Identity</div>
          <div className="row-2">
            <Field label="Device Label" required hint="Human-readable name shown to tenants">
              <input type="text" value={form.label} onChange={e => set('label', e.target.value)} placeholder="e.g. Water Pump Controller" />
            </Field>
            <Field label="Serial Number" hint="Optional. Required when hardware is connected.">
              <input type="text" value={form.serial} onChange={e => set('serial', e.target.value)} placeholder="BLD-XX-0000" />
            </Field>
            <Field label="Device Type" required>
              <select value={form.type} onChange={e => set('type', e.target.value)}>
                <option value="solar_battery_der">Solar + Battery</option>
                <option value="solar_only">Solar Only</option>
                <option value="battery_only">Battery Only</option>
                <option value="hybrid">Hybrid (Solar + Battery + Grid)</option>
              </select>
            </Field>
            <Field label="Assigned Tenant" required>
              <select value={form.tenantId} onChange={e => set('tenantId', e.target.value)}>
                <option value="">— Select tenant —</option>
                {TENANTS.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
              </select>
            </Field>
          </div>
        </div>

        <div>
          <div className="section-ttl">2 · Location</div>
          <Field label="Location Name" required hint="Used in dashboards and maps">
            <input type="text" value={form.location} onChange={e => set('location', e.target.value)} placeholder="e.g. North Field, Gezira" />
          </Field>
          <div className="row-2">
            <Field label="GPS Latitude" hint="Optional, -90 to 90"><input type="number" step="0.0001" value={form.lat} onChange={e => set('lat', e.target.value)} placeholder="14.4012" /></Field>
            <Field label="GPS Longitude" hint="Optional, -180 to 180"><input type="number" step="0.0001" value={form.lng} onChange={e => set('lng', e.target.value)} placeholder="33.5108" /></Field>
          </div>
        </div>

        <div>
          <div className="section-ttl">3 · Hardware Specifications</div>
          <div className="row-3">
            <Field label="PV Capacity" hint="kW · drives solar simulation peak" required>
              <input type="number" value={form.pvKw} onChange={e => set('pvKw', e.target.value)} placeholder="15" />
            </Field>
            <Field label="Battery Capacity" hint="kWh · 0 if no battery">
              <input type="number" value={form.batteryKwh} onChange={e => set('batteryKwh', e.target.value)} placeholder="30" />
            </Field>
            <Field label="Max Load" hint="kW · caps load simulation" required>
              <input type="number" value={form.maxLoadKw} onChange={e => set('maxLoadKw', e.target.value)} placeholder="10" />
            </Field>
          </div>
          <div className="row-2">
            <Field label="Inverter Brand"><input type="text" value={form.inverterBrand} onChange={e => set('inverterBrand', e.target.value)} placeholder="Victron" /></Field>
            <Field label="Inverter Model"><input type="text" value={form.inverterModel} onChange={e => set('inverterModel', e.target.value)} placeholder="MultiPlus-II 48/5000" /></Field>
          </div>
        </div>

        <div>
          <div className="section-ttl">4 · Subscription & Billing</div>
          <div className="row-2">
            <Field label="Subscription Package" required hint="Can differ from tenant default">
              <select value={form.package} onChange={e => set('package', e.target.value)}>
                {PACKAGES.map(p => <option key={p.id} value={p.name}>{p.name} — {p.monthlyFee.toLocaleString()} SDG · {p.includedKwh} kWh</option>)}
              </select>
            </Field>
            <Field label="Install Date" required hint="Used for billing proration">
              <input type="date" value={form.installDate} onChange={e => set('installDate', e.target.value)} />
            </Field>
          </div>
        </div>

        <div>
          <div className="section-ttl">5 · Operational Settings</div>
          <div className="row-3">
            <Field label="Telemetry Tick" hint="How often simulator fires (ms)">
              <input type="number" value={form.tick} onChange={e => set('tick', e.target.value)} />
            </Field>
            <Field label="Timezone Offset" hint="Hours from UTC. Sudan = +3">
              <input type="number" step="0.5" value={form.tz} onChange={e => set('tz', e.target.value)} />
            </Field>
            <Field label="Simulation Enabled" hint="Disable when real hardware connects">
              <div className="row" style={{ height: 38, alignItems: 'center' }}>
                <Toggle on={form.simEnabled} onChange={v => set('simEnabled', v)} />
                <span style={{ marginLeft: 8, fontSize: 13 }}>{form.simEnabled ? 'Running' : 'Stopped'}</span>
              </div>
            </Field>
          </div>
        </div>
      </div>
    </Modal>
  );
};

Object.assign(window, { AdminDeviceDetail, DeviceFormModal });
