'use client';

/**
 * API Reference: Live URLs & CDN
 *
 * Based on docs/api/live-url.md
 */

import { TipBox } from '@/components/docs/shared/TipBox';
import { Table } from '@/components/docs/shared/Table';
import { CodeBlock } from '@/components/docs/shared/CodeBlock';
import { DocPage } from '@/components/docs/layout/DocPage';
import {
  Hero,
  SectionHeader,
  InlineCode,
  EndpointCard,
} from '@/components/docs/blocks';

const tocItems = [
  { id: 'overview', text: 'Overview', level: 2 },
  { id: 'url-architecture', text: 'URL Architecture', level: 2 },
  { id: 'cdn-serving', text: 'CDN Image Serving', level: 2 },
  { id: 'live-generation', text: 'Live URL Generation', level: 2 },
  { id: 'cache-behavior', text: 'Cache Behavior', level: 2 },
  { id: 'rate-limiting', text: 'IP Rate Limiting', level: 2 },
  { id: 'scope-management', text: 'Scope Management', level: 2 },
  { id: 'use-cases', text: 'Use Cases', level: 2 },
  { id: 'next-steps', text: 'Next Steps', level: 2 },
];

const urlPatterns = [
  ['/{org}/{proj}/img/{uuid}', 'Direct image by UUID', 'Caddy → MinIO (public)'],
  ['/{org}/{proj}/img/@{alias}', 'Image by alias', 'Caddy → API → MinIO'],
  ['/{org}/{proj}/live/{scope}?prompt=...', 'Live generation', 'Caddy → API → MinIO'],
];

const liveQueryParams = [
  { name: 'prompt', type: 'string', required: true, default: '-', description: 'Image description' },
  { name: 'aspectRatio', type: 'string', required: false, default: '"1:1"', description: 'Aspect ratio' },
  { name: 'autoEnhance', type: 'boolean', required: false, default: 'true', description: 'Enable prompt enhancement' },
];

const cacheHitHeaders = [
  ['Content-Type', 'image/jpeg'],
  ['Cache-Control', 'public, max-age=31536000'],
  ['X-Cache-Status', 'HIT'],
  ['X-Scope', 'Scope identifier'],
  ['X-Image-Id', 'Image UUID'],
];

const cacheMissHeaders = [
  ['Content-Type', 'image/jpeg'],
  ['Cache-Control', 'public, max-age=31536000'],
  ['X-Cache-Status', 'MISS'],
  ['X-Scope', 'Scope identifier'],
  ['X-Generation-Id', 'Generation UUID'],
  ['X-Image-Id', 'Image UUID'],
  ['X-RateLimit-Limit', '10'],
  ['X-RateLimit-Remaining', 'Remaining requests'],
  ['X-RateLimit-Reset', 'Seconds until reset'],
];

const rateLimits = [
  ['New generations', '10 per hour per IP'],
  ['Cache hits', 'Unlimited'],
];

const scopeParams = [
  { name: 'slug', type: 'string', required: true, default: '-', description: 'Unique identifier' },
  { name: 'allowNewGenerations', type: 'boolean', required: false, default: 'true', description: 'Allow new generations' },
  { name: 'newGenerationsLimit', type: 'number', required: false, default: '30', description: 'Max generations in scope' },
  { name: 'meta', type: 'object', required: false, default: '{}', description: 'Custom metadata' },
];

const errorCodes = [
  ['400', 'SCOPE_INVALID_FORMAT', 'Invalid scope slug format'],
  ['403', 'SCOPE_CREATION_DISABLED', 'New scope creation not allowed'],
  ['404', 'ORG_NOT_FOUND', 'Organization not found'],
  ['404', 'PROJECT_NOT_FOUND', 'Project not found'],
  ['404', 'SCOPE_NOT_FOUND', 'Scope does not exist'],
  ['409', 'SCOPE_ALREADY_EXISTS', 'Scope slug already in use'],
  ['429', 'IP_RATE_LIMIT_EXCEEDED', 'IP rate limit (10/hour) exceeded'],
  ['429', 'SCOPE_GENERATION_LIMIT_EXCEEDED', 'Scope limit reached'],
];

export default function LiveUrlsPage() {
  return (
    <DocPage
      breadcrumbItems={[
        { label: 'Documentation', href: '/docs' },
        { label: 'API Reference', href: '/docs/api' },
        { label: 'Live URLs' },
      ]}
      tocItems={tocItems}
      nextSteps={{
        links: [
          {
            href: '/docs/api/generate',
            title: 'Image Generation',
            description: 'API-based generation with full control over parameters.',
            accent: 'primary',
          },
          {
            href: '/docs/api/advanced',
            title: 'Advanced Generation',
            description: 'Learn about reference images, aliases, and generation flows.',
            accent: 'secondary',
          },
        ],
      }}
    >
      {/* Hero Section */}
      <Hero
        title="Live URLs & CDN"
        subtitle="Generate images on-demand via URL parameters with automatic caching."
      />

      {/* Overview */}
      <section id="overview" className="mb-12">
        <SectionHeader level={2} id="overview">
          Overview
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Live URLs provide a simple way to generate images on-demand using URL parameters.
          Images are cached automatically, so repeated requests return instantly without counting
          toward rate limits.
        </p>
        <TipBox variant="compact" type="info">
          <strong>No API Key Required:</strong> Live URLs are public endpoints. Rate limiting
          is done by IP address instead of API key.
        </TipBox>
      </section>

      {/* URL Architecture */}
      <section id="url-architecture" className="mb-12">
        <SectionHeader level={2} id="url-architecture">
          URL Architecture
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          All images are accessible via CDN at <InlineCode>https://cdn.banatie.app</InlineCode>:
        </p>

        <Table
          headers={['URL Pattern', 'Description', 'Routing']}
          rows={urlPatterns.map(([pattern, description, routing]) => [
            <InlineCode key="pattern">{pattern}</InlineCode>,
            description,
            <span key="routing" className="text-gray-400 text-sm">{routing}</span>,
          ])}
        />

        <div className="mt-6">
          <CodeBlock
            code={`# Direct UUID access (fastest, edge cached)
https://cdn.banatie.app/default/my-project/img/7c4ccf47-41ce-4718-afbc-8c553b2c631a

# Alias access (API resolution)
https://cdn.banatie.app/default/my-project/img/@hero-banner

# Live generation (on-demand with caching)
https://cdn.banatie.app/default/my-project/live/hero?prompt=mountain+sunset`}
            language="bash"
            filename="Example URLs"
          />
        </div>
      </section>

      {/* CDN Image Serving */}
      <section id="cdn-serving" className="mb-12">
        <SectionHeader level={2} id="cdn-serving">
          CDN Image Serving
        </SectionHeader>
        <EndpointCard
          method="GET"
          endpoint="/cdn/:orgSlug/:projectSlug/img/:imageIdOrAlias"
          baseUrl="https://cdn.banatie.app"
        />
        <p className="text-gray-300 leading-relaxed mt-4 mb-4">
          Serve images by UUID or project-scoped alias. No authentication required.
        </p>

        <CodeBlock
          code={`# By UUID (direct MinIO access, fastest)
GET /cdn/acme/website/img/7c4ccf47-41ce-4718-afbc-8c553b2c631a

# By alias (API resolution, then MinIO)
GET /cdn/acme/website/img/@hero`}
          language="bash"
          filename="Examples"
        />

        <TipBox variant="compact" type="info">
          <strong>Performance:</strong> UUID requests are served directly from MinIO with edge caching.
          Alias requests require API resolution but enable dynamic reassignment.
        </TipBox>
      </section>

      {/* Live URL Generation */}
      <section id="live-generation" className="mb-12">
        <SectionHeader level={2} id="live-generation">
          Live URL Generation
        </SectionHeader>
        <EndpointCard
          method="GET"
          endpoint="/cdn/:orgSlug/:projectSlug/live/:scope"
          baseUrl="https://cdn.banatie.app"
        />
        <p className="text-gray-300 leading-relaxed mt-4 mb-4">
          Generate images on-demand via URL parameters. No authentication required.
        </p>

        <SectionHeader level={3} id="live-params" className="mb-4">
          Query Parameters
        </SectionHeader>
        <Table
          headers={['Parameter', 'Type', 'Required', 'Default', 'Description']}
          rows={liveQueryParams.map((param) => [
            <InlineCode key="name">{param.name}</InlineCode>,
            <span key="type" className="text-cyan-400">{param.type}</span>,
            <span key="required" className={param.required ? 'text-green-400' : 'text-gray-500'}>
              {param.required ? 'Yes' : 'No'}
            </span>,
            param.default === '-' ? <span className="text-gray-500">-</span> : <InlineCode key="default">{param.default}</InlineCode>,
            param.description,
          ])}
        />

        <div className="mt-6">
          <CodeBlock
            code={`<!-- Generate a 16:9 landscape image -->
<img src="https://cdn.banatie.app/acme/website/live/hero-section?prompt=mountain+landscape&aspectRatio=16:9" />`}
            language="html"
            filename="Example Usage"
          />
        </div>
      </section>

      {/* Cache Behavior */}
      <section id="cache-behavior" className="mb-12">
        <SectionHeader level={2} id="cache-behavior">
          Cache Behavior
        </SectionHeader>

        <SectionHeader level={3} id="cache-hit" className="mb-4">
          Cache HIT
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Image exists in cache - returns instantly without rate limit check.
        </p>
        <Table
          headers={['Header', 'Value']}
          rows={cacheHitHeaders.map(([header, value]) => [
            <InlineCode key="header">{header}</InlineCode>,
            <InlineCode key="value">{value}</InlineCode>,
          ])}
        />

        <SectionHeader level={3} id="cache-miss" className="mt-8 mb-4">
          Cache MISS
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          New generation - generates image, stores in cache, counts toward rate limit.
        </p>
        <Table
          headers={['Header', 'Value']}
          rows={cacheMissHeaders.map(([header, value]) => [
            <InlineCode key="header">{header}</InlineCode>,
            <InlineCode key="value">{value}</InlineCode>,
          ])}
        />

        <div className="mt-6">
          <TipBox variant="compact" type="info">
            <strong>Cache Key:</strong> Computed from{' '}
            <InlineCode>projectId + scope + prompt + aspectRatio + autoEnhance</InlineCode>
          </TipBox>
        </div>
      </section>

      {/* IP Rate Limiting */}
      <section id="rate-limiting" className="mb-12">
        <SectionHeader level={2} id="rate-limiting">
          IP Rate Limiting
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Live URLs are rate limited by IP address:
        </p>

        <Table
          headers={['Limit', 'Value']}
          rows={rateLimits.map(([limit, value]) => [
            limit,
            <InlineCode key="value">{value}</InlineCode>,
          ])}
        />

        <div className="mt-6">
          <TipBox variant="compact" type="warning">
            <strong>Important:</strong> Only cache MISS (new generations) count toward the limit.
            Cache HIT requests are unlimited.
          </TipBox>
        </div>
      </section>

      {/* Scope Management */}
      <section id="scope-management" className="mb-12">
        <SectionHeader level={2} id="scope-management">
          Scope Management
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Scopes organize live URL generation budgets. Scope endpoints require Project Key authentication.
        </p>

        <SectionHeader level={3} id="create-scope" className="mb-4">
          Create Scope
        </SectionHeader>
        <EndpointCard
          method="POST"
          endpoint="/api/v1/live/scopes"
          baseUrl="https://api.banatie.app"
        />

        <Table
          headers={['Parameter', 'Type', 'Required', 'Default', 'Description']}
          rows={scopeParams.map((param) => [
            <InlineCode key="name">{param.name}</InlineCode>,
            <span key="type" className="text-cyan-400">{param.type}</span>,
            <span key="required" className={param.required ? 'text-green-400' : 'text-gray-500'}>
              {param.required ? 'Yes' : 'No'}
            </span>,
            param.default === '-' ? <span className="text-gray-500">-</span> : <InlineCode key="default">{param.default}</InlineCode>,
            param.description,
          ])}
        />

        <SectionHeader level={3} id="lazy-scope" className="mt-6 mb-4">
          Lazy Scope Creation
        </SectionHeader>
        <p className="text-gray-300 leading-relaxed mb-4">
          Scopes are auto-created on first live URL request if <InlineCode>project.allowNewLiveScopes = true</InlineCode>.
        </p>

        <SectionHeader level={3} id="scope-endpoints" className="mt-6 mb-4">
          Scope Endpoints
        </SectionHeader>
        <div className="space-y-4">
          <div>
            <EndpointCard method="GET" endpoint="/api/v1/live/scopes" baseUrl="https://api.banatie.app" />
            <p className="text-gray-400 text-sm mt-2">List all scopes with pagination</p>
          </div>
          <div>
            <EndpointCard method="GET" endpoint="/api/v1/live/scopes/:slug" baseUrl="https://api.banatie.app" />
            <p className="text-gray-400 text-sm mt-2">Get scope with statistics</p>
          </div>
          <div>
            <EndpointCard method="PUT" endpoint="/api/v1/live/scopes/:slug" baseUrl="https://api.banatie.app" />
            <p className="text-gray-400 text-sm mt-2">Update scope settings</p>
          </div>
          <div>
            <EndpointCard method="POST" endpoint="/api/v1/live/scopes/:slug/regenerate" baseUrl="https://api.banatie.app" />
            <p className="text-gray-400 text-sm mt-2">Regenerate scope images</p>
          </div>
          <div>
            <EndpointCard method="DELETE" endpoint="/api/v1/live/scopes/:slug" baseUrl="https://api.banatie.app" />
            <p className="text-gray-400 text-sm mt-2">Delete scope (cascades to images)</p>
          </div>
        </div>

        <div className="mt-6">
          <TipBox variant="prominent" type="warning">
            <strong>Delete Warning:</strong> Deleting a scope permanently removes all cached images.
            Aliased images may be kept based on alias protection rules.
          </TipBox>
        </div>
      </section>

      {/* Use Cases */}
      <section id="use-cases" className="mb-12">
        <SectionHeader level={2} id="use-cases">
          Use Cases
        </SectionHeader>

        <SectionHeader level={3} id="hero-images" className="mb-4">
          Dynamic Hero Images
        </SectionHeader>
        <CodeBlock
          code={`<img src="https://cdn.banatie.app/acme/website/live/hero?prompt=professional+office+workspace&aspectRatio=16:9" />`}
          language="html"
          filename="Hero Image"
        />
        <p className="text-gray-400 text-sm mt-2 mb-6">First load generates, subsequent loads are cached.</p>

        <SectionHeader level={3} id="placeholders" className="mb-4">
          Product Placeholders
        </SectionHeader>
        <CodeBlock
          code={`<img src="https://cdn.banatie.app/acme/store/live/products?prompt=product+placeholder+gray+box&aspectRatio=1:1" />`}
          language="html"
          filename="Product Placeholder"
        />

        <SectionHeader level={3} id="blog-images" className="mt-6 mb-4">
          Blog Post Images
        </SectionHeader>
        <CodeBlock
          code={`<img src="https://cdn.banatie.app/acme/blog/live/posts?prompt=abstract+technology+background&aspectRatio=16:9" />`}
          language="html"
          filename="Blog Image"
        />
      </section>
    </DocPage>
  );
}
