// Tenant screens: Dashboard (fleet + single device), Analytics, Account

const TenantDashboard = ({ tenantId, setRoute, initialView }) => {
  const tenant = TENANTS.find(t => t.id === tenantId);
  const devices = DEVICES.filter(d => d.tenantId === tenantId && d.status !== 'inactive');
  const [view, setView] = React.useState(initialView || 'fleet'); // 'fleet' | device id
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const i = setInterval(() => setTick(x => x + 1), 3000);
    return () => clearInterval(i);
  }, []);

  if (!tenant) return <div>Tenant not found.</div>;

  return (
    <>
      <div className="row" style={{ marginBottom: 18, gap: 14 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, color: 'var(--ink-500)', fontWeight: 500 }}>Welcome back,</div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.015em', marginTop: 2 }}>{tenant.contact} · {tenant.name}</div>
        </div>
        <div className="row">
          <Badge tone="green" dot>{devices.filter(d => d.connectivity === 'online').length} of {devices.length} Online</Badge>
        </div>
      </div>

      {/* Device tab switcher */}
      <div className="row" style={{ marginBottom: 20, justifyContent: 'space-between' }}>
        <div className="device-tabs">
          <button className="dtab" data-on={view === 'fleet'} onClick={() => setView('fleet')}>
            <Icon.Building size={14} /> Fleet Overview
          </button>
          {devices.map(d => (
            <button key={d.id} className="dtab" data-on={view === d.id} onClick={() => setView(d.id)}>
              {d.status === 'maintenance' ? <Icon.Alert size={13} style={{ color: 'var(--amber-600)' }} /> : <span className="dot" />}
              {d.label}
            </button>
          ))}
        </div>
        <div className="row" style={{ gap: 6 }}>
          <Button variant="ghost" size="sm" icon={<Icon.Calendar size={14}/>}>Today</Button>
          <Button variant="ghost" size="sm" icon={<Icon.Download size={14}/>}>Export</Button>
        </div>
      </div>

      {view === 'fleet'
        ? <FleetView devices={devices} tenant={tenant} tick={tick} setView={setView} setRoute={setRoute} />
        : <SingleDeviceView device={devices.find(d => d.id === view)} tick={tick} />
      }
    </>
  );
};

// --- Fleet Overview ---
const FleetView = ({ devices, tenant, tick, setView, setRoute }) => {
  const totalPv = devices.reduce((s, d) => s + d.pvNow, 0) + Math.sin(tick) * 1.2;
  const avgSoc = devices.filter(d => d.soc != null).reduce((s, d, _, a) => s + d.soc / a.length, 0);
  const totalLoad = devices.reduce((s, d) => s + d.loadKwh, 0);
  const openAlerts = ALARMS.filter(a => devices.find(d => d.id === a.deviceId) && !a.cleared).length;

  return (
    <>
      {/* Fleet summary */}
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.08, color: 'var(--ink-400)', marginBottom: 10 }}>
        Fleet Summary
      </div>
      <div className="kpi-row">
        <KPI label="Total Solar" value={totalPv.toFixed(1)} unit="kW" foot="all devices · live"
          icon={<Icon.Sun size={18}/>} tone="amber" />
        <KPI label="Avg Battery" value={Math.round(avgSoc)} unit="%" foot="fleet avg SOC"
          icon={<Icon.Battery size={18}/>} tone="green" />
        <KPI label="Load Today" value={totalLoad.toFixed(1)} unit="kWh" foot="across fleet"
          icon={<Icon.Plug size={18}/>} />
        <KPI label="Alerts" value={openAlerts} foot={openAlerts === 0 ? 'all clear' : 'needs attention'}
          icon={<Icon.Bell size={18}/>} tone={openAlerts > 0 ? 'red' : 'green'} />
      </div>

      {/* Device cards */}
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.08, color: 'var(--ink-400)', margin: '6px 0 10px' }}>
        Devices
      </div>
      <div className="fleet-grid" style={{ marginBottom: 24 }}>
        {devices.map((d, i) => <FleetDeviceCard key={d.id} device={d} idx={i} tick={tick} onOpen={() => setView(d.id)} />)}
      </div>

      {/* Fleet activity */}
      <div className="grid-3">
        <Card title="Fleet activity feed" padded={true}>
          <div className="feed">
            {ACTIVITY.filter(a => devices.find(x => x.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>
                    <span className="msg" style={{marginLeft: 6}}>{e.msg}</span>
                  </div>
                  <div className="dot" />
                </div>
              );
            })}
          </div>
        </Card>
        <Card title="This month" subtitle={tenant.name}>
          <div className="kv">
            <span className="k">Current invoice</span><span className="v" style={{fontFamily:'var(--font-sans)', color:'var(--navy-700)', fontWeight: 600}}>INV-2026-04-AHM</span>
            <span className="k">Estimated total</span><span className="v" style={{color: 'var(--ink-900)', fontWeight: 700}}>{fmtSDG(tenant.monthSpend)}</span>
            <span className="k">Active devices</span><span className="v">{devices.length}</span>
            <span className="k">Due date</span><span className="v">May 15</span>
          </div>
          <Button variant="primary" icon={<Icon.Receipt size={14}/>} onClick={() => setRoute('t-invoices')}>View Invoice</Button>
        </Card>
      </div>
    </>
  );
};

const FleetDeviceCard = ({ device: d, idx, tick, onOpen }) => {
  const pvNow = d.pvNow + Math.sin(tick / 2 + idx) * 0.5;
  return (
    <div className="fleet-card" onClick={onOpen}>
      <div className="head">
        <div>
          <div className="name">{d.label}</div>
          <div className="sub">{d.typeLabel} · {d.package}</div>
        </div>
        <StatusBadge status={d.status === 'maintenance' ? 'maintenance' : d.connectivity} />
      </div>

      <div className="metrics">
        <div className="fleet-metric">
          <div className="lbl"><Icon.Sun size={12}/> Solar</div>
          <div className="val">{pvNow.toFixed(1)} <span className="unit">kW</span></div>
          <div className="bar warn"><span style={{ width: `${Math.min(100, (pvNow / d.pvKw) * 100)}%` }} /></div>
        </div>
        <div className="fleet-metric">
          <div className="lbl"><Icon.Battery size={12}/> SOC</div>
          {d.soc != null ? (
            <>
              <div className="val">{d.soc} <span className="unit">%</span></div>
              <div className={"bar " + (d.soc < 30 ? 'danger' : d.soc < 60 ? 'warn' : '')}>
                <span style={{ width: `${d.soc}%` }} />
              </div>
            </>
          ) : (
            <>
              <div className="val muted" style={{ fontSize: 13 }}>no battery</div>
              <div className="bar" style={{ opacity: 0.4 }}><span style={{ width: '0%' }} /></div>
            </>
          )}
        </div>
        <div className="fleet-metric">
          <div className="lbl"><Icon.Plug size={12}/> Load Today</div>
          <div className="val">{d.loadKwh.toFixed(1)} <span className="unit">kWh</span></div>
          <Sparkline data={genLoadCurve(24, d.maxLoadKw, idx + 9).filter((_, j) => j % 2 === 0)} color="#1b5c8e" width={120} height={28} />
        </div>
        <div className="fleet-metric">
          <div className="lbl"><Icon.Wallet size={12}/> PAYGo Credit</div>
          <div className="val" style={{ color: d.credit < 50 ? 'var(--amber-600)' : 'var(--ink-900)' }}>
            {d.credit.toFixed(1)} <span className="unit">kWh</span>
          </div>
          <div className={"bar cool " + (d.credit < 50 ? 'warn' : '')}>
            <span style={{ width: `${Math.min(100, d.credit / 1.5)}%` }} />
          </div>
        </div>
      </div>

      <div className="row" style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line-soft)', justifyContent: 'space-between' }}>
        <ConnDot status={d.connectivity} />
        <span style={{ fontSize: 12, color: 'var(--navy-700)', fontWeight: 600 }}>View Details →</span>
      </div>
    </div>
  );
};

// --- Single device view (full 7-widget set) ---
const SingleDeviceView = ({ device: d, tick }) => {
  if (!d) return null;
  const pvNow = d.pvNow + Math.sin(tick / 2) * 0.8;
  const loadNow = d.loadKwh + Math.cos(tick / 3) * 0.3;
  const onlineFor = '2h 14m';

  return (
    <>
      <div className="kpi-row" style={{ gridTemplateColumns: '1fr 1fr 1.6fr' }}>
        {/* Sun power gauge */}
        <div className="gauge-card">
          <div className="hd">
            <div className="row" style={{ gap: 8 }}>
              <span style={{ color: 'var(--amber-600)' }}><Icon.Sun size={16}/></span>
              <span className="ttl">Sun Power</span>
            </div>
            <span className="muted" style={{ fontSize: 12 }}>{d.pvKw} kW peak</span>
          </div>
          <div className="center">
            <ArcGauge value={pvNow} max={d.pvKw} unit="kW" sub="solar generation" color="#e0a850" />
          </div>
          <div className="muted center" style={{fontSize: 12}}>
            <span style={{ color: pvNow > 0 ? 'var(--green-700)' : 'var(--ink-500)', fontWeight: 600 }}>
              {pvNow > d.pvKw * 0.6 ? 'Peak generation' : pvNow > d.pvKw * 0.2 ? 'Producing' : pvNow > 0 ? 'Low light' : 'After dark'}
            </span>
          </div>
        </div>

        {/* Battery */}
        <div className="gauge-card">
          <div className="hd">
            <div className="row" style={{ gap: 8 }}>
              <span style={{ color: 'var(--green-700)' }}><Icon.Battery size={16}/></span>
              <span className="ttl">Battery</span>
            </div>
            <span className="muted" style={{ fontSize: 12 }}>{d.batteryKwh ? d.batteryKwh + ' kWh' : 'none'}</span>
          </div>
          <div className="center">
            {d.soc != null
              ? <RingGauge value={d.soc} sub="state of charge" color="#5baa6f" />
              : <div className="muted center" style={{padding: 32}}>No battery on this device</div>}
          </div>
          <div className="muted center" style={{fontSize: 12}}>
            {d.soc != null && (
              <span style={{ fontWeight: 600, color: d.soc > 50 ? 'var(--green-700)' : 'var(--amber-600)' }}>
                {d.soc > 80 ? 'Reserves high' : d.soc > 50 ? 'Healthy' : d.soc > 25 ? 'Mid' : 'Low — charge soon'}
              </span>
            )}
          </div>
        </div>

        {/* System alerts */}
        <Card title="System Alerts" subtitle="Last 24 hours">
          <SystemAlerts device={d} />
        </Card>
      </div>

      {/* Power used + credit + connectivity row */}
      <div className="kpi-row" style={{ gridTemplateColumns: '2fr 1fr', marginBottom: 16 }}>
        <Card title="Power Used Today" subtitle="Live load draw — last 30 minutes">
          <LineChart series={[{ label: 'Load (kW)', color: PALETTE[0], data: genLoadCurve(60, d.maxLoadKw, 21) }]}
            height={240} ySuffix=" kW" area showLegend={false} />
        </Card>

        <div className="stack">
          <Card>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ color: 'var(--navy-700)' }}><Icon.Wallet size={16}/></span>
              <div className="bb" style={{ fontSize: 13 }}>Credit Left (PAYGo)</div>
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 36, fontWeight: 600, marginTop: 10, color: d.credit < 50 ? 'var(--amber-600)' : 'var(--ink-900)' }}>
              {d.credit.toFixed(1)} <span style={{ fontSize: 13, color: 'var(--ink-400)', fontFamily: 'var(--font-sans)' }}>kWh</span>
            </div>
            <div className="bar" style={{ marginTop: 14 }}><span style={{ width: `${Math.min(100, d.credit / 1.5)}%`, background: d.credit < 50 ? 'var(--amber-500)' : 'var(--green-600)' }} /></div>
            <div className="row" style={{ marginTop: 12, justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-500)' }}>
              <span>≈ {Math.round(d.credit / 4)} days at current load</span>
            </div>
            <Button variant="accent" className="" icon={<Icon.Plus size={14}/>} >Top Up</Button>
          </Card>
          <Card>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ color: 'var(--green-700)' }}><Icon.Wifi size={16}/></span>
              <div className="bb" style={{ fontSize: 13 }}>Connectivity</div>
            </div>
            <div style={{ marginTop: 10, display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span style={{
                width: 10, height: 10, borderRadius: '50%',
                background: d.connectivity === 'online' ? 'var(--green-600)' : 'var(--ink-300)',
                boxShadow: d.connectivity === 'online' ? '0 0 0 4px rgba(91,170,111,0.18)' : 'none'
              }} />
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 600, color: d.connectivity === 'online' ? 'var(--green-700)' : 'var(--ink-500)' }}>
                {d.connectivity === 'online' ? 'ONLINE' : 'OFFLINE'}
              </span>
            </div>
            <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>for {onlineFor} · last ping <span className="mono">2s ago</span></div>
          </Card>
        </div>
      </div>

      {/* Activity feed */}
      <Card title="Device activity feed" subtitle="Live · 3s interval">
        <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>
    </>
  );
};

const SystemAlerts = ({ device }) => {
  const alarms = ALARMS.filter(a => a.deviceId === device.id);
  if (alarms.length === 0) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0' }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12, background: 'var(--green-100)',
          color: 'var(--green-700)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <Icon.CircleCheck size={22} />
        </div>
        <div>
          <div className="bb" style={{ fontSize: 14 }}>All systems normal</div>
          <div className="muted" style={{ fontSize: 12 }}>No active alarms in the last 24 hours</div>
        </div>
      </div>
    );
  }
  return (
    <div className="stack" style={{ gap: 10 }}>
      {alarms.map(a => (
        <div key={a.id} style={{
          padding: 10, borderRadius: 8,
          background: a.severity === 'alert' ? 'var(--red-100)' : 'var(--amber-100)',
          display: 'flex', gap: 10
        }}>
          <Icon.Alert size={16} style={{ color: a.severity === 'alert' ? 'var(--red-600)' : 'var(--amber-600)', flexShrink: 0, marginTop: 2 }} />
          <div style={{ flex: 1 }}>
            <div className="bb" style={{ fontSize: 13 }}>{a.msg}</div>
            <div className="muted mono" style={{ fontSize: 11, marginTop: 3 }}>{a.at}</div>
          </div>
        </div>
      ))}
    </div>
  );
};

// --- Tenant Analytics ---
const TenantAnalytics = ({ tenantId }) => {
  const tenant = TENANTS.find(t => t.id === tenantId);
  const devices = DEVICES.filter(d => d.tenantId === tenantId && d.status !== 'inactive');
  const [device, setDevice] = React.useState('all');
  const [period, setPeriod] = React.useState('7d');
  const [metric, setMetric] = React.useState('solar');

  const filtered = device === 'all' ? devices : devices.filter(d => d.id === device);
  const samples = period === '24h' ? 96 : period === '7d' ? 168 : 720;

  const buildSeries = () => {
    if (metric === 'solar') {
      return filtered.map((d, i) => ({ label: d.label, color: PALETTE[i % PALETTE.length],
        data: genSolarCurve(samples, d.pvKw, i + 1) }));
    }
    if (metric === 'load') {
      return filtered.map((d, i) => ({ label: d.label, color: PALETTE[i % PALETTE.length],
        data: genLoadCurve(samples, d.maxLoadKw, i + 1) }));
    }
    if (metric === 'soc') {
      return filtered.filter(d => d.soc != null).map((d, i) => ({ label: d.label, color: PALETTE[i % PALETTE.length],
        data: genSocCurve(samples, i + 1) }));
    }
    if (metric === 'paygo') {
      return filtered.map((d, i) => ({ label: d.label, color: PALETTE[i % PALETTE.length],
        data: genPaygoCurve(30, d.credit + 30, 2 + i * 0.3, i + 1) }));
    }
    return [];
  };

  const ySuffix = metric === 'soc' ? '%' : metric === 'paygo' ? ' kWh' : ' kW';
  const threshold = metric === 'paygo' ? 5 : null;

  return (
    <>
      <PageHead title="Analytics"
        subtitle={"Per-device and fleet-wide trends for " + tenant.name}
        actions={
          <Button variant="primary" icon={<Icon.Download size={14}/>}>Export</Button>
        }
      />

      <Card padded={false}>
        <div className="filters">
          <div className="select">
            <select value={device} onChange={e => setDevice(e.target.value)}>
              <option value="all">All Devices</option>
              {devices.map(d => <option key={d.id} value={d.id}>{d.label}</option>)}
            </select>
            <Icon.ChevronD size={14}/>
          </div>
          <div className="select">
            <select value={period} onChange={e => setPeriod(e.target.value)}>
              <option value="24h">Last 24 hours</option>
              <option value="7d">Last 7 days</option>
              <option value="30d">Last 30 days</option>
              <option value="custom">Custom range…</option>
            </select>
            <Icon.ChevronD size={14}/>
          </div>
          <div className="grow"/>
          <div className="row" style={{ gap: 4 }}>
            {[['solar','Solar Gen'], ['load','Consumption'], ['soc','Battery SOC'], ['paygo','PAYGo Bal']].map(([m, l]) => (
              <button key={m} className="btn sm" style={metric === m ? { background: 'var(--navy-700)', borderColor: 'var(--navy-700)', color: '#fff' } : {}}
                onClick={() => setMetric(m)}>{l}</button>
            ))}
          </div>
        </div>
        <div style={{ padding: 20 }}>
          <LineChart series={buildSeries()} height={340} ySuffix={ySuffix} threshold={threshold}
            area={metric === 'solar' || metric === 'load'}
            yMin={metric === 'soc' ? 0 : null}
            yMax={metric === 'soc' ? 100 : null}
          />
        </div>
      </Card>

      <div style={{height:20}}/>

      <Card title="Summary by device" subtitle={period === '24h' ? 'Last 24 hours' : period === '7d' ? 'Last 7 days' : 'Last 30 days'} 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></tr>
          </thead>
          <tbody>
            {devices.map(d => {
              const factor = period === '24h' ? 1 : period === '7d' ? 7 : 30;
              return (
                <tr key={d.id}>
                  <td><span className="pri">{d.label}</span><div className="meta">{d.typeLabel}</div></td>
                  <td className="num">{fmtNum(d.todayGen * factor, 0)} kWh</td>
                  <td className="num">{fmtNum(d.loadKwh * factor * 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>
                </tr>
              );
            })}
            <tr style={{ background: 'var(--surface)' }}>
              <td className="bb">Fleet Total</td>
              <td className="num bb">{fmtNum(devices.reduce((s, d) => s + d.todayGen * (period === '24h' ? 1 : period === '7d' ? 7 : 30), 0), 0)} kWh</td>
              <td className="num bb">{fmtNum(devices.reduce((s, d) => s + d.loadKwh * (period === '24h' ? 1 : period === '7d' ? 7 : 30) * 0.95, 0), 0)} kWh</td>
              <td className="num bb">{Math.round(devices.filter(d => d.soc != null).reduce((s, d, _, a) => s + d.soc / a.length, 0))}%</td>
              <td className="muted">—</td>
            </tr>
          </tbody>
        </table>
      </Card>
    </>
  );
};

Object.assign(window, { TenantDashboard, TenantAnalytics });
