import { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { CHROME_STORE, REPO, VSCODE_MARKETPLACE } from '../links';

function scrollToSection(id: string) {
  document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

export function DocsPage() {
  useEffect(() => {
    const fromPath = window.location.href.match(/docs[#/]+([\w-]+)/i)?.[1];
    const target = fromPath && fromPath !== 'docs' ? fromPath : undefined;
    if (target) {
      window.setTimeout(() => scrollToSection(target), 80);
    }
  }, []);

  const nav = [
    ['overview', 'Overview'],
    ['chrome', 'Chrome'],
    ['vscode', 'VS Code'],
    ['cli', 'CLI'],
    ['shared', 'Shared core'],
    ['install', 'Install'],
    ['privacy', 'Privacy'],
  ] as const;

  return (
    <div className="wrap docs-layout">
      <aside className="docs-nav" aria-label="Docs sections">
        {nav.map(([id, label]) => (
          <button key={id} type="button" className="nav-link-btn" onClick={() => scrollToSection(id)}>
            {label}
          </button>
        ))}
      </aside>

      <article className="docs-content">
        <h1>Documentation</h1>
        <p className="intro">
          LexAI is an open-source, bring-your-own-LLM assistant. This page covers every package and
          its features. Contributor setup lives on the{' '}
          <Link to="/contribute">Contribute</Link> page.
        </p>

        <section className="docs-block" id="overview">
          <h2>Overview</h2>
          <p>
            Three clients share one provider/prompt core. There is no LexAI backend — you supply an
            API key for OpenAI, Anthropic, Groq, or OpenRouter.
          </p>
          <ul>
            <li>
              <strong>Chrome</strong> — writing help on any webpage
            </li>
            <li>
              <strong>VS Code / Cursor</strong> — writing actions + workspace-aware Code Assist
            </li>
            <li>
              <strong>CLI</strong> — Prompt Builder for the terminal
            </li>
          </ul>
        </section>

        <section className="docs-block" id="chrome">
          <h2>Chrome extension</h2>
          <p>
            Manifest V3. Select text on any page, run an action, Replace or Copy. API key encrypted
            locally with tweetnacl secretbox.
          </p>
          <h3>Setup</h3>
          <p>
            Options page → choose provider (OpenAI, Anthropic, Groq, or OpenRouter) and paste your
            API key. There are no environment variables.
          </p>
          <h3>Features</h3>
          <ul>
            <li>Fix Grammar, Rephrase, Shorten, Expand, Explain, Make Prompt</li>
            <li>Writing styles: Formal, Casual, Academic, Creative, Concise</li>
            <li>Floating toolbar, right-click context menu, popup editor</li>
            <li>Prompt Builder — patterns, persona, output format</li>
            <li>Providers: OpenAI · Anthropic · Groq · OpenRouter</li>
            <li>Works in text boxes, email composers, forms, and contenteditable pages</li>
          </ul>
          <div className="docs-meta">
            <a className="btn btn-primary" href={CHROME_STORE} target="_blank" rel="noreferrer">
              Chrome Web Store
            </a>
            <a
              className="btn btn-ghost"
              href={`${REPO}/src/branch/main/packages/chrome`}
              target="_blank"
              rel="noreferrer"
            >
              Package README
            </a>
          </div>
        </section>

        <section className="docs-block" id="vscode">
          <h2>VS Code / Cursor extension</h2>
          <p>
            Editor twin of LexAI. Select text or code → action or Code Assist → Accept / Regenerate
            / Discard. Key lives in VS Code Secret Storage.
          </p>
          <p>
            Published listing:{' '}
            <a href={VSCODE_MARKETPLACE} target="_blank" rel="noreferrer">
              JuanKibin.lexai-vscode
            </a>
          </p>
          <h3>Setup</h3>
          <p>
            Command Palette → <code>LexAI: Open Settings</code> → provider, model, and API key.
            The key is stored in VS Code Secret Storage. There are no environment variables.
          </p>
          <h3>Code Assist</h3>
          <ul>
            <li>Freeform instruction in an inline prompt above the selection</li>
            <li>
              Workspace context: surrounding code, imports, and symbol definitions from other files
            </li>
            <li>Entry points: CodeLens, context menu, Command Palette, Activity Bar sidebar</li>
          </ul>
          <h3>Writing actions</h3>
          <ul>
            <li>Fix Grammar · Rephrase · Shorten · Expand · Explain · Make Prompt</li>
            <li>Writing styles + Prompt Builder option chips in the suggestion zone</li>
            <li>Suggestion UI: zone (default), side panel, or both</li>
            <li>Status bar: ready / processing / not configured</li>
            <li>Sidebar workspace panel for paste → run → Copy</li>
          </ul>
          <div className="docs-meta">
            <a className="btn btn-primary" href={VSCODE_MARKETPLACE} target="_blank" rel="noreferrer">
              VS Code Marketplace
            </a>
            <a
              className="btn btn-ghost"
              href={`${REPO}/src/branch/main/packages/vscode`}
              target="_blank"
              rel="noreferrer"
            >
              Package README
            </a>
          </div>
        </section>

        <section className="docs-block" id="cli">
          <h2>CLI — Prompt Builder</h2>
          <p>
            Improves a rough idea into a paste-ready engineered prompt before you send it to another
            agent.
          </p>
          <h3>Setup</h3>
          <p>Environment variables (PowerShell shown; bash uses <code>export NAME=value</code>):</p>
          <pre className="mono">{`$env:LEXAI_API_KEY = "sk-..."              # required
$env:LEXAI_PROVIDER = "openai"              # optional: openai | anthropic | groq | openrouter
$env:LEXAI_MODEL = "gpt-4o"                 # optional`}</pre>
          <p>
            Optional defaults file (never put the API key here): <code>~/.lexai/config.json</code>
          </p>
          <pre className="mono">{`{
  "provider": "openai",
  "model": "gpt-4o",
  "pattern": "role",
  "persona": "Expert Developer",
  "format": "Markdown",
  "style": "Concise"
}`}</pre>
          <p>
            Precedence: flags → config file → env → defaults. The key is always{' '}
            <code>LEXAI_API_KEY</code>.
          </p>
          <h3>Features</h3>
          <ul>
            <li>
              Command: <code>lexai prompt</code>
            </li>
            <li>
              Input from args, stdin, or <code>-f/--file</code>
            </li>
            <li>Flags: pattern, persona, format, style, provider, model</li>
            <li>
              Also <code>--list</code> (patterns, personas, formats, styles) and{' '}
              <code>--help</code>
            </li>
            <li>Engineered prompt on stdout (pipe-safe); progress and errors on stderr</li>
          </ul>
          <h3>Examples</h3>
          <pre className="mono">{`lexai prompt "add rate limiting to the express auth routes"

echo "debug flaky playwright on CI" | lexai prompt --pattern role

lexai prompt -f draft.txt --format Markdown --model gpt-4o`}</pre>
          <div className="docs-meta">
            <a
              className="btn btn-ghost"
              href={`${REPO}/src/branch/main/packages/cli`}
              target="_blank"
              rel="noreferrer"
            >
              Package README
            </a>
          </div>
        </section>

        <section className="docs-block" id="shared">
          <h2>Shared core</h2>
          <ul>
            <li>
              Location: <code>src/lib</code> (<code>providers</code>, <code>actions</code>,{' '}
              <code>types</code>)
            </li>
            <li>Chrome-only modules: crypto (key encryption), messaging helpers</li>
            <li>VS Code and CLI must not import Chrome-only modules</li>
          </ul>
        </section>

        <section className="docs-block" id="install">
          <h2>Install</h2>
          <p>Published builds:</p>
          <ul>
            <li>
              Chrome —{' '}
              <a href={CHROME_STORE} target="_blank" rel="noreferrer">
                Chrome Web Store
              </a>
            </li>
            <li>
              VS Code / Cursor —{' '}
              <a href={VSCODE_MARKETPLACE} target="_blank" rel="noreferrer">
                Visual Studio Marketplace
              </a>{' '}
              (<code>JuanKibin.lexai-vscode</code>)
            </li>
          </ul>
          <p style={{ marginTop: '1rem' }}>From source (Node.js 22+):</p>
          <pre className="mono">{`git clone https://git.juankibin.space/kibin/LexAI.git
cd LexAI
npm run install:all

# Chrome
npm run chrome:dev          # or chrome:build → load packages/chrome/.output/chrome-mv3

# VS Code
npm run vscode:build        # or install from Marketplace

# CLI
npm run cli:build
export LEXAI_API_KEY=sk-...          # required
export LEXAI_PROVIDER=openai         # optional: openai | anthropic | groq | openrouter
export LEXAI_MODEL=gpt-4o            # optional
node packages/cli/out/cli.js prompt "your rough idea"

# Website
npm run website:dev`}</pre>
        </section>

        <section className="docs-block" id="privacy">
          <h2>Privacy</h2>
          <ul>
            <li>No LexAI backend, account, or subscription</li>
            <li>No LexAI telemetry</li>
            <li>
              Chrome: encrypted key in <code>chrome.storage.local</code>
            </li>
            <li>VS Code: Secret Storage</li>
            <li>
              CLI: <code>LEXAI_API_KEY</code> required; optional <code>LEXAI_PROVIDER</code> and{' '}
              <code>LEXAI_MODEL</code>. Never store the key in <code>~/.lexai/config.json</code>
            </li>
            <li>Text is sent only to the LLM provider you configure</li>
          </ul>
        </section>
      </article>
    </div>
  );
}
