// charge-log.jsx — a member's charging sessions (site/charge-log.html).
// Reads and writes public.charge_sessions directly with the member's sign-in;
// row-level security limits every query to their own rows. The Concierge
// reads the same table (server-side) to answer about their charging.
const { useState, useEffect, useMemo, useRef } = React;
const CU = window.ChargeUtils;
const COLS = 'id,started_at,kwh,cost,location_type,location_name,network,soc_start,soc_end,odometer_km,source,import_batch,notes';
const TYPES = { home: 'Home', public: 'Public', work: 'Work', other: 'Other' };
const FIELDS = [
  ['started_at', 'Date & time', true], ['kwh', 'Energy (kWh)', true], ['cost', 'Cost (R)'], ['location_name', 'Place'],
  ['network', 'Network'], ['soc_start', 'Battery at start (%)'], ['soc_end', 'Battery at end (%)'], ['odometer_km', 'Odometer (km)'],
];

const rand2 = (n) => (n == null ? '—' : 'R' + Number(n).toFixed(2));
// "1 234.5": a space between thousands and a point for decimals, as the rest
// of the site writes figures. (en-ZA's toLocaleString uses a decimal comma.)
const fmt = (n, dp) => { const v = Math.round(Number(n) * 10 ** dp) / 10 ** dp; const [i, f] = String(v).split('.'); return i.replace(/\B(?=(\d{3})+(?!\d))/g, ' ') + (f ? '.' + f : ''); };
const kwh = (n) => (n == null ? '—' : fmt(n, 1) + ' kWh');
const rand = (n) => (n == null ? '—' : 'R' + fmt(n, 0));
const when = (iso) => new Date(iso).toLocaleString('en-ZA', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
// <input type="datetime-local"> works in local time; the site's members are in SA.
const toLocalInput = (iso) => { const d = new Date(iso); const p = (x) => String(x).padStart(2, '0'); return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`; };
const uuid = () => (crypto.randomUUID ? crypto.randomUUID() : 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; return (c === 'x' ? r : (r & 3 | 8)).toString(16); }));

let toastSet = null;
const toast = (m) => toastSet && toastSet(m);

function Tile({ l, v, s }) { return <div className="tile"><div className="l">{l}</div><div className="v">{v}</div>{s && <div className="s">{s}</div>}</div>; }

function SessionForm({ initial, onSave, onCancel, busy }) {
  const blank = { started_at: toLocalInput(new Date().toISOString()), location_type: 'home', location_name: '', network: '', kwh: '', cost: '', soc_start: '', soc_end: '', odometer_km: '', notes: '' };
  const [v, setV] = useState(initial ? { ...blank, ...initial, started_at: toLocalInput(initial.started_at), cost: initial.cost ?? '', soc_start: initial.soc_start ?? '', soc_end: initial.soc_end ?? '', odometer_km: initial.odometer_km ?? '', location_name: initial.location_name || '', network: initial.network || '', notes: initial.notes || '' } : blank);
  const [err, setErr] = useState('');
  const set = (k) => (e) => setV({ ...v, [k]: e.target.value });
  const submit = (e) => {
    e.preventDefault();
    const k = CU.num(v.kwh);
    if (!(k > 0) || k > 500) return setErr('Enter the energy added, in kWh (more than 0).');
    const pct = (x) => (x === '' ? null : Math.round(CU.num(x)));
    const s1 = pct(v.soc_start), s2 = pct(v.soc_end);
    if ([s1, s2].some((x) => x != null && (x < 0 || x > 100))) return setErr('Battery percentages are between 0 and 100.');
    const cost = v.cost === '' ? null : CU.num(v.cost);
    if (cost != null && cost < 0) return setErr('Cost can’t be negative.');
    const started = new Date(v.started_at);
    if (isNaN(started)) return setErr('Choose a date and time.');
    setErr('');
    onSave({
      started_at: started.toISOString(), kwh: Math.round(k * 100) / 100, cost, location_type: v.location_type,
      location_name: v.location_name.trim() || null, network: v.network.trim() || null, soc_start: s1, soc_end: s2,
      odometer_km: v.odometer_km === '' ? null : Math.round(CU.num(v.odometer_km)), notes: v.notes.trim() || null,
    });
  };
  return (
    <form className="panel" onSubmit={submit}>
      <h2>{initial ? 'Edit session' : 'Add a charging session'}</h2>
      {err && <div className="err" role="alert">{err}</div>}
      <div className="frm">
        <div className="f w2"><label>Date &amp; time</label><input type="datetime-local" value={v.started_at} onChange={set('started_at')} required/></div>
        <div className="f"><label>Where</label><select value={v.location_type} onChange={set('location_type')}>{Object.entries(TYPES).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select></div>
        <div className="f"><label>Energy added (kWh)</label><input inputMode="decimal" value={v.kwh} onChange={set('kwh')} placeholder="e.g. 32.5" required/></div>
        <div className="f w2"><label>Place (optional)</label><input value={v.location_name} onChange={set('location_name')} placeholder={v.location_type === 'home' ? 'Home' : 'e.g. Sandton City'}/></div>
        <div className="f"><label>Network (optional)</label><input value={v.network} onChange={set('network')} placeholder="e.g. GridCars"/></div>
        <div className="f"><label>Cost (R, optional)</label><input inputMode="decimal" value={v.cost} onChange={set('cost')} placeholder={v.location_type === 'home' ? 'leave blank to use your tariff' : 'e.g. 210'}/></div>
        <div className="f"><label>Battery at start (%)</label><input inputMode="numeric" value={v.soc_start} onChange={set('soc_start')}/></div>
        <div className="f"><label>Battery at end (%)</label><input inputMode="numeric" value={v.soc_end} onChange={set('soc_end')}/></div>
        <div className="f w2"><label>Odometer (km, optional)</label><input inputMode="numeric" value={v.odometer_km} onChange={set('odometer_km')}/><span className="hint">With readings now and then, we can work out your real energy use.</span></div>
        <div className="f w4"><label>Notes (optional)</label><textarea value={v.notes} maxLength={500} onChange={set('notes')}/></div>
      </div>
      <div className="frm-actions">
        <button type="button" className="btn btn-ghost" onClick={onCancel}>Cancel</button>
        <button type="submit" className="btn btn-accent" disabled={busy}>{busy ? 'Saving…' : 'Save session'}</button>
      </div>
    </form>
  );
}

function Importer({ existing, onImport, onCancel, busy }) {
  const [rows, setRows] = useState(null);
  const [name, setName] = useState('');
  const [map, setMap] = useState({});
  const [type, setType] = useState('public');
  const [err, setErr] = useState('');
  const read = (e) => {
    const f = e.target.files[0]; if (!f) return;
    if (f.size > 5 * 1024 * 1024) { setErr('That file is over 5 MB. Export a shorter date range.'); return; }
    const r = new FileReader();
    r.onload = () => {
      const all = CU.parseCsv(String(r.result));
      if (all.length < 2) { setErr('That file has no rows to import. It needs a header row and at least one session.'); return; }
      setErr(''); setName(f.name); setRows(all); setMap(CU.guessMapping(all[0]));
    };
    r.readAsText(f);
  };
  const result = useMemo(() => {
    if (!rows || map.started_at == null || map.kwh == null) return null;
    const out = CU.rowsToSessions(rows.slice(1, 2001), map, { location_type: type });
    const have = new Set(existing.map(CU.dedupeKey));
    const fresh = [], dup = [];
    out.sessions.forEach((s) => (have.has(CU.dedupeKey(s)) ? dup : fresh).push(s));
    return { fresh, dup, errors: out.errors, truncated: rows.length - 1 > 2000 };
  }, [rows, map, type, existing]);
  const header = rows ? rows[0] : [];
  return (
    <div className="panel">
      <h2>Import from a CSV <small>from your charging app or a spreadsheet</small></h2>
      {err && <div className="err" role="alert">{err}</div>}
      <div className="f" style={{ maxWidth: 420 }}><label>CSV file</label><input type="file" accept=".csv,text/csv" onChange={read} style={{ paddingTop: 9 }}/>
        <span className="hint">Most charging apps can export your history as CSV. Save Excel files as CSV first. The file is read in your browser; only the sessions you import are saved.</span></div>
      {rows && (
        <>
          <p style={{ margin: '16px 0 10px', fontSize: 13.5, color: 'var(--fg-2)' }}>Match the columns in <b>{name}</b> ({rows.length - 1} rows):</p>
          <div className="frm">
            {FIELDS.map(([k, l, req]) => (
              <div className="f" key={k}><label>{l}{req ? ' *' : ''}</label>
                <select value={map[k] ?? ''} onChange={(e) => setMap({ ...map, [k]: e.target.value === '' ? undefined : Number(e.target.value) })}>
                  <option value="">— not in file —</option>{header.map((h, i) => <option key={i} value={i}>{h || 'Column ' + (i + 1)}</option>)}
                </select></div>
            ))}
            <div className="f"><label>Sessions are mostly at</label><select value={type} onChange={(e) => setType(e.target.value)}>{Object.entries(TYPES).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select><span className="hint">Places named “Home” are marked home anyway.</span></div>
          </div>
          {!result ? <div className="note" style={{ marginTop: 14 }}>Choose which columns hold the date and the kWh to continue.</div> : (
            <>
              <div className="note" style={{ marginTop: 14 }}>
                <b>{result.fresh.length}</b> session(s) ready to import
                {result.dup.length > 0 && <> · {result.dup.length} already in your log (skipped)</>}
                {result.errors.length > 0 && <> · {result.errors.length} row(s) can’t be read (rows {result.errors.slice(0, 6).map((e) => e.row).join(', ')}{result.errors.length > 6 ? '…' : ''}: {result.errors[0].reason})</>}
                {result.truncated && <> · only the first 2 000 rows are imported at a time</>}
              </div>
              {result.fresh.length > 0 && (
                <div className="scroll"><table className="tbl"><thead><tr><th>When</th><th>Where</th><th>kWh</th><th>Cost</th><th>Battery</th></tr></thead>
                  <tbody>{result.fresh.slice(0, 5).map((s, i) => <tr key={i}><td>{when(s.started_at)}</td><td>{TYPES[s.location_type]}{s.location_name ? ' · ' + s.location_name : ''}</td><td>{s.kwh}</td><td>{s.cost == null ? '—' : rand2(s.cost)}</td><td>{s.soc_start != null ? s.soc_start + '% → ' + (s.soc_end ?? '?') + '%' : '—'}</td></tr>)}</tbody></table></div>
              )}
            </>
          )}
        </>
      )}
      <div className="frm-actions">
        <button className="btn btn-ghost" onClick={onCancel}>Cancel</button>
        <button className="btn btn-accent" disabled={busy || !result || !result.fresh.length} onClick={() => onImport(result.fresh)}>{busy ? 'Importing…' : result && result.fresh.length ? `Import ${result.fresh.length} session(s)` : 'Import'}</button>
      </div>
    </div>
  );
}

function App() {
  const [state, setState] = useState('loading');      // loading | signin | noconfig | ready | error
  const [user, setUser] = useState(null);
  const [tariff, setTariff] = useState(null);
  const [rows, setRows] = useState([]);
  const [mode, setMode] = useState(null);              // null | 'add' | 'import' | session (edit)
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [lastBatch, setLastBatch] = useState(null);
  const [showAll, setShowAll] = useState(false);
  const [t, setT] = useState('');
  toastSet = (m) => { setT(m); clearTimeout(toastSet._t); toastSet._t = setTimeout(() => setT(''), 2600); };

  const load = async (u) => {
    const [s, p] = await Promise.all([
      DB.sb.from('charge_sessions').select(COLS).eq('user_id', u.id).order('started_at', { ascending: false }).limit(2000),
      DB.sb.from('profile_prefs').select('home_tariff').eq('profile_id', u.id).maybeSingle(),
    ]);
    if (s.error) throw s.error;
    setRows(s.data || []);
    setTariff(p.data && p.data.home_tariff != null ? Number(p.data.home_tariff) : null);
  };

  useEffect(() => {
    (async () => {
      if (!window.DB || !DB.configured) return setState('noconfig');
      const u = await DB.getUser().catch(() => null);
      if (!u) return setState('signin');
      setUser(u);
      try { await load(u); setState('ready'); }
      catch (e) { console.error('[charge-log]', e); setState('error'); }
    })();
  }, []);

  const summary = useMemo(() => CU.summarise(rows, { homeTariff: tariff }), [rows, tariff]);

  const save = async (data) => {
    setBusy(true); setErr('');
    try {
      const q = mode && mode.id
        ? DB.sb.from('charge_sessions').update(data).eq('id', mode.id)
        : DB.sb.from('charge_sessions').insert({ ...data, user_id: user.id, source: 'manual' });
      const { error } = await q;
      if (error) throw error;
      await load(user); setMode(null); toast(mode && mode.id ? 'Session updated' : 'Session added');
    } catch (e) { setErr('Couldn’t save: ' + (e.message || e)); }
    finally { setBusy(false); }
  };

  const remove = async (s) => {
    if (!confirm('Delete this session from ' + when(s.started_at) + '?')) return;
    const { error } = await DB.sb.from('charge_sessions').delete().eq('id', s.id);
    if (error) return toast('Couldn’t delete: ' + error.message);
    await load(user); toast('Session deleted');
  };

  const importRows = async (list) => {
    setBusy(true); setErr('');
    const batch = uuid();
    try {
      for (let i = 0; i < list.length; i += 200) {
        const { error } = await DB.sb.from('charge_sessions').insert(list.slice(i, i + 200).map((s) => ({ ...s, user_id: user.id, source: 'csv', import_batch: batch })));
        if (error) throw error;
      }
      await load(user); setMode(null); setLastBatch({ id: batch, n: list.length }); toast(list.length + ' session(s) imported');
    } catch (e) {
      setErr('The import stopped part-way: ' + (e.message || e) + '. Sessions imported so far are kept; you can undo them below.');
      setLastBatch({ id: batch, n: null });
      await load(user).catch(() => {});
    } finally { setBusy(false); }
  };

  const undoImport = async () => {
    const { error } = await DB.sb.from('charge_sessions').delete().eq('import_batch', lastBatch.id);
    if (error) return toast('Couldn’t undo: ' + error.message);
    setLastBatch(null); await load(user); toast('Import undone');
  };

  if (state === 'loading') return <div className="cl-page"><div className="cl-col"><div className="skel"/><div className="skel"/></div></div>;
  if (state === 'signin') return <div className="state"><h2>Your charge log</h2><p>Sign in to keep a record of your charging, and get answers from the Concierge based on what you actually spend.</p><a className="btn btn-accent btn-sm" style={{ marginTop: 18 }} href={'auth.html?next=' + encodeURIComponent('charge-log.html')}>Sign in <span className="arr">→</span></a></div>;
  if (state === 'noconfig' || state === 'error') return <div className="state"><h2>The charge log is unavailable</h2><p>We can’t load it right now. This is on our side — please try again shortly.</p><button className="btn btn-accent btn-sm" style={{ marginTop: 18 }} onClick={() => location.reload()}>Try again</button></div>;

  const s = summary;
  const homeCostNote = s.home_estimate ? `+ about ${rand(s.home_estimate.cost)} at home at your ${rand2(s.home_estimate.tariff)}/kWh` : null;
  const maxMonth = Math.max(1, ...s.months.map((m) => m.kwh));

  return (
    <div className="cl-page"><div className="cl-col">
      <div className="cl-head">
        <div>
          <div className="eyebrow">Charge log</div>
          <h1>Your charging, in one place.</h1>
          <p>Log sessions or import them from your charging app. The <a href="concierge.html" style={{ color: 'var(--accent)' }}>Concierge</a> uses this to answer questions about your own costs and habits.</p>
        </div>
        <div className="cl-actions">
          <button className="btn btn-ghost" onClick={() => setMode('import')}>Import CSV</button>
          <button className="btn btn-accent" onClick={() => setMode('add')}>Add session</button>
        </div>
      </div>
      {err && <div className="err" role="alert">{err}</div>}
      {lastBatch && <div className="note">{lastBatch.n != null ? lastBatch.n + ' session(s) imported.' : 'Part of an import was saved.'} <button className="btn btn-ghost btn-sm" style={{ height: 30, marginLeft: 8 }} onClick={undoImport}>Undo import</button></div>}
      {mode === 'add' && <SessionForm busy={busy} onSave={save} onCancel={() => setMode(null)}/>}
      {mode && mode.id && <SessionForm key={mode.id} initial={mode} busy={busy} onSave={save} onCancel={() => setMode(null)}/>}
      {mode === 'import' && <Importer existing={rows} busy={busy} onImport={importRows} onCancel={() => setMode(null)}/>}

      {rows.length === 0 ? (
        <div className="panel" style={{ textAlign: 'center', padding: '40px 20px' }}>
          <h2 style={{ justifyContent: 'center' }}>No sessions yet</h2>
          <p style={{ color: 'var(--fg-2)', maxWidth: 460, margin: '0 auto' }}>Add your last few charges, or import your history. Tip: add your home tariff on your <a href="profile.html" style={{ color: 'var(--accent)' }}>profile</a> so home charging without a receipt is still costed.</p>
        </div>
      ) : (
        <>
          <div className="tiles">
            <Tile l="Last 30 days" v={kwh(s.last_30_days.kwh)} s={s.last_30_days.sessions + ' session(s)'}/>
            <Tile l="Spent, last 30 days" v={s.last_30_days.costed_kwh ? rand(s.last_30_days.cost) : '—'} s={s.last_30_days.uncosted_kwh ? kwh(s.last_30_days.uncosted_kwh) + ' with no cost logged' : 'from logged costs'}/>
            <Tile l="Average price" v={s.total.rand_per_kwh != null ? rand2(s.total.rand_per_kwh) + '/kWh' : '—'} s={s.by_type.public && s.by_type.public.rand_per_kwh != null ? 'public ' + rand2(s.by_type.public.rand_per_kwh) + (s.by_type.home && s.by_type.home.rand_per_kwh != null ? ' · home ' + rand2(s.by_type.home.rand_per_kwh) : '') : 'where a cost was logged'}/>
            <Tile l="Charged at home" v={s.home_share != null ? Math.round(s.home_share * 100) + '%' : '—'} s="of all energy"/>
            <Tile l="Energy use" v={s.efficiency ? s.efficiency.kwh_per_100km + ' kWh' : '—'} s={s.efficiency ? 'per 100 km, over ' + s.efficiency.km + ' km' : 'add odometer readings to measure'}/>
            <Tile l="All time" v={kwh(s.total.kwh)} s={(s.total.costed_kwh ? rand(s.total.cost) + ' logged' : 'no costs logged') + (homeCostNote ? ' ' + homeCostNote : '')}/>
          </div>
          {s.months.length > 1 && (
            <div className="panel"><h2>Energy by month <small>last {s.months.length} months</small></h2>
              <div className="mbars">{s.months.map((m) => (
                <div className="mrow" key={m.month} title={m.month + ': ' + kwh(m.kwh) + (m.costed_kwh ? ', ' + rand(m.cost) : '')}>
                  <span>{new Date(m.month + '-01T12:00:00Z').toLocaleDateString('en-ZA', { month: 'short', year: 'numeric' })}</span>
                  <span className="trk"><span className="fill" style={{ display: 'block', width: (m.kwh / maxMonth * 100) + '%' }}/></span>
                  <span className="val">{kwh(m.kwh)}{m.costed_kwh ? ' · ' + rand(m.cost) : ''}</span>
                </div>))}</div>
            </div>
          )}
          <div className="panel"><h2>Sessions <small>{rows.length} logged · <a href="concierge.html" style={{ color: 'var(--accent)' }}>Ask the Concierge about them →</a></small></h2>
            {(showAll ? rows : rows.slice(0, 20)).map((r) => (
              <div className="sess" key={r.id}>
                <div className="when">{when(r.started_at)}</div>
                <div className="where"><b>{r.location_name || TYPES[r.location_type]}</b><span className={'typ ' + r.location_type}>{TYPES[r.location_type]}</span>
                  <small>{[r.network, r.soc_start != null ? r.soc_start + '% → ' + (r.soc_end ?? '?') + '%' : null, r.odometer_km != null ? fmt(r.odometer_km, 0) + ' km' : null, r.source === 'csv' ? 'imported' : null].filter(Boolean).join(' · ')}</small></div>
                <div className="nums">{kwh(Number(r.kwh))}<small>{r.cost != null ? rand2(r.cost) : r.location_type === 'home' && tariff != null ? '≈ ' + rand2(Number(r.kwh) * tariff) + ' est.' : 'no cost'}</small></div>
                <div className="ops"><button onClick={() => { setMode(r); scrollTo({ top: 0, behavior: 'smooth' }); }}>Edit</button><button onClick={() => remove(r)}>Delete</button></div>
              </div>))}
            {!showAll && rows.length > 20 && <div style={{ textAlign: 'center', paddingTop: 12 }}><button className="btn btn-ghost btn-sm" onClick={() => setShowAll(true)}>Show all {rows.length} sessions</button></div>}
          </div>
        </>
      )}
      {t && <div className="toast" role="status">{t}</div>}
    </div></div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
