// pages-docs.jsx
// Editorial/Brutalist API Documentation Page
// Uses React (window.React) and global t(), navigate()

/**
 * PURE HELPERS
 * Exposed via window.__docsInternals
 */

const buildCurlExample = (endpointPath, body) => {
  const baseUrl = "https://ruuapi.com";
  const jsonBody = JSON.stringify(body);
  return `curl -X POST ${baseUrl}${endpointPath} \\
  -H "Content-Type: application/json" \\
  -d '${jsonBody}'`;
};

const parseEndpointMeta = (slug) => {
  const map = {
    'schema-build': { path: '/api/agent/schema-build', method: 'POST', tier: 'free', rate: 1000 },
    'schema-validate': { path: '/api/agent/schema-validate', method: 'POST', tier: 'free', rate: 1000 },
    'llms-txt-build': { path: '/api/agent/llms-txt-build', method: 'POST', tier: 'free', rate: 1000 },
    'llms-txt-validate': { path: '/api/agent/llms-txt-validate', method: 'POST', tier: 'free', rate: 1000 },
    'schema-autofill': { path: '/api/tools/schema/autofill', method: 'POST', tier: 'gated', rate: 100 }
  };
  return map[slug] || null;
};

/**
 * SYNTAX HIGHLIGHTING
 * Simple regex-based highlighter for the brutalist UI
 */
const highlightCode = (code, lang) => {
  if (!code) return '';
  
  let escaped = code
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");

  // Keywords
  const keywords = /\b(function|return|import|const|let|var|async|await|if|else|from|interface|export|try|catch|new|class|throw|print|interface|await|fetch|method|headers|body)\b/g;
  escaped = escaped.replace(keywords, '<span style="color: var(--accent)">$1</span>');

  // Strings
  const strings = /(&quot;.*?&quot;|&#039;.*?&#039;)/g;
  escaped = escaped.replace(strings, '<span style="color: #98d4a3">$1</span>');

  // Comments
  const comments = /(#.*|\/\/.*)/g;
  escaped = escaped.replace(comments, '<span style="color: var(--ink-3)">$1</span>');

  // Numbers
  const numbers = /\b(\d+)\b/g;
  escaped = escaped.replace(numbers, '<span style="color: #f0a050">$1</span>');

  // URLs
  const urls = /(https?:\/\/[^\s&]+)/g;
  escaped = escaped.replace(urls, '<span style="color: #80c8f0">$1</span>');

  return escaped;
};

/**
 * COMPONENTS
 */

const CodeBlock = ({ code, lang, style = {} }) => {
  return (
    <pre style={{
      background: 'var(--ink)',
      color: 'var(--paper)',
      fontFamily: 'var(--mono)',
      fontSize: '13px',
      padding: '16px',
      borderRadius: '0',
      border: '2px solid var(--ink)',
      overflowX: 'auto',
      margin: 0,
      whiteSpace: 'pre-wrap',
      wordBreak: 'break-all',
      ...style
    }}>
      <code dangerouslySetInnerHTML={{ __html: highlightCode(code, lang) }} />
    </pre>
  );
};

const EndpointCard = ({ slug, meta, description, exampleRequest, exampleResponse }) => {
  
  const { t } = useT();
  const [activeTab, setActiveTab] = React.useState('curl');
  const [tryItLoading, setTryItLoading] = React.useState(false);
  const [tryItResponse, setTryItResponse] = React.useState(null);
  const [isCopied, setIsCopied] = React.useState(false);

  const pythonSnippet = `import httpx

resp = httpx.post(
    "https://ruuapi.com${meta.path}",
    json=${JSON.stringify(exampleRequest, null, 4)},
    timeout=10
)
print(resp.json())`;

  const jsSnippet = `const resp = await fetch("https://ruuapi.com${meta.path}", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(${JSON.stringify(exampleRequest)})
});
const data = await resp.json();`;

  const tsSnippet = `interface APIResponse { 
  ok: boolean; 
  [key: string]: any; 
}

const resp = await fetch("https://ruuapi.com${meta.path}", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(${JSON.stringify(exampleRequest)})
});
const data: APIResponse = await resp.json();`;

  const curlSnippet = buildCurlExample(meta.path, exampleRequest);

  const snippets = {
    curl: curlSnippet,
    python: pythonSnippet,
    js: jsSnippet,
    ts: tsSnippet
  };

  const handleTryIt = async () => {
    setTryItLoading(true);
    setTryItResponse(null);
    try {
      const res = await fetch(`https://ruuapi.com${meta.path}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(exampleRequest)
      });
      const data = await res.json();
      setTryItResponse(JSON.stringify(data, null, 2));
    } catch (err) {
      setTryItResponse(`Error: ${err.message}`);
    } finally {
      setTryItLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(curlSnippet);
    setIsCopied(true);
    setTimeout(() => setIsCopied(false), 2000);
  };

  return (
    <div id={`ep-${slug}`} style={{
      border: '2px solid var(--ink)',
      marginBottom: '48px',
      background: 'var(--paper)',
      boxShadow: '4px 4px 0 var(--ink)'
    }}>
      {/* Header Row */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        padding: '12px 16px',
        borderBottom: '2px solid var(--ink)',
        background: 'var(--paper-2)',
        gap: '12px',
        flexWrap: 'wrap'
      }}>
        <span style={{
          background: 'var(--ink)',
          color: 'var(--paper)',
          padding: '2px 8px',
          fontWeight: 'bold',
          fontSize: '12px',
          fontFamily: 'var(--mono)'
        }}>{meta.method}</span>
        
        <span style={{ 
          fontFamily: 'var(--mono)', 
          fontSize: '14px', 
          fontWeight: '600',
          color: 'var(--ink)'
        }}>{meta.path}</span>

        <div style={{ flex: 1 }} />

        {meta.tier === 'free' ? (
          <span className="stamp" style={{
            background: 'var(--accent)',
            color: 'var(--ink)',
            padding: '2px 8px',
            fontSize: '10px',
            fontWeight: '900',
            border: '1px solid var(--ink)',
            textTransform: 'uppercase'
          }}>
            {t('docs.endpoint.free')} · {meta.rate}/h · NO AUTH
          </span>
        ) : (
          <span className="stamp" style={{
            background: 'var(--ink)',
            color: 'var(--paper)',
            padding: '2px 8px',
            fontSize: '10px',
            fontWeight: '900',
            border: '1px solid var(--ink)',
            textTransform: 'uppercase'
          }}>
            {t('docs.endpoint.gated')} · {meta.rate}/h · BEARER AUTH
          </span>
        )}
      </div>

      <div style={{ padding: '24px 24px 0' }}>
        <p style={{ margin: '0 0 24px', fontSize: '16px', color: 'var(--ink-2)', lineHeight: '1.5' }}>
          {description}
        </p>
      </div>

      {/* Panels Grid */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: window.innerWidth < 1200 ? '1fr' : '1.2fr 1.2fr 1fr',
        borderTop: '2px solid var(--ink)',
      }}>
        {/* Request Panel */}
        <div style={{ borderRight: window.innerWidth < 1200 ? 'none' : '2px solid var(--ink)', borderBottom: window.innerWidth < 1200 ? '2px solid var(--ink)' : 'none' }}>
          <div style={{ padding: '8px 16px', borderBottom: '2px solid var(--ink)', background: 'var(--paper-3)', fontSize: '11px', fontWeight: 'bold', fontFamily: 'var(--mono)' }}>REQUEST BODY</div>
          <CodeBlock code={JSON.stringify(exampleRequest, null, 2)} lang="json" style={{ border: 'none', height: '300px' }} />
        </div>

        {/* Response Panel */}
        <div style={{ borderRight: window.innerWidth < 1200 ? 'none' : '2px solid var(--ink)', borderBottom: window.innerWidth < 1200 ? '2px solid var(--ink)' : 'none' }}>
          <div style={{ padding: '8px 16px', borderBottom: '2px solid var(--ink)', background: 'var(--paper-3)', fontSize: '11px', fontWeight: 'bold', fontFamily: 'var(--mono)' }}>EXAMPLE RESPONSE</div>
          <CodeBlock code={JSON.stringify(exampleResponse, null, 2)} lang="json" style={{ border: 'none', height: '300px' }} />
        </div>

        {/* Try-It Panel */}
        <div style={{ background: 'var(--paper-2)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: '8px 16px', borderBottom: '2px solid var(--ink)', background: 'var(--paper-3)', fontSize: '11px', fontWeight: 'bold', fontFamily: 'var(--mono)' }}>{t('docs.tryit.response')}</div>
          <div style={{ padding: '16px', flex: 1, display: 'flex', flexDirection: 'column', gap: '12px' }}>
            <div style={{ display: 'flex', gap: '8px' }}>
              <button 
                className="btn" 
                onClick={handleTryIt} 
                disabled={tryItLoading || meta.tier === 'gated'}
                style={{ flex: 1 }}
              >
                {tryItLoading ? '...' : t('docs.tryit.run')}
              </button>
              <button 
                className="btn btn-ghost" 
                onClick={copyToClipboard}
                style={{ minWidth: '100px' }}
              >
                {isCopied ? t('docs.tryit.copied') : t('docs.tryit.copy')}
              </button>
            </div>
            
            <div style={{
              flex: 1,
              background: 'var(--ink)',
              color: 'var(--accent)',
              fontFamily: 'var(--mono)',
              fontSize: '12px',
              padding: '12px',
              border: '2px solid var(--ink)',
              overflowY: 'auto',
              minHeight: '200px',
              maxHeight: '228px'
            }}>
              {tryItResponse || (meta.tier === 'gated' ? '> Auth required for this endpoint.' : '> Click Run to test the API...')}
            </div>
          </div>
        </div>
      </div>

      {/* Tabs Section */}
      <div style={{ borderTop: '2px solid var(--ink)' }}>
        <div style={{ display: 'flex', background: 'var(--paper-3)', borderBottom: '2px solid var(--ink)' }}>
          {['curl', 'python', 'js', 'ts'].map(tab => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              style={{
                padding: '10px 20px',
                border: 'none',
                borderRight: '2px solid var(--ink)',
                background: activeTab === tab ? 'var(--accent)' : 'transparent',
                color: 'var(--ink)',
                fontFamily: 'var(--mono)',
                fontSize: '12px',
                fontWeight: 'bold',
                cursor: 'pointer',
                textTransform: 'uppercase'
              }}
            >
              {t(`docs.tab.${tab}`)}
            </button>
          ))}
        </div>
        <CodeBlock code={snippets[activeTab]} lang={activeTab} style={{ border: 'none' }} />
      </div>
    </div>
  );
};

/**
 * MAIN PAGE COMPONENT
 */
const DocsPage = () => {
  
  const { t } = useT();
  const [activeNavSection, setActiveNavSection] = React.useState('quick-start');
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);

  React.useEffect(() => {
    const handleResize = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  React.useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          setActiveNavSection(entry.target.id);
        }
      });
    }, { threshold: 0.2, rootMargin: '-10% 0px -70% 0px' });

    const sections = ['quick-start', 'endpoints', 'ep-schema-build', 'ep-schema-validate', 'ep-llms-txt-build', 'ep-llms-txt-validate', 'ep-autofill', 'sdks', 'rate-limits', 'errors', 'wordpress', 'agent-guide'];
    sections.forEach(id => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });

    return () => observer.disconnect();
  }, []);

  const navLinks = [
    { id: 'quick-start', label: t('docs.nav.quickstart') },
    { id: 'endpoints', label: t('docs.nav.endpoints'), children: [
      { id: 'ep-schema-build', label: 'Schema Build' },
      { id: 'ep-schema-validate', label: 'Schema Validate' },
      { id: 'ep-llms-txt-build', label: 'llms.txt Build' },
      { id: 'ep-llms-txt-validate', label: 'llms.txt Validate' },
      { id: 'ep-autofill', label: 'Schema Autofill (token-gated)' },
    ]},
    { id: 'sdks', label: t('docs.nav.sdks') },
    { id: 'rate-limits', label: t('docs.nav.rate') },
    { id: 'errors', label: t('docs.nav.errors') },
    { id: 'wordpress', label: t('docs.nav.wordpress') },
    { id: 'agent-guide', label: t('docs.nav.agents') },
  ];

  const scrollTo = (id) => {
    const el = document.getElementById(id);
    if (el) {
      const offset = 20;
      const bodyRect = document.body.getBoundingClientRect().top;
      const elementRect = el.getBoundingClientRect().top;
      const elementPosition = elementRect - bodyRect;
      const offsetPosition = elementPosition - offset;

      window.scrollTo({
        top: offsetPosition,
        behavior: 'smooth'
      });
    }
  };

  return (
    <div style={{ 
      background: 'var(--paper)', 
      color: 'var(--ink)', 
      minHeight: '100vh', 
      fontFamily: 'var(--sans)' 
    }}>
      {/* HERO BLOCK */}
      <div style={{
        borderBottom: '4px solid var(--ink)',
        padding: isMobile ? '40px 24px' : '72px 56px 56px',
        background: 'var(--paper)',
        position: 'relative',
        overflow: 'hidden'
      }}>
        <div style={{ position: 'relative', zIndex: 2 }}>
          <span className="stamp" style={{
            background: 'var(--accent)',
            border: '2px solid var(--ink)',
            padding: '4px 12px',
            fontSize: '14px',
            fontWeight: '900',
            display: 'inline-block',
            marginBottom: '24px',
            transform: 'rotate(-1deg)'
          }}>
            {t('docs.hero.stamp')}
          </span>
          
          <h1 className="serif" style={{
            fontSize: isMobile ? '48px' : '84px',
            lineHeight: '0.9',
            margin: '0 0 24px',
            letterSpacing: '-0.03em',
            maxWidth: '900px'
          }}>
            {t('docs.hero.title.a')} <em style={{ color: 'var(--accent)', fontStyle: 'italic', textDecoration: 'underline' }}>{t('docs.hero.title.hl')}</em>
          </h1>
          
          <p style={{
            fontSize: isMobile ? '18px' : '24px',
            lineHeight: '1.4',
            maxWidth: '650px',
            margin: '0 0 32px',
            color: 'var(--ink-2)'
          }}>
            {t('docs.hero.sub')}
          </p>

          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            fontSize: '13px',
            fontWeight: 'bold',
            color: 'var(--ink-2)',
            textTransform: 'uppercase',
            letterSpacing: '0.05em'
          }}>
            <span style={{ width: '8px', height: '8px', background: 'var(--accent)', borderRadius: '50%', border: '1px solid var(--ink)' }} />
            {t('docs.hero.trust')}
          </div>
        </div>
      </div>

      {/* LAYOUT GRID */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '260px 1fr',
        minHeight: 'calc(100vh - 300px)'
      }}>
        {/* SIDEBAR */}
        {!isMobile && (
          <aside className="sticky" style={{
            top: 0,
            height: '100vh',
            borderRight: '2px solid var(--ink)',
            padding: '40px 24px',
            overflowY: 'auto',
            background: 'var(--paper-2)'
          }}>
            <nav style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
              {navLinks.map(link => (
                <div key={link.id} style={{ marginBottom: '12px' }}>
                  <button
                    onClick={() => scrollTo(link.id)}
                    style={{
                      width: '100%',
                      textAlign: 'left',
                      padding: '8px 12px',
                      background: activeNavSection === link.id ? 'var(--accent)' : 'transparent',
                      border: activeNavSection === link.id ? '2px solid var(--ink)' : '2px solid transparent',
                      fontFamily: 'var(--sans)',
                      fontSize: '14px',
                      fontWeight: '800',
                      cursor: 'pointer',
                      transition: '0.1s',
                      boxShadow: activeNavSection === link.id ? '3px 3px 0 var(--ink)' : 'none',
                      textTransform: 'uppercase'
                    }}
                  >
                    {link.label}
                  </button>
                  {link.children && (
                    <div style={{ display: 'flex', flexDirection: 'column', marginTop: '4px', borderLeft: '2px solid var(--ink-3)', marginLeft: '12px' }}>
                      {link.children.map(child => (
                        <button
                          key={child.id}
                          onClick={() => scrollTo(child.id)}
                          style={{
                            textAlign: 'left',
                            padding: '6px 16px',
                            background: activeNavSection === child.id ? 'var(--accent)' : 'transparent',
                            border: 'none',
                            fontFamily: 'var(--sans)',
                            fontSize: '12px',
                            fontWeight: activeNavSection === child.id ? '800' : '500',
                            cursor: 'pointer',
                            color: activeNavSection === child.id ? 'var(--ink)' : 'var(--ink-2)'
                          }}
                        >
                          {child.label}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              ))}
            </nav>
          </aside>
        )}

        {/* MAIN CONTENT */}
        <main style={{
          padding: isMobile ? '32px 24px' : '56px 64px',
          maxWidth: '1100px'
        }}>
          {/* QUICK START */}
          <section id="quick-start" style={{ marginBottom: '80px' }}>
            <h2 className="serif" style={{ fontSize: '48px', margin: '0 0 16px' }}>Quick start</h2>
            <p style={{ fontSize: '18px', color: 'var(--ink-2)', marginBottom: '32px' }}>
              No signup. No API key. Make your first request in 30 seconds.
            </p>
            <div style={{ border: '2px solid var(--ink)', boxShadow: '6px 6px 0 var(--ink)' }}>
              <div style={{ padding: '12px 16px', background: 'var(--paper-3)', borderBottom: '2px solid var(--ink)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: '#ff5f56' }} />
                <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: '#ffbd2e' }} />
                <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: '#27c93f' }} />
                <span style={{ marginLeft: '8px', fontSize: '12px', fontWeight: 'bold', fontFamily: 'var(--mono)', color: 'var(--ink-3)' }}>terminal — bash</span>
              </div>
              <CodeBlock 
                code={buildCurlExample('/api/agent/schema-build', {
                  primary_type: 'Article',
                  bundle: ['Article', 'FAQPage'],
                  fields: { headline: 'My Article', datePublished: '2026-05-15', author: 'Jane Doe' }
                })} 
                lang="bash" 
                style={{ border: 'none' }}
              />
            </div>
          </section>

          {/* ENDPOINT REFERENCE */}
          <section id="endpoints" style={{ marginBottom: '80px' }}>
            <h2 className="serif" style={{ fontSize: '48px', margin: '0 0 16px' }}>{t('docs.nav.endpoints')}</h2>
            <p style={{ fontSize: '18px', color: 'var(--ink-2)', marginBottom: '48px' }}>
              Base URL: <code style={{ background: 'var(--paper-2)', padding: '2px 6px', border: '1px solid var(--ink)' }}>https://ruuapi.com</code>
            </p>

            <EndpointCard 
              slug="schema-build"
              meta={parseEndpointMeta('schema-build')}
              description="Generate valid JSON-LD schema markup from a flat key-value object of fields. Supports bundles like Article+FAQPage."
              exampleRequest={{
                primary_type: 'Article',
                bundle: ['Article', 'FAQPage'],
                fields: {
                  headline: 'My Article',
                  datePublished: '2026-05-15',
                  author: 'Jane Doe'
                }
              }}
              exampleResponse={{
                ok: true,
                jsonld: {
                  '@context': 'https://schema.org',
                  '@type': ['Article', 'FAQPage'],
                  headline: 'My Article',
                  datePublished: '2026-05-15'
                },
                grade: 'A',
                warnings: []
              }}
            />

            <EndpointCard 
              slug="schema-validate"
              meta={parseEndpointMeta('schema-validate')}
              description="Validate JSON-LD against Schema.org constraints and check for common SEO errors."
              exampleRequest={{
                jsonld: {
                  '@context': 'https://schema.org',
                  '@type': 'Article',
                  headline: 'Test Article'
                }
              }}
              exampleResponse={{
                ok: true,
                valid: true,
                errors: [],
                warnings: ["Missing 'image' field", "Missing 'author' field"]
              }}
            />

            <EndpointCard 
              slug="llms-txt-build"
              meta={parseEndpointMeta('llms-txt-build')}
              description="Generate an optimized llms.txt file for your site to guide AI agents and crawlers."
              exampleRequest={{
                site_name: 'My Site',
                description: 'AI-native content platform',
                features: ['Schema markup', 'llms.txt generation']
              }}
              exampleResponse={{
                ok: true,
                content: "# My Site\n\n> AI-native content platform\n\n## Features\n- Schema markup\n- llms.txt generation"
              }}
            />

            <EndpointCard 
              slug="llms-txt-validate"
              meta={parseEndpointMeta('llms-txt-validate')}
              description="Validate an existing llms.txt file for syntax and recommended sections."
              exampleRequest={{
                content: "# My Site\n> Description\n## About\nContent here."
              }}
              exampleResponse={{
                ok: true,
                valid: true,
                score: 85,
                recommendations: ["Add a 'Tools' section"]
              }}
            />

            <EndpointCard 
              slug="autofill"
              meta={parseEndpointMeta('schema-autofill')}
              description="Automatically fill schema fields from a URL using our high-speed crawler and LLM extractor."
              exampleRequest={{
                url: 'https://example.com/blog/post-1',
                type: 'Article'
              }}
              exampleResponse={{
                ok: true,
                fields: {
                  headline: "Extracted Headline",
                  author: "John Smith",
                  datePublished: "2026-01-01"
                }
              }}
            />
          </section>

          {/* SDKs */}
          <section id="sdks" style={{ marginBottom: '80px' }}>
            <h2 className="serif" style={{ fontSize: '48px', margin: '0 0 16px' }}>{t('docs.nav.sdks')}</h2>
            <p style={{ fontSize: '18px', color: 'var(--ink-2)', marginBottom: '32px' }}>
              Use any HTTP client. No SDK required. Examples in curl, Python (httpx), and JS (fetch).
            </p>
            <CodeBlock 
              lang="python"
              code={`# Python example using httpx
import httpx

with httpx.Client(base_url="https://ruuapi.com") as client:
    resp = client.post("/api/agent/schema-build", json={
        "primary_type": "Article",
        "fields": {"headline": "Hello World"}
    })
    print(resp.json())`}
            />
          </section>

          {/* RATE LIMITS */}
          <section id="rate-limits" style={{ marginBottom: '80px' }}>
            <h2 className="serif" style={{ fontSize: '48px', margin: '0 0 16px' }}>{t('docs.nav.rate')}</h2>
            <p style={{ fontSize: '18px', color: 'var(--ink-2)', marginBottom: '32px' }}>
              CORS is open (*). Requests over the limit return HTTP 429.
            </p>
            <div style={{ overflowX: 'auto' }}>
              <table style={{
                width: '100%',
                borderCollapse: 'collapse',
                border: '2px solid var(--ink)',
                fontFamily: 'var(--mono)',
                fontSize: '14px'
              }}>
                <thead>
                  <tr style={{ background: 'var(--paper-3)', textAlign: 'left' }}>
                    <th style={{ padding: '12px', border: '2px solid var(--ink)' }}>ENDPOINT</th>
                    <th style={{ padding: '12px', border: '2px solid var(--ink)' }}>LIMIT</th>
                    <th style={{ padding: '12px', border: '2px solid var(--ink)' }}>AUTH</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>/api/agent/*</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>1000/hour/IP</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>None</td>
                  </tr>
                  <tr style={{ background: 'var(--paper-2)' }}>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>/api/tools/*</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>100/hour</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>Bearer Token</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </section>

          {/* ERRORS */}
          <section id="errors" style={{ marginBottom: '80px' }}>
            <h2 className="serif" style={{ fontSize: '48px', margin: '0 0 16px' }}>{t('docs.nav.errors')}</h2>
            <div style={{ overflowX: 'auto', marginBottom: '32px' }}>
              <table style={{
                width: '100%',
                borderCollapse: 'collapse',
                border: '2px solid var(--ink)',
                fontFamily: 'var(--sans)',
                fontSize: '14px'
              }}>
                <thead>
                  <tr style={{ background: 'var(--paper-3)', textAlign: 'left' }}>
                    <th style={{ padding: '12px', border: '2px solid var(--ink)', fontWeight: 'bold' }}>CODE</th>
                    <th style={{ padding: '12px', border: '2px solid var(--ink)', fontWeight: 'bold' }}>MEANING</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)', fontFamily: 'var(--mono)' }}>200</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>Success</td>
                  </tr>
                  <tr>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)', fontFamily: 'var(--mono)' }}>422</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>Validation error (check your JSON body)</td>
                  </tr>
                  <tr>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)', fontFamily: 'var(--mono)' }}>429</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>Rate limit exceeded</td>
                  </tr>
                  <tr>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)', fontFamily: 'var(--mono)' }}>500</td>
                    <td style={{ padding: '12px', border: '2px solid var(--ink)' }}>Server error</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <CodeBlock 
              lang="json"
              code={JSON.stringify({
                ok: false,
                error: "Validation error",
                details: ["'primary_type' is required"]
              }, null, 2)}
            />
          </section>

          {/* WORDPRESS INTEGRATION */}
          <section id="wordpress" style={{ marginBottom: '80px' }}>
            <h2 className="serif" style={{ fontSize: '48px', margin: '0 0 16px' }}>{t('docs.nav.wordpress')}</h2>
            <p style={{ fontSize: '18px', color: 'var(--ink-2)', marginBottom: '32px' }}>
              {t('docs.wordpress.intro')}
            </p>

            <div style={{
              display: 'grid',
              gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
              gap: '24px',
              marginBottom: '40px'
            }}>
              {[
                { num: '1', title: t('docs.wordpress.step1title'), body: t('docs.wordpress.step1body') },
                { num: '2', title: t('docs.wordpress.step2title'), body: t('docs.wordpress.step2body') },
                { num: '3', title: t('docs.wordpress.step3title'), body: t('docs.wordpress.step3body') },
              ].map(step => (
                <div key={step.num} style={{
                  border: '2px solid var(--ink)',
                  padding: '24px',
                  background: 'var(--paper-2)',
                  boxShadow: '4px 4px 0 var(--ink)'
                }}>
                  <div style={{
                    fontSize: '32px',
                    fontWeight: '900',
                    color: 'var(--accent)',
                    marginBottom: '12px',
                    fontFamily: 'var(--serif)'
                  }}>{step.num}</div>
                  <h3 style={{ margin: '0 0 8px', fontSize: '16px', fontWeight: '700' }}>{step.title}</h3>
                  <p style={{ margin: 0, fontSize: '14px', color: 'var(--ink-2)', lineHeight: '1.5' }}>{step.body}</p>
                </div>
              ))}
            </div>

            <div style={{ display: 'flex', gap: '16px', alignItems: 'center', flexWrap: 'wrap', marginBottom: '32px' }}>
              <a
                href="https://github.com/mehmetnadir/blog-writer-for-seo-and-geo/releases"
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: 'inline-block',
                  padding: '14px 28px',
                  background: 'var(--accent)',
                  color: 'var(--ink)',
                  fontWeight: '700',
                  fontSize: '15px',
                  textDecoration: 'none',
                  border: '2px solid var(--ink)',
                  boxShadow: '3px 3px 0 var(--ink)'
                }}
              >
                {t('docs.wordpress.download')}
              </a>
              <span style={{ fontSize: '13px', color: 'var(--ink-3)' }}>
                {t('docs.wordpress.license')}
              </span>
            </div>

            <div style={{
              padding: '20px 24px',
              background: 'var(--paper-3)',
              border: '1px solid var(--ink-3)',
              borderRadius: '2px',
              fontSize: '13px',
              color: 'var(--ink-2)',
              fontFamily: 'var(--mono)'
            }}>
              <strong style={{ color: 'var(--ink)', fontFamily: 'var(--sans)' }}>{t('docs.wordpress.featurestitle')}</strong>
              <ul style={{ margin: '8px 0 0', paddingLeft: '20px', lineHeight: '2' }}>
                <li>{t('docs.wordpress.feature1')}</li>
                <li>{t('docs.wordpress.feature2')}</li>
                <li>{t('docs.wordpress.feature3')}</li>
                <li>{t('docs.wordpress.feature4')}</li>
              </ul>
            </div>
          </section>

          {/* AGENT GUIDE */}
          <section id="agent-guide" style={{
            background: 'var(--ink)',
            color: 'var(--paper)',
            padding: isMobile ? '32px 24px' : '64px',
            borderTop: '8px solid var(--accent)',
            boxShadow: '8px 8px 0 var(--accent)',
            marginBottom: '100px'
          }}>
            <h2 className="serif" style={{ fontSize: '56px', margin: '0 0 24px', color: 'var(--accent)' }}>
              {t('docs.agents.title')}
            </h2>
            <p style={{ fontSize: '20px', lineHeight: '1.6', marginBottom: '40px', color: 'var(--paper-3)' }}>
              {t('docs.agents.body')}
            </p>
            
            <CodeBlock 
              lang="python"
              style={{ background: '#1a1a1a', border: '2px solid var(--accent)', marginBottom: '40px' }}
              code={`# High-level Agentic tool implementation
import json

def build_schema(params: dict):
    """Call ruuapi schema-build tool"""
    return httpx.post("https://ruuapi.com/api/agent/schema-build", json=params).json()

# Discovery
# GET https://ruuapi.com/api/agent/<endpoint>/example 
# returns canned request bodies for few-shot prompting.`}
            />

            <div style={{
              padding: '24px',
              borderLeft: '4px solid var(--accent)',
              background: 'rgba(198, 242, 78, 0.05)',
              fontSize: '16px',
              fontStyle: 'italic',
              color: 'var(--paper-2)'
            }}>
              {t('docs.agents.cite')}
            </div>
          </section>
        </main>
      </div>

      {/* FOOTER STRIP */}
      <footer style={{
        borderTop: '4px solid var(--ink)',
        padding: '32px 56px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        background: 'var(--ink)',
        color: 'var(--paper)',
        fontSize: '12px',
        fontFamily: 'var(--mono)',
        textTransform: 'uppercase'
      }}>
        <div>&copy; 2026 RUUAPI.COM · OPEN API</div>
        <div style={{ display: 'flex', gap: '24px' }}>
          <a href="#" style={{ color: 'var(--accent)', textDecoration: 'none' }}>GITHUB</a>
          <a href="#" style={{ color: 'var(--accent)', textDecoration: 'none' }}>STATUS</a>
          <a href="#" style={{ color: 'var(--accent)', textDecoration: 'none' }}>TOS</a>
        </div>
      </footer>
    </div>
  );
};

// EXPORTS
window.__docsInternals = { buildCurlExample, parseEndpointMeta };
Object.assign(window, { DocsPage });
