/* ============================================================
   history.jsx — version history panel + undo hotkey
   ============================================================ */

function useUndoHotkey() {
  const { undo, history } = useApp();
  useEffect(() => {
    const onKey = (e) => {
      const isUndo = (e.metaKey || e.ctrlKey) && !e.shiftKey && (e.key === 'z' || e.key === 'Z');
      if (isUndo) {
        const tag = (e.target && e.target.tagName) || '';
        // allow native undo inside text fields
        if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target && e.target.isContentEditable)) return;
        e.preventDefault();
        undo();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [undo]);
}

function fmtAgo(ts) {
  const d = (Date.now() - ts) / 1000;
  if (d < 60) return Math.round(d) + ' sec geleden';
  if (d < 3600) return Math.round(d / 60) + ' min geleden';
  if (d < 86400) return Math.round(d / 3600) + ' u geleden';
  return new Date(ts).toLocaleDateString('nl-NL', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}

function HistoryPanel() {
  const { history, undo, revertTo } = useApp();
  const [open, setOpen] = useState(false);
  useUndoHotkey();

  return (
    <>
      <button className="btn-icon history-trigger" title="Geschiedenis (⌘Z om ongedaan te maken)"
              onClick={() => setOpen(v => !v)}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
          <path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/>
        </svg>
        {history.length > 0 && <span className="history-count">{history.length}</span>}
      </button>

      {open && (
        <div className="history-panel">
          <div className="history-head">
            <div>
              <div className="history-title">Versiegeschiedenis</div>
              <div className="history-sub">{history.length} wijzigingen · maximaal 50</div>
            </div>
            <button className="icon-close" onClick={() => setOpen(false)}>×</button>
          </div>

          <div className="history-actions">
            <button className="btn" onClick={undo} disabled={history.length === 0}>
              ↶ Laatste ongedaan maken
            </button>
          </div>

          {history.length === 0 ? (
            <div className="history-empty">Nog geen wijzigingen om terug te draaien.</div>
          ) : (
            <ul className="history-list">
              {history.slice().reverse().map((entry, revI) => {
                const i = history.length - 1 - revI;
                return (
                  <li key={i} className="history-item">
                    <div className="history-dot" style={{background: entry.color || '#8b9a54'}}/>
                    <div className="history-body">
                      <div className="history-label">{entry.label}</div>
                      <div className="history-meta">
                        <span className="history-author">{entry.author}</span>
                        <span className="history-time">· {fmtAgo(entry.at)}</span>
                      </div>
                    </div>
                    <button className="history-revert"
                            onClick={() => { revertTo(i); setOpen(false); }}
                            title="Herstel naar deze versie">
                      herstel
                    </button>
                  </li>
                );
              })}
            </ul>
          )}

          <div className="history-foot">
            Elk geaccepteerd voorstel, toegevoegd blok en verwijderde sectie wordt hier vastgelegd. Tip: <kbd>⌘Z</kbd> maakt de laatste stap ongedaan.
          </div>
        </div>
      )}
    </>
  );
}

Object.assign(window, { HistoryPanel });
