// editor.jsx
// Document pane — toolbar, mode-switch (preview/edit/split), inline title,
// floating selection toolbar.

const { useState: useStateE, useRef: useRefE, useEffect: useEffectE, useLayoutEffect, useMemo: useMemoE, useCallback: useCallbackE } = React;

const EIcon = {
  Doc: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" />
      <path d="M14 3v5h5M9 13h6M9 17h4" />
    </svg>
  ),
  Eye: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  ),
  Code: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M16 18l6-6-6-6M8 6l-6 6 6 6" />
    </svg>
  ),
  Split: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="16" rx="2" />
      <path d="M12 4v16" />
    </svg>
  ),
  Undo: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 14l-4-4 4-4" />
      <path d="M5 10h9a5 5 0 0 1 0 10h-2" />
    </svg>
  ),
  Redo: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M15 14l4-4-4-4" />
      <path d="M19 10h-9a5 5 0 0 0 0 10h2" />
    </svg>
  ),
  History: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 12a9 9 0 1 0 3-6.7" />
      <path d="M3 4v5h5" />
      <path d="M12 7v5l3 2" />
    </svg>
  ),
  Download: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3v12M7 10l5 5 5-5M5 21h14" />
    </svg>
  ),
  Empty: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z" />
      <path d="M14 3v5h5" />
      <path d="M9 13h6M9 17h4" />
    </svg>
  ),
  Quote: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M6 9h4v6H6z" /><path d="M14 9h4v6h-4z" />
    </svg>
  ),
  Sparkle: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 3l1.7 5.3L19 10l-5.3 1.7L12 17l-1.7-5.3L5 10l5.3-1.7z" />
    </svg>
  ),
};

// ─── Floating selection toolbar ──────────────────────────────
function SelectionToolbar({ selection, onQuote, onRewrite }) {
  if (!selection) return null;
  const { rect } = selection;
  return (
    <div
      className="float-tool"
      style={{ left: rect.left + rect.width / 2, top: rect.top + window.scrollY }}
    >
      <button onClick={onQuote} title="Add quote to chat">
        <EIcon.Quote /> Quote in chat
      </button>
      <div className="sep" />
      <button onClick={onRewrite} title="Ask Claude to rewrite this">
        <EIcon.Sparkle /> Rewrite with Claude
      </button>
    </div>
  );
}

// ─── Preview pane ────────────────────────────────────────────
function Preview({ markdown, streaming, onSelectionChange, paneRef }) {
  const ref = useRefE(null);

  // Render markdown
  const html = useMemoE(() => window.renderMarkdown(markdown), [markdown]);

  // Track selection within this preview
  useEffectE(() => {
    function check() {
      const sel = window.getSelection();
      if (!sel || sel.isCollapsed) { onSelectionChange(null); return; }
      if (!ref.current) return;
      const range = sel.getRangeAt(0);
      if (!ref.current.contains(range.commonAncestorContainer)) {
        return; // not in this pane
      }
      const text = sel.toString();
      if (!text.trim()) { onSelectionChange(null); return; }
      const rect = range.getBoundingClientRect();
      onSelectionChange({ text, rect, source: 'preview' });
    }
    document.addEventListener('selectionchange', check);
    return () => document.removeEventListener('selectionchange', check);
  }, [onSelectionChange]);

  if (!markdown || !markdown.trim()) {
    return (
      <div className="doc-empty">
        <div className="inner">
          <div className="glyph"><EIcon.Empty /></div>
          <h2>What do you want to write today?</h2>
          <p>Ask Claude on the left to draft something, or start typing in the editor — markdown supported.</p>
        </div>
      </div>
    );
  }
  return (
    <div
      ref={(el) => { ref.current = el; if (paneRef) paneRef.current = el; }}
      className="preview"
      dangerouslySetInnerHTML={{ __html: html + (streaming ? '<span class="stream-cursor"></span>' : '') }}
    />
  );
}

// ─── Source editor pane ──────────────────────────────────────
function SourceEditor({ markdown, onChange, disabled, onSelectionChange, paneRef }) {
  const ref = useRefE(null);

  useEffectE(() => {
    function check() {
      if (!ref.current) return;
      if (document.activeElement !== ref.current) { return; }
      const start = ref.current.selectionStart;
      const end = ref.current.selectionEnd;
      if (start === end) { onSelectionChange(null); return; }
      const text = ref.current.value.slice(start, end);
      if (!text.trim()) { onSelectionChange(null); return; }
      const r = ref.current.getBoundingClientRect();
      // Approximate rect: place above current selection (top of textarea + line guess)
      const before = ref.current.value.slice(0, start);
      const lines = before.split('\n').length;
      const lineHeight = 13.5 * 1.65;
      const top = r.top + 32 + (lines - 1) * lineHeight - ref.current.scrollTop;
      const rect = { left: r.left + r.width / 2, top: top, width: 0, height: 0 };
      onSelectionChange({ text, rect, source: 'editor' });
    }
    document.addEventListener('selectionchange', check);
    return () => document.removeEventListener('selectionchange', check);
  }, [onSelectionChange]);

  return (
    <div className="source-wrap">
      <textarea
        ref={(el) => { ref.current = el; if (paneRef) paneRef.current = el; }}
        className="source-editor"
        value={markdown}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        spellCheck={false}
        placeholder="# Start writing in markdown…"
      />
    </div>
  );
}

// ─── Document pane host ─────────────────────────────────────
function DocumentPane({
  title,
  setTitle,
  markdown,
  setMarkdown,
  mode,
  setMode,
  isStreaming,
  canUndo,
  canRedo,
  onUndo,
  onRedo,
  onOpenHistory,
  onExport,
  versionCount,
  onSelectionChange,
}) {
  const [titleVal, setTitleVal] = useStateE(title);
  useEffectE(() => { setTitleVal(title); }, [title]);

  const previewRef = useRefE(null);
  const editorRef = useRefE(null);

  // Auto-scroll preview to bottom while streaming
  useEffectE(() => {
    if (!isStreaming) return;
    const el = previewRef.current;
    if (el) {
      const scroller = el.closest('.doc-pane-half') || el.closest('.doc-scroll');
      if (scroller) scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' });
    }
  }, [markdown, isStreaming]);

  const wordCount = useMemoE(() => {
    if (!markdown) return 0;
    return markdown.trim().split(/\s+/).filter(Boolean).length;
  }, [markdown]);

  return (
    <main className="doc-pane">
      {isStreaming ? <div className="stream-progress"><div className="bar"></div></div> : null}
      <div className="doc-toolbar">
        <div className="doc-title-wrap">
          <div className="doc-icon"><EIcon.Doc /></div>
          <input
            className="doc-title"
            value={titleVal}
            onChange={(e) => setTitleVal(e.target.value)}
            onBlur={() => setTitle(titleVal.trim() || 'Untitled')}
            onKeyDown={(e) => { if (e.key === 'Enter') e.target.blur(); }}
            placeholder="Untitled"
          />
          <span className="doc-meta">{wordCount.toLocaleString()} words</span>
        </div>

        <div className="toolbar-group">
          <button
            className="icon-btn"
            onClick={onUndo}
            disabled={!canUndo}
            style={{ opacity: canUndo ? 1 : 0.35, cursor: canUndo ? 'pointer' : 'not-allowed' }}
            title="Undo (⌘Z)"
          ><EIcon.Undo /></button>
          <button
            className="icon-btn"
            onClick={onRedo}
            disabled={!canRedo}
            style={{ opacity: canRedo ? 1 : 0.35, cursor: canRedo ? 'pointer' : 'not-allowed' }}
            title="Redo (⌘⇧Z)"
          ><EIcon.Redo /></button>
          <div className="toolbar-sep" />
          <div className="mode-seg" role="tablist" aria-label="View mode">
            <button
              className={mode === 'preview' ? 'active' : ''}
              onClick={() => setMode('preview')}
              role="tab"
              aria-selected={mode === 'preview'}
            >
              <EIcon.Eye /> Preview
            </button>
            <button
              className={mode === 'edit' ? 'active' : ''}
              onClick={() => setMode('edit')}
              role="tab"
              aria-selected={mode === 'edit'}
            >
              <EIcon.Code /> Edit
            </button>
            <button
              className={mode === 'split' ? 'active' : ''}
              onClick={() => setMode('split')}
              role="tab"
              aria-selected={mode === 'split'}
            >
              <EIcon.Split /> Split
            </button>
          </div>
          <div className="toolbar-sep" />
          <button className="btn" onClick={onOpenHistory} title="Version history">
            <EIcon.History /> History
            {versionCount > 0 ? (
              <span style={{
                marginLeft: 4, fontSize: 10.5, fontWeight: 600,
                background: 'var(--paper-deep)', color: 'var(--ink-muted)',
                padding: '1px 5px', borderRadius: 4,
              }}>{versionCount}</span>
            ) : null}
          </button>
          <button className="btn" onClick={onExport} title="Download .md">
            <EIcon.Download />
          </button>
        </div>
      </div>

      <div className="doc-scroll">
        <div className={`doc-split ${mode === 'split' ? 'split' : 'single'}`}>
          {mode === 'split' ? (
            <React.Fragment>
              <div className="doc-pane-half">
                <div className="pane-label"><EIcon.Code /> Source</div>
                <SourceEditor
                  markdown={markdown}
                  onChange={setMarkdown}
                  disabled={isStreaming}
                  onSelectionChange={onSelectionChange}
                  paneRef={editorRef}
                />
              </div>
              <div className="doc-pane-half">
                <div className="pane-label"><EIcon.Eye /> Preview</div>
                <Preview
                  markdown={markdown}
                  streaming={isStreaming}
                  onSelectionChange={onSelectionChange}
                  paneRef={previewRef}
                />
              </div>
            </React.Fragment>
          ) : mode === 'edit' ? (
            <div className="doc-pane-half">
              <SourceEditor
                markdown={markdown}
                onChange={setMarkdown}
                disabled={isStreaming}
                onSelectionChange={onSelectionChange}
                paneRef={editorRef}
              />
            </div>
          ) : (
            <div className="doc-pane-half">
              <Preview
                markdown={markdown}
                streaming={isStreaming}
                onSelectionChange={onSelectionChange}
                paneRef={previewRef}
              />
            </div>
          )}
        </div>
      </div>
    </main>
  );
}

window.DocumentPane = DocumentPane;
window.SelectionToolbar = SelectionToolbar;
