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

// ============================================================
// Distraction-free writer — a single big text column.
// Reuses the existing `notes` store with folder='Writing' so
// sessions are first-class and also visible in the Notes tool.
//
// The same data layer, a different UI: no toolbar, no markdown
// preview, no list — just typing.
// ============================================================

const WRITER_FOLDER = 'Writing';
const WRITER_TARGETS = [
  { value: 250, label: '250' },
  { value: 500, label: '500' },
  { value: 750, label: '750', sub: '"The Artist\u2019s Way"' },
  { value: 1000, label: '1k' },
  { value: 2000, label: '2k' },
];

function WriterTool() {
  const live = useLiveQuery(['notes']) || {};
  const all = useMemo(
    () => [...(live.notes || [])].filter(n => n.folder === WRITER_FOLDER)
                                 .sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0)),
    [live.notes]
  );
  const [currentId, setCurrentId] = useState(null);
  const [body, setBody] = useState('');
  const [title, setTitle] = useState('');
  const [draftDirty, setDraftDirty] = useState(false);
  const [sidebarCollapsed, toggleSidebar] = useToolSidebar('writer');
  const [target, setTarget] = useState(750);
  const [lastSaved, setLastSaved] = useState(null);
  const debRef = useRef(null);
  const taRef = useRef(null);

  // Load preferences (sidebar collapse is handled by useToolSidebar)
  useEffect(() => {
    db.kv.get('writerPrefs').then(rec => {
      if (rec?.v?.target) setTarget(rec.v.target);
    });
  }, []);
  const savePref = (patch) => db.kv.put({ k: 'writerPrefs', v: { target, ...patch } });

  // Select first session or create one
  useEffect(() => {
    if (!live.notes) return;
    if (currentId && all.find(n => n.id === currentId)) return;
    if (all.length > 0) setCurrentId(all[0].id);
    else createSession();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [live.notes]);

  // Load body/title when switching session
  useEffect(() => {
    if (!currentId) return;
    const note = all.find(n => n.id === currentId);
    if (!note) return;
    setBody(note.body || '');
    setTitle(note.title || '');
    setDraftDirty(false);
    setLastSaved(note.updatedAt);
  }, [currentId]);

  // Auto-save (debounced)
  useEffect(() => {
    if (!currentId || !draftDirty) return;
    if (debRef.current) clearTimeout(debRef.current);
    debRef.current = setTimeout(async () => {
      const existing = all.find(n => n.id === currentId);
      await db.notes.put({
        ...(existing || {}),
        id: currentId,
        folder: WRITER_FOLDER,
        title: title.trim() || 'Untitled session',
        body,
        format: 'markdown',
      });
      setDraftDirty(false);
      setLastSaved(Date.now());
    }, 500);
    return () => debRef.current && clearTimeout(debRef.current);
  }, [body, title, currentId, draftDirty]);

  const createSession = async () => {
    const now = new Date();
    const seed = {
      folder: WRITER_FOLDER,
      title: `Session — ${now.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`,
      body: '',
      format: 'markdown',
    };
    const saved = await db.notes.put(seed);
    setCurrentId(saved.id);
    setTimeout(() => taRef.current?.focus(), 50);
  };

  const removeSession = async (id) => {
    const target = all.find(n => n.id === id);
    if (!target) return;
    const ok = await window.lhDialog.confirm({
      title: `Delete "${target.title}"?`,
      message: 'The session is removed from your Writing folder. This can\u2019t be undone.',
      confirmLabel: 'Delete',
      danger: true,
      icon: 'delete',
    });
    if (!ok) return;
    await db.notes.delete(id);
    if (currentId === id) setCurrentId(null);
  };

  const wordCount = useMemo(() => body.trim() ? body.trim().split(/\s+/).length : 0, [body]);
  const readingMin = Math.max(1, Math.round(wordCount / 230));
  const targetPct = Math.min(100, Math.round((wordCount / target) * 100));

  const saveStatus = useMemo(() => {
    if (draftDirty) return 'Unsaved…';
    if (lastSaved) return `Saved · ${relMin(lastSaved)}`;
    return 'Saved locally';
  }, [draftDirty, lastSaved]);

  return (
    <div className={`writer-tool ${sidebarCollapsed ? 'is-collapsed' : ''}`}>
      <aside className="writer-sidebar">
        <div className="writer-collapsed-rail" onClick={toggleSidebar} title="Expand sidebar">
          <Icon name="chevron_right" />
        </div>
        <div className="writer-sidebar-head">
          <h2>Sessions</h2>
          <div style={{ flex: 1 }} />
          <button className="lh-btn primary" onClick={createSession}>
            <Icon name="add" />New
          </button>
          <ToolSidebarToggle collapsed={sidebarCollapsed} onToggle={toggleSidebar} />
        </div>
        <ul className="writer-sessions">
          {all.length === 0 ? (
            <li className="writer-sessions-empty">No sessions yet.</li>
          ) : all.map(n => (
            <li key={n.id} className={n.id === currentId ? 'is-active' : ''}>
              <button className="writer-session" onClick={() => setCurrentId(n.id)}>
                <div className="writer-session-title">{n.title || 'Untitled'}</div>
                <div className="writer-session-meta">
                  {wordsOf(n.body)} words · {relMin(n.updatedAt)}
                </div>
              </button>
              <button
                className="writer-session-del"
                onClick={(e) => { e.stopPropagation(); removeSession(n.id); }}
                title="Delete session"
              >
                <Icon name="close" />
              </button>
            </li>
          ))}
        </ul>
      </aside>

      <main className="writer-main">
        <header className="writer-head">
          {sidebarCollapsed && (
            <button
              className="writer-icon-btn"
              onClick={toggleSidebar}
              title="Show sessions"
            >
              <Icon name="left_panel_open" />
            </button>
          )}
          <input
            className="writer-title-input"
            placeholder="Session title…"
            value={title}
            onChange={e => { setTitle(e.target.value); setDraftDirty(true); }}
          />
          <div className="writer-meta">
            <span className="writer-status">{saveStatus}</span>
          </div>
        </header>

        <div className="writer-paper">
          <textarea
            ref={taRef}
            className="writer-textarea"
            placeholder="Just start. Don't read what you wrote yesterday. Don't go back to fix a typo.&#10;&#10;Type."
            value={body}
            onChange={e => { setBody(e.target.value); setDraftDirty(true); }}
            spellCheck
          />
        </div>

        <footer className="writer-foot">
          <div className="writer-progress-wrap">
            <div className="writer-progress">
              <span style={{ width: `${targetPct}%` }} />
            </div>
            <div className="writer-progress-meta">
              <strong>{wordCount}</strong> / {target} words · {targetPct}%
            </div>
          </div>
          <div className="writer-foot-stats">
            <span>{readingMin} min read</span>
            <span className="dot">·</span>
            <span>{body.length} chars</span>
          </div>
          <div className="writer-targets">
            <span>Target:</span>
            {WRITER_TARGETS.map(t => (
              <button
                key={t.value}
                className={`writer-target ${target === t.value ? 'is-active' : ''}`}
                onClick={() => { setTarget(t.value); savePref({ target: t.value }); }}
                title={t.sub}
              >
                {t.label}
              </button>
            ))}
          </div>
        </footer>
      </main>
    </div>
  );
}

function wordsOf(s) { return s ? (s.trim().split(/\s+/).filter(Boolean).length) : 0; }
function relMin(ts) {
  if (!ts) return '—';
  const d = (Date.now() - ts) / 1000;
  if (d < 60)   return 'just now';
  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.WriterTool = WriterTool;
