// Admin → Tenant detail page (Profile / Devices / Analytics / Billing tabs)

const AdminTenantDetail = ({ tenantId, setRoute, openAddDevice, openEditDevice, initialTab }) => {
  const tenant = TENANTS.find(t => t.id === tenantId);
  const devices = DEVICES.filter(d => d.tenantId === tenantId);
  const tenantIdx = TENANTS.findIndex(t => t.id === tenantId);

  const [tab, setTab] = React.useState(initialTab || 'profile');
  if (!tenant) return <div>Tenant not found.</div>;

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

      <div className="row" style={{ alignItems: 'center', marginBottom: 24 }}>
        <div className="tenant-chip" style={{ alignItems: 'center' }}>
          <div className="av" style={{ width: 56, height: 56, fontSize: 18, borderRadius: 12,
            background: tenantIdx % 3 === 0 ? 'linear-gradient(135deg, var(--navy-700), var(--teal-400))' :
                        tenantIdx % 3 === 1 ? 'linear-gradient(135deg, var(--green-600), var(--teal-400))' :
                        'linear-gradient(135deg, var(--amber-500), var(--navy-700))' }}>
            {tenant.name.split(/\s+/).slice(0, 2).map(s => s[0]).join('').toUpperCase()}
          </div>
        </div>
        <div style={{ marginLeft: 14 }}>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em' }}>{tenant.name}</div>
          <div className="row" style={{ gap: 12, fontSize: 13, color: 'var(--ink-500)', marginTop: 4 }}>
            <span><Icon.Pin size={13} style={{ verticalAlign: '-2px' }} /> {tenant.address}</span>
            <span>·</span>
            <span><Icon.Hash size={12} style={{ verticalAlign: '-1px' }} /> <span className="mono">{tenant.id}</span></span>
            <span>·</span>
            <span>Joined <span className="mono">{tenant.joined}</span></span>
          </div>
        </div>
        <div className="spacer" />
        <div className="row">
          <StatusBadge status={tenant.status} />
          <Button icon={<Icon.Edit size={14} />}>Edit Tenant</Button>
          <Button variant="ghost" icon={<Icon.More size={14} />}></Button>
        </div>
      </div>

      <Tabs
        tabs={[
          { id: 'profile', label: 'Profile' },
          { id: 'devices', label: 'Devices', count: devices.length },
          { id: 'analytics', label: 'Analytics' },
          { id: 'billing', label: 'Billing', count: INVOICES.filter(i => i.tenantId === tenantId).length },
        ]}
        active={tab}
        onChange={setTab}
      />

      {tab === 'profile' && <TenantProfileTab tenant={tenant} devices={devices} />}
      {tab === 'devices' && <TenantDevicesTab tenant={tenant} devices={devices} setRoute={setRoute} openAdd={openAddDevice} openEdit={openEditDevice} />}
      {tab === 'analytics' && <TenantAnalyticsTab tenant={tenant} devices={devices} />}
      {tab === 'billing' && <TenantBillingTab tenant={tenant} />}
    </>
  );
};

// --- Profile tab ---
const TenantProfileTab = ({ tenant, devices }) => (
  <div className="grid-3">
    <div className="stack">
      <Card title="Contact Information" action={<Button size="sm" variant="ghost" icon={<Icon.Edit size={14} />}>Edit</Button>}>
        <div className="row-2">
          <Field label="Primary contact"><div className="mono" style={{ padding: 6 }}>{tenant.contact}</div></Field>
          <Field label="Email"><div style={{ padding: 6 }}>{tenant.email}</div></Field>
          <Field label="Phone"><div className="mono" style={{ padding: 6 }}>{tenant.phone}</div></Field>
          <Field label="Tenant ID"><div className="mono" style={{ padding: 6 }}>{tenant.id}</div></Field>
        </div>
        <Field label="Service address" hint="Used as fleet default location"><div style={{ padding: 6 }}>{tenant.address}</div></Field>
      </Card>

      <Card title="Subscription Defaults"
        action={<Button size="sm" variant="ghost" icon={<Icon.Edit size={14} />}>Change</Button>}>
        <div className="row" style={{ alignItems: 'flex-start', gap: 18 }}>
          <div style={{ flex: 1 }}>
            <div className="muted" style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.06 }}>Default Package</div>
            <div className="row" style={{ marginTop: 6, alignItems: 'center', gap: 10 }}>
              <Badge tone="blue">{tenant.package}</Badge>
              <span className="muted" style={{ fontSize: 12 }}>
                {PACKAGES.find(p => p.name === tenant.package)?.monthlyFee.toLocaleString()} SDG/mo · {PACKAGES.find(p => p.name === tenant.package)?.includedKwh} kWh included
              </span>
            </div>
            <div className="hint" style={{ marginTop: 8 }}>Applied to new devices unless overridden per-device.</div>
          </div>
        </div>
      </Card>
    </div>

    <div className="stack">
      <Card title="Fleet at a glance">
        <div className="kpi-row cols-2" style={{ marginBottom: 0 }}>
          <div className="kpi" style={{ padding: '14px 16px' }}>
            <div className="label">Devices</div>
            <div className="value" style={{ fontSize: 22 }}>{devices.length}</div>
            <div className="foot">{devices.filter(d => d.status === 'active').length} active</div>
          </div>
          <div className="kpi" style={{ padding: '14px 16px' }}>
            <div className="label">This Month</div>
            <div className="value" style={{ fontSize: 22 }}>{fmtSDG(tenant.monthSpend)}</div>
            <div className="foot">{tenant.balance ? <span className="trend down">●</span> : <span className="trend up">●</span>} {tenant.balance ? 'Outstanding' : 'On track'}</div>
          </div>
        </div>
        <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px dashed var(--line)' }}>
          <div className="muted" style={{ fontSize: 12, marginBottom: 8 }}>Devices by type</div>
          {Object.entries(devices.reduce((acc, d) => { acc[d.typeLabel] = (acc[d.typeLabel] || 0) + 1; return acc; }, {})).map(([k, v]) => (
            <div key={k} className="row" style={{ justifyContent: 'space-between', padding: '4px 0', fontSize: 13 }}>
              <span>{k}</span>
              <span className="mono bb">{v}</span>
            </div>
          ))}
        </div>
      </Card>
      <Card title="Recent Activity">
        <div className="feed">
          {ACTIVITY.slice(0, 5).filter(a => devices.find(d => d.id === a.deviceId)).map((e, i) => {
            const d = DEVICES.find(x => x.id === e.deviceId);
            return (
              <div key={i} className={"item " + (e.tag === 'warn' ? 'warn' : e.tag === 'alert' ? 'alert' : '')}>
                <div className="time">{e.at}</div>
                <div>
                  <span className="dev">{d?.label}</span>
                  <div className="msg">{e.msg}</div>
                </div>
                <div className="dot" />
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  </div>
);

// --- Devices tab ---
const TenantDevicesTab = ({ tenant, devices, setRoute, openAdd, openEdit }) => (
  <div>
    <div className="row" style={{ marginBottom: 16, justifyContent: 'space-between' }}>
      <div className="muted" style={{ fontSize: 13 }}>
        Manage all DER devices belonging to <span className="bb" style={{ color: 'var(--ink-900)' }}>{tenant.name}</span>.
      </div>
      <Button variant="primary" icon={<Icon.Plus size={14} />} onClick={() => openAdd && openAdd(tenant.id)}>Add Device</Button>
    </div>

    <div className="device-grid">
      {devices.map(d => (
        <div key={d.id} className="device-card" onClick={() => setRoute(`a-devices/${d.id}`)}>
          <div className="head">
            <div>
              <div className="name">{d.label}</div>
              <div className="type">{d.typeLabel} · <span className="mono">{d.serial}</span></div>
            </div>
            <StatusBadge status={d.status} />
          </div>
          <div className="specs">
            <span className="lbl">PV Capacity</span><span className="val">{d.pvKw} kW</span>
            <span className="lbl">Battery</span><span className="val">{d.batteryKwh > 0 ? d.batteryKwh + ' kWh' : '—'}</span>
            <span className="lbl">Max Load</span><span className="val">{d.maxLoadKw} kW</span>
            <span className="lbl">Package</span><span className="val" style={{fontFamily:'var(--font-sans)'}}>{d.package}</span>
          </div>
          <div className="foot">
            <span><Icon.Pin size={12} style={{verticalAlign:'-2px'}}/> {d.location}</span>
            <div className="row">
              <button className="btn ghost sm" onClick={e => { e.stopPropagation(); openEdit && openEdit(d.id); }}>
                <Icon.Edit size={14} />
              </button>
              <button className="btn ghost sm"><Icon.More size={14} /></button>
            </div>
          </div>
        </div>
      ))}

      <div className="device-card add" onClick={() => openAdd && openAdd(tenant.id)}>
        <div className="plus"><Icon.Plus /></div>
        <div className="bb" style={{ color: 'var(--navy-700)' }}>Add New Device</div>
        <div className="muted" style={{ fontSize: 12, textAlign: 'center', maxWidth: 200 }}>
          Register a new DER device to {tenant.name}
        </div>
      </div>
    </div>
  </div>
);

// --- Analytics tab ---
const TenantAnalyticsTab = ({ tenant, devices }) => {
  const [period, setPeriod] = React.useState('7d');
  const activeDevs = devices.filter(d => d.status !== 'inactive');

  const totalGen = activeDevs.reduce((s, d) => s + d.todayGen, 0) * (period === '24h' ? 1 : period === '7d' ? 7 : 30);
  const totalLoad = totalGen * 0.65;
  const avgSoc = activeDevs.filter(d => d.soc != null).reduce((s, d, _, a) => s + d.soc / a.length, 0);

  // PV series
  const pvSeries = activeDevs.map((d, i) => ({
    label: d.label,
    color: PALETTE[i % PALETTE.length],
    data: genSolarCurve(48, d.pvKw, i + 5),
  }));
  // SOC series
  const socSeries = activeDevs.filter(d => d.soc != null).map((d, i) => ({
    label: d.label,
    color: PALETTE[i % PALETTE.length],
    data: genSocCurve(48, i + 7),
  }));
  // Consumption stacked bar — 7 days
  const consDays = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const consData = activeDevs.map((d, i) => consDays.map((_, j) => Math.round(d.todayGen * (0.5 + ((i * 7 + j * 3) % 5) * 0.18) * 0.65)));
  // PAYGo
  const paygoSeries = activeDevs.map((d, i) => ({
    label: d.label,
    color: PALETTE[i % PALETTE.length],
    data: genPaygoCurve(30, d.credit + 30, 2 + i * 0.3, i + 9),
  }));

  return (
    <>
      <div className="row" style={{ marginBottom: 18, justifyContent: 'space-between' }}>
        <div className="muted" style={{ fontSize: 13 }}>
          Fleet-wide analytics across <span className="bb" style={{ color: 'var(--ink-900)' }}>{activeDevs.length} devices</span> belonging to {tenant.name}.
        </div>
        <div className="row" style={{ gap: 6 }}>
          {['24h', '7d', '30d', 'custom'].map(p => (
            <button key={p} className="btn sm" style={period === p ? { background: 'var(--navy-700)', color: '#fff', borderColor: 'var(--navy-700)' } : {}}
              onClick={() => setPeriod(p)}>{p === 'custom' ? 'Custom…' : p}</button>
          ))}
        </div>
      </div>

      <div className="kpi-row">
        <KPI label="Total Generation" value={fmtNum(totalGen)} unit="kWh" icon={<Icon.Sun size={18}/>} tone="amber" foot={period} />
        <KPI label="Total Load" value={fmtNum(totalLoad)} unit="kWh" icon={<Icon.Plug size={18}/>} foot="consumption" />
        <KPI label="Avg Battery SOC" value={Math.round(avgSoc)} unit="%" icon={<Icon.Battery size={18}/>} tone="green" foot="fleet average" />
        <KPI label="Active / Online" value={`${activeDevs.length}/${devices.length}`} icon={<Icon.Wifi size={18}/>} foot="streaming" />
      </div>

      <div className="grid-2" style={{ marginBottom: 16 }}>
        <Card title="Solar Generation" subtitle="One line per device · kW">
          <LineChart series={pvSeries} height={240} ySuffix=" kW" area />
        </Card>
        <Card title="Daily Consumption" subtitle="Stacked by device · last 7 days">
          <StackedBarChart
            data={consData}
            labels={consDays}
            series={activeDevs.map((d, i) => ({ label: d.label, color: PALETTE[i % PALETTE.length] }))}
            height={240}
          />
        </Card>
        <Card title="Battery State of Charge" subtitle="One line per device · %">
          <LineChart series={socSeries} height={240} ySuffix="%" yMin={0} yMax={100} />
        </Card>
        <Card title="PAYGo Balance" subtitle="Threshold line at 5 kWh">
          <LineChart series={paygoSeries} height={240} ySuffix=" kWh" threshold={5} />
        </Card>
      </div>

      <Card title="Per-device summary" padded={false}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Device</th><th className="num">Total Gen</th><th className="num">Total Load</th>
              <th className="num">Avg SOC</th><th className="num">Min PAYGo</th><th>Trend</th>
            </tr>
          </thead>
          <tbody>
            {activeDevs.map((d, i) => (
              <tr key={d.id}>
                <td><span className="pri">{d.label}</span><div className="meta">{d.typeLabel}</div></td>
                <td className="num">{fmtNum(d.todayGen * 7, 0)} kWh</td>
                <td className="num">{fmtNum(d.loadKwh * 7 * 0.95, 0)} kWh</td>
                <td className="num">{d.soc != null ? Math.round(d.soc) + '%' : '—'}</td>
                <td className="num">{(d.credit - 10).toFixed(1)} kWh</td>
                <td><Sparkline data={genSolarCurve(24, d.pvKw, i + 1).filter((_, j) => j % 2 === 0)} color={PALETTE[i % PALETTE.length]} /></td>
              </tr>
            ))}
            <tr style={{ background: 'var(--surface)', fontWeight: 700 }}>
              <td className="bb">Fleet Total</td>
              <td className="num bb">{fmtNum(activeDevs.reduce((s, d) => s + d.todayGen * 7, 0), 0)} kWh</td>
              <td className="num bb">{fmtNum(activeDevs.reduce((s, d) => s + d.loadKwh * 7 * 0.95, 0), 0)} kWh</td>
              <td className="num bb">{Math.round(avgSoc)}%</td>
              <td className="muted">—</td>
              <td></td>
            </tr>
          </tbody>
        </table>
      </Card>
    </>
  );
};

// --- Billing tab (admin view) ---
const TenantBillingTab = ({ tenant }) => {
  const invoices = INVOICES.filter(i => i.tenantId === tenant.id);
  const totalBilled = invoices.reduce((s, i) => s + i.total, 0);
  const collected = invoices.filter(i => i.status === 'paid').reduce((s, i) => s + i.total, 0);

  const monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

  return (
    <>
      <div className="kpi-row cols-3">
        <KPI label="Total Billed" value={fmtSDG(totalBilled)} icon={<Icon.Receipt size={18} />} foot={invoices.length + ' invoices'} />
        <KPI label="Collected" value={fmtSDG(collected)} icon={<Icon.Wallet size={18} />} tone="green" foot={invoices.filter(i=>i.status==='paid').length + ' paid'} />
        <KPI label="Outstanding" value={fmtSDG(totalBilled - collected)} icon={<Icon.Clock size={18} />} tone={totalBilled - collected > 0 ? 'amber' : ''} foot={(invoices.filter(i => i.status !== 'paid').length) + ' open'} />
      </div>

      <Card title="Invoice history" padded={false}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Invoice</th>
              <th>Period</th>
              <th>Devices</th>
              <th className="num">Subtotal</th>
              <th className="num">Total</th>
              <th>Status</th>
              <th>Issued / Due</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {invoices.map(inv => (
              <tr key={inv.id}>
                <td className="pri mono">{inv.id}</td>
                <td className="mono">{monthNames[inv.month - 1]} {inv.year}</td>
                <td>{inv.devices}</td>
                <td className="num">{fmtSDG(inv.subtotal)}</td>
                <td className="num bb">{fmtSDG(inv.total)}</td>
                <td><StatusBadge status={inv.status} /></td>
                <td className="mono meta">
                  <div>{inv.issuedAt}</div>
                  <div style={{ fontSize: 11 }}>due {inv.dueDate}</div>
                </td>
                <td>
                  <Button size="sm" variant="ghost" icon={<Icon.Eye size={14} />}></Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </>
  );
};

window.AdminTenantDetail = AdminTenantDetail;
