// frontend/src/pages/manufacturing/firmware/FirmwareApiPage.jsx
// Firmware OTA API reference — rendered as a tab panel inside FirmwareManagerPage

import { useState } from 'react'
import Tabs from '@/components/ui/Tabs'
import Card from '@/components/ui/Card'

// ─── Param colour system ──────────────────────────────────────────────────────

const PARAM = {
  hwType:   { color: 'var(--color-danger)',  bg: 'var(--color-danger-bg)',  label: '{hw_type}',        eg: 'vesper_plus · chronos · agnus' },
  channel:  { color: 'var(--color-info)',    bg: 'var(--color-info-bg)',    label: '{channel}',        eg: 'stable · beta · alpha · testing' },
  version:  { color: 'var(--color-success)', bg: 'var(--color-success-bg)', label: '{version}',        eg: '1.0 · 2.5.1 · 1.2.3' },
  identity: { color: 'var(--color-warning)', bg: 'var(--color-warning-bg)', label: 'device_uid / sha256', eg: 'BSVSPR-26C13X-… · a3f1c8…' },
}

// An inline coloured segment inside a URL path
function PathParam({ kind }) {
  const p = PARAM[kind]
  return (
    <span style={{
      fontFamily: 'var(--font-family-mono)',
      fontSize: 'var(--font-size-xs)',
      color: p.color,
      fontWeight: 'var(--font-weight-semibold)',
    }}>
      {p.label}
    </span>
  )
}

// A standalone pill tag (query param or body field)
function ParamPill({ kind, name }) {
  const p = PARAM[kind]
  return (
    <span style={{
      display: 'inline-flex',
      alignItems: 'center',
      fontFamily: 'var(--font-family-mono)',
      fontSize: 'var(--font-size-xs)',
      color: p.color,
      backgroundColor: p.bg,
      border: `1px solid ${p.color}`,
      borderRadius: 'var(--radius-sm)',
      padding: '1px var(--space-2)',
      opacity: 0.9,
      whiteSpace: 'nowrap',
    }}>
      {name}
    </span>
  )
}

// ─── Endpoint data ────────────────────────────────────────────────────────────

// pathParts: array of { text, plain } | { kind }
// query / body: array of { name, kind }

const GET_ENDPOINTS = [
  {
    label: 'Check for latest version',
    pathParts: [
      { text: '/api/firmware/', plain: true },
      { kind: 'hwType' },
      { text: '/', plain: true },
      { kind: 'channel' },
      { text: '/latest', plain: true },
    ],
    query: [
      { name: '?hw_version',      kind: 'version' },
      { name: '?current_version', kind: 'version' },
    ],
    desc: 'Returns metadata for the correct next firmware hop. Pass hw_version and current_version so the server resolves upgrade chains correctly.',
  },
  {
    label: 'Get specific version info',
    pathParts: [
      { text: '/api/firmware/', plain: true },
      { kind: 'hwType' },
      { text: '/', plain: true },
      { kind: 'channel' },
      { text: '/', plain: true },
      { kind: 'version' },
      { text: '/info', plain: true },
    ],
    desc: 'Returns metadata for a specific version. Used when resolving upgrade chains with min_fw_version constraints.',
  },
  {
    label: 'Get latest changelog',
    pathParts: [
      { text: '/api/firmware/', plain: true },
      { kind: 'hwType' },
      { text: '/', plain: true },
      { kind: 'channel' },
      { text: '/latest/changelog', plain: true },
    ],
    desc: 'Returns the full changelog for the latest firmware as plain text. Not served in metadata — for admin/display use only.',
  },
  {
    label: 'Get specific version changelog',
    pathParts: [
      { text: '/api/firmware/', plain: true },
      { kind: 'hwType' },
      { text: '/', plain: true },
      { kind: 'channel' },
      { text: '/', plain: true },
      { kind: 'version' },
      { text: '/info/changelog', plain: true },
    ],
    desc: 'Returns the full changelog for a specific firmware version as plain text.',
  },
  {
    label: 'Download firmware binary',
    pathParts: [
      { text: '/api/firmware/', plain: true },
      { kind: 'hwType' },
      { text: '/', plain: true },
      { kind: 'channel' },
      { text: '/', plain: true },
      { kind: 'version' },
      { text: '/firmware.bin', plain: true },
    ],
    desc: 'Streams the raw .bin file. Devices fetch this after confirming the version via /latest or /info.',
  },
]

const POST_ENDPOINTS = [
  {
    label: 'OTA download event',
    pathParts: [{ text: '/api/ota/events/download', plain: true }],
    body: [
      { name: 'device_uid',   kind: 'identity' },
      { name: 'hw_type',      kind: 'hwType'   },
      { name: 'hw_version',   kind: 'version'  },
      { name: 'from_version', kind: 'version'  },
      { name: 'to_version',   kind: 'version'  },
      { name: 'channel',      kind: 'channel'  },
    ],
    desc: 'Posted when the binary is fully written to the staged partition (before Update.end()). Best-effort — no retry on failure.',
  },
  {
    label: 'OTA flash confirmed',
    pathParts: [{ text: '/api/ota/events/flash', plain: true }],
    body: [
      { name: 'device_uid',   kind: 'identity' },
      { name: 'hw_type',      kind: 'hwType'   },
      { name: 'hw_version',   kind: 'version'  },
      { name: 'from_version', kind: 'version'  },
      { name: 'to_version',   kind: 'version'  },
      { name: 'channel',      kind: 'channel'  },
      { name: 'sha256',       kind: 'identity' },
    ],
    desc: 'Posted after Update.end() succeeds — partition committed, device about to reboot. This is ground truth for fleet version tracking.',
  },
]

// ─── Endpoint card ────────────────────────────────────────────────────────────

function EndpointCard({ method, label, pathParts, query, body, desc }) {
  const isGet = method === 'GET'
  const methodColor  = isGet ? 'var(--color-info)'    : 'var(--color-success)'
  const methodBg     = isGet ? 'var(--color-info-bg)' : 'var(--color-success-bg)'

  return (
    <Card variant="outlined" style={{ marginBottom: 'var(--space-3)' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>

        {/* Method badge + label */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
          <span style={{
            fontFamily: 'var(--font-family-mono)',
            fontSize: 'var(--font-size-xs)',
            fontWeight: 'var(--font-weight-bold)',
            color: methodColor,
            backgroundColor: methodBg,
            border: `1px solid ${methodColor}`,
            borderRadius: 'var(--radius-sm)',
            padding: '2px var(--space-2)',
            letterSpacing: 'var(--tracking-wide)',
            flexShrink: 0,
          }}>
            {method}
          </span>
          <span style={{
            fontSize: 'var(--font-size-sm)',
            fontWeight: 'var(--font-weight-medium)',
            color: 'var(--color-text-secondary)',
          }}>
            {label}
          </span>
        </div>

        {/* URL path */}
        <div style={{
          display: 'flex',
          flexWrap: 'wrap',
          alignItems: 'center',
          gap: 0,
          padding: 'var(--space-2) var(--space-3)',
          backgroundColor: 'var(--color-bg-base)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border)',
        }}>
          <span style={{
            fontFamily: 'var(--font-family-mono)',
            fontSize: 'var(--font-size-xs)',
            color: 'var(--color-text-muted)',
            marginRight: 1,
          }}>
            console.bellsystems.net
          </span>
          {pathParts.map((p, i) =>
            p.plain
              ? <span key={i} style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-primary)' }}>{p.text}</span>
              : <PathParam key={i} kind={p.kind} />
          )}
        </div>

        {/* Query params */}
        {query && query.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)', alignItems: 'center' }}>
            <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)', marginRight: 'var(--space-1)' }}>
              QUERY
            </span>
            {query.map((q) => <ParamPill key={q.name} name={q.name} kind={q.kind} />)}
          </div>
        )}

        {/* Body fields */}
        {body && body.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)', alignItems: 'center' }}>
            <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)', marginRight: 'var(--space-1)' }}>
              BODY
            </span>
            {body.map((f) => <ParamPill key={f.name} name={f.name} kind={f.kind} />)}
          </div>
        )}

        {/* Description */}
        <p style={{
          fontSize: 'var(--font-size-xs)',
          color: 'var(--color-text-muted)',
          lineHeight: 1.6,
          margin: 0,
          borderTop: '1px solid var(--color-border)',
          paddingTop: 'var(--space-2)',
        }}>
          {desc}
        </p>
      </div>
    </Card>
  )
}

// ─── Legend panel ─────────────────────────────────────────────────────────────

function LegendPanel() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
      {Object.entries(PARAM).map(([key, p]) => (
        <Card key={key} variant="outlined" style={{ borderLeft: `3px solid ${p.color}` }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
            <span style={{
              fontFamily: 'var(--font-family-mono)',
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              color: p.color,
            }}>
              {p.label}
            </span>
            <span style={{
              fontFamily: 'var(--font-family-mono)',
              fontSize: 'var(--font-size-xs)',
              color: 'var(--color-text-muted)',
              lineHeight: 1.5,
            }}>
              {p.eg}
            </span>
          </div>
        </Card>
      ))}

      <p style={{
        fontSize: 'var(--font-size-xs)',
        color: 'var(--color-text-muted)',
        lineHeight: 1.6,
        margin: 0,
        marginTop: 'var(--space-1)',
        textAlign: 'center',
        fontStyle: 'italic',
      }}>
        Colour coding is consistent across path segments, query params, and body fields.
      </p>
    </div>
  )
}

// ─── Main page ────────────────────────────────────────────────────────────────

const METHOD_TABS = [
  { key: 'get',  label: 'GET'  },
  { key: 'post', label: 'POST' },
]

export default function FirmwareApiPage() {
  const [activeMethod, setActiveMethod] = useState('get')

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>

      {/* Notice banner */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 'var(--space-3)',
        padding: 'var(--space-3) var(--space-4)',
        backgroundColor: 'var(--color-bg-elevated)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-lg)',
      }}>
        {/* Lock-open icon */}
        <svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="var(--color-text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
          <rect x="3" y="7" width="10" height="7" rx="1.5" />
          <path d="M5 7V5a3 3 0 0 1 6 0" />
        </svg>
        <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', margin: 0 }}>
          All endpoints are <strong style={{ color: 'var(--color-text-primary)' }}>unauthenticated</strong> — devices call them directly without any API key or session token.
        </p>
      </div>

      {/* Two-column layout — grid spans both the header row and the content row */}
      <div style={{ display: 'grid', gridTemplateColumns: '70fr 30fr', columnGap: 'var(--space-6)', rowGap: 'var(--space-4)', alignItems: 'start' }}>

        {/* Row 1 left: GET / POST tabs */}
        <Tabs tabs={METHOD_TABS} active={activeMethod} onChange={setActiveMethod} variant="line" />

        {/* Row 1 right: "Parameter Legend" label — visually sits in the tab bar row */}
        <div style={{
          display: 'flex',
          alignItems: 'flex-end',
          paddingBottom: 'var(--space-2)',
          borderBottom: '1px solid var(--color-border)',
        }}>
          <span style={{
            fontSize: 'var(--font-size-xs)',
            fontWeight: 'var(--font-weight-semibold)',
            color: 'var(--color-text-secondary)',
            textTransform: 'uppercase',
            letterSpacing: 'var(--tracking-wide)',
          }}>
            Parameter Legend
          </span>
        </div>

        {/* Row 2 left: endpoint cards */}
        <div>
          {activeMethod === 'get'  && GET_ENDPOINTS.map((ep)  => <EndpointCard key={ep.label} method="GET"  {...ep} />)}
          {activeMethod === 'post' && POST_ENDPOINTS.map((ep) => <EndpointCard key={ep.label} method="POST" {...ep} />)}
        </div>

        {/* Row 2 right: legend items (sticky) */}
        <div style={{ position: 'sticky', top: 'var(--space-6)' }}>
          <LegendPanel />
        </div>
      </div>
    </div>
  )
}
