"use client";
/**
 * Update-available banner. Renders nothing unless the local .update_check ledger
 * (via GET /api/system/update) reports a newer version. When the operator clicks
 * Update it POSTs — the click is the human consent for this irreversible action,
 * so it applies directly (the agent-only self_update tool stays always-gated).
 * Fixed-position + null-when-current → zero impact on the dashboard layout.
 */

import { useEffect, useState } from 'react';

const WRAP = {
  position: 'fixed', top: 12, right: 12, zIndex: 9999,
  maxWidth: 340, padding: '10px 12px', borderRadius: 10,
  background: '#141414', color: '#EDE7DD', border: '1px solid #2A2A2A',
  boxShadow: '0 6px 24px rgba(0,0,0,0.35)', fontSize: 13, lineHeight: 1.4,
};
const ROW = { display: 'flex', gap: 8, alignItems: 'center', marginTop: 8 };
const BTN = { padding: '5px 10px', borderRadius: 7, border: '1px solid #3A3A3A', background: '#C1440E', color: '#fff', cursor: 'pointer', fontSize: 12 };
const GHOST = { ...BTN, background: 'transparent', color: '#9A9A9A', borderColor: '#2A2A2A' };

export default function UpdateBanner() {
  const [info, setInfo] = useState(null);
  const [dismissed, setDismissed] = useState(false);
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState(null);

  useEffect(() => {
    let alive = true;
    fetch('/api/system/update')
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => { if (alive && d) setInfo(d); })
      .catch(() => {});
    return () => { alive = false; };
  }, []);

  if (dismissed || !info || !info.behind) return null;

  async function applyUpdate() {
    setBusy(true);
    try {
      const res = await fetch('/api/system/update', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
      const d = await res.json().catch(() => ({}));
      setDone(d.ok ? (d.message || 'Updated. Restart to apply.') : (d.error || 'Update failed.'));
    } catch {
      setDone('Update failed.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={WRAP} role="status" aria-live="polite">
      {done ? (
        <div>{done}</div>
      ) : (
        <>
          <div><strong>madarX OS v{info.latest}</strong> is available (you have v{info.current}).</div>
          <div style={ROW}>
            <button type="button" style={BTN} onClick={applyUpdate} disabled={busy}>
              {busy ? 'Updating…' : 'Update now'}
            </button>
            <button type="button" style={GHOST} onClick={() => setDismissed(true)} disabled={busy}>
              Later
            </button>
          </div>
        </>
      )}
    </div>
  );
}
