/* global React, Icon, IconBtn, db */
const { useState, useEffect, useRef, useCallback } = React;

// ============================================================
// Scratch pad — a single always-there textarea.
// Auto-saves to db.kv on every keystroke (debounced).
// Bring back what you typed last week without thinking about it.
// ============================================================
function ScratchpadTool() {
  const [body, setBody] = useState('');
  const [mono, setMono] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [lastSaved, setLastSaved] = useState(null);
  const debRef = useRef(null);

  useEffect(() => {
    Promise.all([db.kv.get('scratchpad'), db.kv.get('scratchpadMono')]).then(([b, m]) => {
      if (b?.v != null) setBody(b.v.body || '');
      if (b?.v?.updatedAt) setLastSaved(b.v.updatedAt);
      if (m?.v != null) setMono(!!m.v);
      setLoaded(true);
    });
  }, []);

  // Debounced save — 400ms after last keystroke
  useEffect(() => {
    if (!loaded) return;
    if (debRef.current) clearTimeout(debRef.current);
    debRef.current = setTimeout(() => {
      const ts = Date.now();
      db.kv.put({ k: 'scratchpad', v: { body, updatedAt: ts } });
      setLastSaved(ts);
    }, 400);
    return () => debRef.current && clearTimeout(debRef.current);
  }, [body, loaded]);

  const toggleMono = () => { const next = !mono; setMono(next); db.kv.put({ k: 'scratchpadMono', v: next }); };

  const stats = (() => {
    const chars = body.length;
    const words = body.trim() ? body.trim().split(/\s+/).length : 0;
    const lines = body ? body.split('\n').length : 0;
    return { chars, words, lines };
  })();

  const copyAll = async () => {
    try { await navigator.clipboard.writeText(body); } catch {}
  };
  const clear = async () => {
    const ok = await window.lhDialog.confirm({
      title: 'Clear scratch pad?',
      message: 'The current text will be erased. There is no undo.',
      confirmLabel: 'Clear',
      danger: true,
      icon: 'delete',
    });
    if (ok) setBody('');
  };

  const savedLabel = lastSaved
    ? `Saved ${relTimeFor(lastSaved)}`
    : 'Saved locally';

  return (
    <div className="scratch-tool">
      <header className="scratch-head">
        <div className="scratch-head-text">
          <h1>Scratch pad</h1>
          <p>The fastest path from a thought to "I'll come back to this."</p>
        </div>
        <div className="scratch-head-actions">
          <button
            className={`lh-btn ghost ${mono ? 'is-active' : ''}`}
            onClick={toggleMono}
            title="Toggle monospace"
          >
            <Icon name="code" />
            {mono ? 'Mono' : 'Prose'}
          </button>
          <button className="lh-btn ghost" onClick={copyAll} disabled={!body}>
            <Icon name="content_copy" />Copy
          </button>
          <button className="lh-btn ghost" onClick={clear} disabled={!body}>
            <Icon name="delete_sweep" />Clear
          </button>
        </div>
      </header>

      <textarea
        className={`scratch-text ${mono ? 'is-mono' : ''}`}
        placeholder="Start typing — autosaved as you go. Nothing leaves this browser."
        value={body}
        onChange={e => setBody(e.target.value)}
        spellCheck={!mono}
      />

      <footer className="scratch-foot">
        <span>{stats.words} word{stats.words === 1 ? '' : 's'}</span>
        <span className="dot">·</span>
        <span>{stats.chars} char{stats.chars === 1 ? '' : 's'}</span>
        <span className="dot">·</span>
        <span>{stats.lines} line{stats.lines === 1 ? '' : 's'}</span>
        <span style={{ flex: 1 }} />
        <span className="scratch-saved">
          <Icon name="cloud_done" />{savedLabel}
        </span>
      </footer>
    </div>
  );
}

function relTimeFor(ts) {
  const d = (Date.now() - ts) / 1000;
  if (d < 2)   return 'just now';
  if (d < 60)  return `${Math.floor(d)}s ago`;
  if (d < 3600) return `${Math.floor(d/60)}m ago`;
  if (d < 86400) return `${Math.floor(d/3600)}h ago`;
  return `${Math.floor(d/86400)}d ago`;
}

window.ScratchpadTool = ScratchpadTool;
