// maintenance.jsx — an admin's notice that the board will be down for an update
//
// Kept with the board as a lab-wide setting (data.settings, admins only; the server enforces it):
//   { id: 'maintenance', from, to, note, issuedAt, issuedBy }   (from/to: ms timestamps)
// From the moment it's issued until `to`, every page shows a banner along the top, and each
// browser gets a pop-up once per notice (the first time it sees it, on loading the page or live).

const MAINT_SEEN_KEY = 'workshop_v2_maintenance_seen';

const maintenanceNotice = (data) => {
  const n = ((data && data.settings) || []).find(s => s.id === 'maintenance');
  return n && n.to > Date.now() ? n : null;
};

// "Fri 17 Oct, 18:00 – 19:30" (the end's date is only repeated when it's another day)
function maintenanceWhen(n) {
  const day = (ms) => new Date(ms).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
  const time = (ms) => new Date(ms).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
  return `${day(n.from)}, ${time(n.from)} – ${day(n.to) === day(n.from) ? '' : day(n.to) + ', '}${time(n.to)}`;
}

// Re-render every 30 s, so the banner moves from "coming up" to "now" to gone on its own.
function useMinuteTick() {
  const [, tick] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => { const t = setInterval(tick, 30000); return () => clearInterval(t); }, []);
}

function MaintenanceBanner({ data }) {
  useMinuteTick();
  const n = maintenanceNotice(data);
  if (!n) return null;
  const now = Date.now() >= n.from;
  return (
    <div className={`nb-maint-banner ${now ? 'is-now' : ''}`} role="status">
      <span className="nb-maint-icon">🛠</span>
      <span className="nb-maint-text">
        {now
          ? <>Update in progress until {new Date(n.to).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })}.</>
          : <>The Kanban will be unavailable for an update <b>{maintenanceWhen(n)}</b>.</>}
        {n.note && <span className="nb-maint-note"> {n.note}</span>}
      </span>
    </div>
  );
}

// The pop-up, once per notice per browser.
function MaintenanceModal({ data }) {
  const n = maintenanceNotice(data);
  const [seen, setSeen] = React.useState(() => { try { return localStorage.getItem(MAINT_SEEN_KEY); } catch (e) { return null; } });
  if (!n || seen === String(n.issuedAt)) return null;
  const dismiss = () => {
    try { localStorage.setItem(MAINT_SEEN_KEY, String(n.issuedAt)); } catch (e) {}
    setSeen(String(n.issuedAt));
  };
  const by = personById(data, n.issuedBy);
  return (
    <div className="nb-help-overlay" style={{ zIndex: 400 }} onClick={(e) => { if (e.target === e.currentTarget) dismiss(); }}>
      <div className="nb-help-modal nb-maint-modal" role="alertdialog" aria-labelledby="nb-maint-title">
        <div className="nb-help-header">
          <div id="nb-maint-title" style={{ fontFamily: 'var(--hand)', fontSize: 28, color: 'var(--ink)' }}>🛠 Planned update</div>
        </div>
        <p className="nb-maint-body">The Kanban will be temporarily unavailable for an update:</p>
        <div className="nb-maint-window">{maintenanceWhen(n)}</div>
        {n.note && <p className="nb-maint-body">{n.note}</p>}
        <p className="nb-maint-body nb-maint-small">
          Anything you change during the update is kept in your browser and sent once the board is back.
          {by ? ` Notice from ${by.name}.` : ''}
        </p>
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <button className="nb-btn accent" onClick={dismiss} autoFocus>Got it</button>
        </div>
      </div>
    </div>
  );
}

// datetime-local value <-> ms (local time)
const toLocalInput = (ms) => {
  const d = new Date(ms), p = (x) => String(x).padStart(2, '0');
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}T${p(d.getHours())}:${p(d.getMinutes())}`;
};

// For admins, in Settings: issue, change or withdraw the notice.
// onSave(notice | null): null withdraws it.
function MaintenanceSettings({ data, meId, onSave }) {
  const current = maintenanceNotice(data);
  const nextHour = Math.ceil(Date.now() / 3600000) * 3600000;
  const [from, setFrom] = React.useState(toLocalInput(current ? current.from : nextHour));
  const [to, setTo] = React.useState(toLocalInput(current ? current.to : nextHour + 3600000));
  const [note, setNote] = React.useState(current ? current.note || '' : '');
  const fromMs = new Date(from).getTime(), toMs = new Date(to).getTime();
  const problem = isNaN(fromMs) || isNaN(toMs) ? 'pick a start and an end'
    : toMs <= fromMs ? 'the end must be after the start'
    : toMs <= Date.now() ? 'that window has already passed' : null;

  const publish = () => {
    const issuedAt = Date.now();
    onSave({ id: 'maintenance', from: fromMs, to: toMs, note: note.trim().slice(0, 300), issuedAt, issuedBy: meId || null });
    try { localStorage.setItem(MAINT_SEEN_KEY, String(issuedAt)); } catch (e) {} // no pop-up for the one who wrote it
    showToast(current ? 'Maintenance notice updated: everyone sees it again' : 'Maintenance notice published', 'success');
  };

  return (
    <div className="nb-maint-settings">
      <div className="sync-menu-heading" style={{ paddingLeft: 0 }}>
        Maintenance notice {current ? '· showing now' : ''}
      </div>
      <div className="nb-maint-fields">
        <label>from <input type="datetime-local" className="nb-input" value={from} onChange={e => setFrom(e.target.value)}/></label>
        <label>to <input type="datetime-local" className="nb-input" value={to} onChange={e => setTo(e.target.value)}/></label>
      </div>
      <input className="nb-input" placeholder="note (optional), e.g. new notification bell and API keys" maxLength={300}
        value={note} onChange={e => setNote(e.target.value)}/>
      <div className="nb-maint-actions">
        {problem && <span className="nb-maint-problem">{problem}</span>}
        {current && <button className="nb-btn" onClick={() => { onSave(null); showToast('Maintenance notice withdrawn', 'info'); }}>withdraw</button>}
        <button className="nb-btn accent" disabled={!!problem} onClick={publish}>{current ? 'update notice' : 'publish notice'}</button>
      </div>
    </div>
  );
}

Object.assign(window, { maintenanceNotice, MaintenanceBanner, MaintenanceModal, MaintenanceSettings });
