import React from 'react'
import { Head, usePage } from '@inertiajs/react'
import CollectionCard from '../../components/profile/collections/CollectionCard'
import ShareToast from '../../components/ui/ShareToast'
import Checkbox from '../../components/ui/Checkbox'
import NovaSelect from '../../components/ui/NovaSelect'

function getCsrfToken() {
  if (typeof document === 'undefined') return ''
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
}

async function requestJson(url, { method = 'POST', body } = {}) {
  const response = await fetch(url, {
    method,
    credentials: 'same-origin',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': getCsrfToken(),
      'X-Requested-With': 'XMLHttpRequest',
    },
    body: body ? JSON.stringify(body) : undefined,
  })

  const payload = await response.json().catch(() => ({}))
  if (!response.ok) {
    throw new Error(payload?.message || 'Request failed.')
  }

  return payload
}

function isoToLocalInput(value) {
  if (!value) return ''

  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''

  const local = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
  return local.toISOString().slice(0, 16)
}

function titleize(value) {
  return String(value || '')
    .split('_')
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ')
}

function Field({ label, help, children }) {
  return (
    <label className="block space-y-2">
      <span className="text-sm font-semibold text-white">{label}</span>
      {children}
      {help ? <span className="block text-xs leading-relaxed text-slate-400">{help}</span> : null}
    </label>
  )
}

function StatCard({ label, value, tone = 'sky' }) {
  const toneClasses = {
    sky: 'border-sky-300/15 bg-sky-400/10 text-sky-100',
    amber: 'border-amber-300/15 bg-amber-400/10 text-amber-100',
    emerald: 'border-emerald-300/15 bg-emerald-400/10 text-emerald-100',
  }

  return (
    <div className="rounded-[24px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm">
      <div className={`inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${toneClasses[tone] || toneClasses.sky}`}>{label}</div>
      <div className="mt-4 text-3xl font-semibold tracking-[-0.04em] text-white">{value}</div>
    </div>
  )
}

function sortAssignments(items) {
  return [...items].sort((left, right) => {
    const keyCompare = String(left.program_key || '').localeCompare(String(right.program_key || ''))
    if (keyCompare !== 0) return keyCompare
    return (Number(right.priority) || 0) - (Number(left.priority) || 0)
  })
}

function buildHooksForm(collection) {
  return {
    experiment_key: collection?.experiment_key || '',
    experiment_treatment: collection?.experiment_treatment || '',
    placement_variant: collection?.placement_variant || '',
    ranking_mode_variant: collection?.ranking_mode_variant || '',
    collection_pool_version: collection?.collection_pool_version || '',
    test_label: collection?.test_label || '',
    promotion_tier: collection?.promotion_tier || '',
    partner_key: collection?.partner_key || '',
    trust_tier: collection?.trust_tier || '',
    sponsorship_state: collection?.sponsorship_state || '',
    ownership_domain: collection?.ownership_domain || '',
    commercial_review_state: collection?.commercial_review_state || '',
    legal_review_state: collection?.legal_review_state || '',
    placement_eligibility: Boolean(collection?.placement_eligibility),
  }
}

function buildDiagnostics(collection) {
  if (!collection) {
    return null
  }

  return {
    collection_id: Number(collection.id),
    workflow_state: collection.workflow_state || null,
    health_state: collection.health_state || null,
    placement_eligibility: Boolean(collection.placement_eligibility),
    experiment_key: collection.experiment_key || null,
    experiment_treatment: collection.experiment_treatment || null,
    placement_variant: collection.placement_variant || null,
    ranking_mode_variant: collection.ranking_mode_variant || null,
    collection_pool_version: collection.collection_pool_version || null,
    test_label: collection.test_label || null,
    partner_key: collection.partner_key || null,
    trust_tier: collection.trust_tier || null,
    promotion_tier: collection.promotion_tier || null,
    sponsorship_state: collection.sponsorship_state || null,
    ownership_domain: collection.ownership_domain || null,
    commercial_review_state: collection.commercial_review_state || null,
    legal_review_state: collection.legal_review_state || null,
    ranking_bucket: collection.ranking_bucket || null,
    recommendation_tier: collection.recommendation_tier || null,
    last_health_check_at: collection.last_health_check_at || null,
    last_recommendation_refresh_at: collection.last_recommendation_refresh_at || null,
  }
}

function buildProgramUrl(pattern, programKey) {
  if (!pattern || !programKey) return null
  return pattern.replace('__PROGRAM__', String(programKey))
}

export default function CollectionStaffProgramming() {
  const { props } = usePage()
  const initialCollectionOptions = Array.isArray(props.collectionOptions) ? props.collectionOptions : []
  const initialAssignments = Array.isArray(props.assignments) ? props.assignments : []
  const baseProgramKeys = Array.isArray(props.programKeyOptions) ? props.programKeyOptions : []
  const initialMergeQueue = props.mergeQueue || { summary: {}, pending: [], recent: [] }
  const observabilitySummary = props.observabilitySummary || { counts: {}, watchlist: [], generated_at: null }
  const endpoints = props.endpoints || {}
  const historyPattern = props.historyPattern || ''
  const seo = props.seo || {}
  const viewer = props.viewer || {}
  const [assignments, setAssignments] = React.useState(sortAssignments(initialAssignments))
  const [collectionOverrides, setCollectionOverrides] = React.useState({})
  const collectionOptions = React.useMemo(() => initialCollectionOptions.map((collection) => collectionOverrides[collection.id] || collection), [collectionOverrides, initialCollectionOptions])
  const [mergeQueue, setMergeQueue] = React.useState(initialMergeQueue)
  const [previewCollections, setPreviewCollections] = React.useState([])
  const [diagnostics, setDiagnostics] = React.useState({
    eligibility: null,
    duplicates: null,
    recommendations: null,
  })
  const [notice, setNotice] = React.useState('')
  const [toast, setToast] = React.useState({ id: 0, visible: false, message: '', variant: 'success' })
  const [busy, setBusy] = React.useState('')
  const [queueBusy, setQueueBusy] = React.useState({})
  const [selectedCollectionId, setSelectedCollectionId] = React.useState(initialCollectionOptions[0]?.id || '')
  const [previewForm, setPreviewForm] = React.useState({
    program_key: baseProgramKeys[0] || '',
    limit: 8,
  })
  const [assignmentForm, setAssignmentForm] = React.useState({
    id: null,
    collection_id: collectionOptions[0]?.id || '',
    program_key: baseProgramKeys[0] || '',
    campaign_key: '',
    placement_scope: '',
    starts_at: '',
    ends_at: '',
    priority: 0,
    notes: '',
  })
  const selectedCollection = React.useMemo(() => collectionOptions.find((collection) => String(collection.id) === String(selectedCollectionId)) || null, [collectionOptions, selectedCollectionId])
  const [hooksForm, setHooksForm] = React.useState(buildHooksForm(initialCollectionOptions[0] || null))
  const [hooksDiagnostics, setHooksDiagnostics] = React.useState(buildDiagnostics(initialCollectionOptions[0] || null))

  const programKeyOptions = React.useMemo(() => {
    return Array.from(new Set([
      ...baseProgramKeys,
      ...assignments.map((assignment) => assignment.program_key).filter(Boolean),
      ...collectionOptions.map((collection) => collection.program_key).filter(Boolean),
      assignmentForm.program_key || null,
      previewForm.program_key || null,
    ].filter(Boolean))).sort((left, right) => String(left).localeCompare(String(right)))
  }, [assignmentForm.program_key, assignments, baseProgramKeys, collectionOptions, previewForm.program_key])

  React.useEffect(() => {
    if (!assignmentForm.collection_id && collectionOptions[0]?.id) {
      setAssignmentForm((current) => ({ ...current, collection_id: collectionOptions[0].id }))
    }

    if (!selectedCollectionId && collectionOptions[0]?.id) {
      setSelectedCollectionId(collectionOptions[0].id)
    }
  }, [assignmentForm.collection_id, collectionOptions, selectedCollectionId])

  React.useEffect(() => {
    if (!assignmentForm.program_key && programKeyOptions[0]) {
      setAssignmentForm((current) => ({ ...current, program_key: programKeyOptions[0] }))
    }

    if (!previewForm.program_key && programKeyOptions[0]) {
      setPreviewForm((current) => ({ ...current, program_key: programKeyOptions[0] }))
    }
  }, [assignmentForm.program_key, previewForm.program_key, programKeyOptions])

  React.useEffect(() => {
    setMergeQueue(initialMergeQueue)
  }, [initialMergeQueue])

  React.useEffect(() => {
    setHooksForm(buildHooksForm(selectedCollection))
    setHooksDiagnostics(buildDiagnostics(selectedCollection))
  }, [selectedCollection])

  function showToast(message, variant = 'success') {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant,
    })
  }

  function resetAssignmentForm() {
    setAssignmentForm({
      id: null,
      collection_id: collectionOptions[0]?.id || '',
      program_key: programKeyOptions[0] || '',
      campaign_key: '',
      placement_scope: '',
      starts_at: '',
      ends_at: '',
      priority: 0,
      notes: '',
    })
  }

  function hydrateAssignment(assignment) {
    setAssignmentForm({
      id: assignment.id,
      collection_id: assignment.collection?.id || '',
      program_key: assignment.program_key || '',
      campaign_key: assignment.campaign_key || '',
      placement_scope: assignment.placement_scope || '',
      starts_at: isoToLocalInput(assignment.starts_at),
      ends_at: isoToLocalInput(assignment.ends_at),
      priority: assignment.priority || 0,
      notes: assignment.notes || '',
    })
  }

  async function handleAssignmentSubmit(event) {
    event.preventDefault()
    setBusy('assignment')
    setNotice('')

    try {
      const url = assignmentForm.id
        ? endpoints.updatePattern?.replace('__PROGRAM__', String(assignmentForm.id))
        : endpoints.store

      const payload = await requestJson(url, {
        method: assignmentForm.id ? 'PATCH' : 'POST',
        body: {
          collection_id: Number(assignmentForm.collection_id),
          program_key: assignmentForm.program_key,
          campaign_key: assignmentForm.campaign_key || null,
          placement_scope: assignmentForm.placement_scope || null,
          starts_at: assignmentForm.starts_at ? new Date(assignmentForm.starts_at).toISOString() : null,
          ends_at: assignmentForm.ends_at ? new Date(assignmentForm.ends_at).toISOString() : null,
          priority: Number(assignmentForm.priority || 0),
          notes: assignmentForm.notes || null,
        },
      })

      setAssignments((current) => sortAssignments([...current.filter((item) => item.id !== payload.assignment.id), payload.assignment]))
      setNotice(assignmentForm.id ? 'Programming assignment updated.' : 'Programming assignment created.')
      resetAssignmentForm()
    } catch (error) {
      setNotice(error.message || 'Failed to save programming assignment.')
    } finally {
      setBusy('')
    }
  }

  async function handlePreview(event) {
    event.preventDefault()
    setBusy('preview')
    setNotice('')

    try {
      const payload = await requestJson(endpoints.preview, {
        method: 'POST',
        body: {
          program_key: previewForm.program_key,
          limit: Number(previewForm.limit || 8),
        },
      })

      setPreviewCollections(Array.isArray(payload.collections) ? payload.collections : [])
      setNotice('Preview refreshed.')
    } catch (error) {
      setNotice(error.message || 'Failed to preview this program key.')
    } finally {
      setBusy('')
    }
  }

  async function runDiagnostic(kind) {
    const endpointMap = {
      eligibility: endpoints.refreshEligibility,
      duplicates: endpoints.duplicateScan,
      recommendations: endpoints.refreshRecommendations,
    }

    const url = endpointMap[kind]
    if (!url) {
      return
    }

    setBusy(kind)
    setNotice('')

    try {
      const payload = await requestJson(url, {
        method: 'POST',
        body: {
          collection_id: selectedCollectionId ? Number(selectedCollectionId) : null,
        },
      })

      setDiagnostics((current) => ({ ...current, [kind]: payload.result || null }))
      setNotice(payload?.result?.message || `${titleize(kind)} queued.`)
    } catch (error) {
      setNotice(error.message || `Failed to run ${kind}.`)
    } finally {
      setBusy('')
    }
  }

  async function handleQueueAction(kind, item) {
    const sourceId = item?.source?.id
    const targetId = item?.target?.id

    if (!sourceId || !targetId) {
      return
    }

    const endpointMap = {
      canonicalize: endpoints.canonicalizeCandidate,
      merge: endpoints.mergeCandidate,
      reject: endpoints.rejectCandidate,
    }

    const confirmationMap = {
      canonicalize: `Designate "${item.target?.title || 'this collection'}" as the canonical target for "${item.source?.title || 'this collection'}"?`,
      merge: `Merge "${item.source?.title || 'this collection'}" into "${item.target?.title || 'this collection'}" from the staff queue?`,
      reject: `Mark "${item.target?.title || 'this collection'}" as not a duplicate of "${item.source?.title || 'this collection'}"?`,
    }

    const url = endpointMap[kind]
    if (!url) {
      return
    }

    if (!window.confirm(confirmationMap[kind] || 'Continue?')) {
      return
    }

    setQueueBusy((current) => ({ ...current, [item.id]: kind }))

    try {
      const payload = await requestJson(url, {
        method: 'POST',
        body: {
          source_collection_id: Number(sourceId),
          target_collection_id: Number(targetId),
        },
      })

      if (payload?.mergeQueue) {
        setMergeQueue(payload.mergeQueue)
      }

      showToast(payload?.message || `${titleize(kind)} action completed.`, 'success')
    } catch (error) {
      showToast(error.message || `Failed to ${kind} this queue item.`, 'error')
    } finally {
      setQueueBusy((current) => {
        const next = { ...current }
        delete next[item.id]
        return next
      })
    }
  }

  async function handleHooksSubmit(event) {
    event.preventDefault()

    if (!selectedCollectionId || !endpoints.metadataUpdate) {
      return
    }

    setBusy('hooks')
    setNotice('')

    try {
      const payload = await requestJson(endpoints.metadataUpdate, {
        method: 'POST',
        body: {
          collection_id: Number(selectedCollectionId),
          experiment_key: hooksForm.experiment_key || null,
          experiment_treatment: hooksForm.experiment_treatment || null,
          placement_variant: hooksForm.placement_variant || null,
          ranking_mode_variant: hooksForm.ranking_mode_variant || null,
          collection_pool_version: hooksForm.collection_pool_version || null,
          test_label: hooksForm.test_label || null,
          promotion_tier: hooksForm.promotion_tier || null,
          partner_key: viewer.isAdmin ? (hooksForm.partner_key || null) : undefined,
          trust_tier: viewer.isAdmin ? (hooksForm.trust_tier || null) : undefined,
          sponsorship_state: viewer.isAdmin ? (hooksForm.sponsorship_state || null) : undefined,
          ownership_domain: viewer.isAdmin ? (hooksForm.ownership_domain || null) : undefined,
          commercial_review_state: viewer.isAdmin ? (hooksForm.commercial_review_state || null) : undefined,
          legal_review_state: viewer.isAdmin ? (hooksForm.legal_review_state || null) : undefined,
          placement_eligibility: Boolean(hooksForm.placement_eligibility),
        },
      })

      if (payload?.collection?.id) {
        setCollectionOverrides((current) => ({
          ...current,
          [payload.collection.id]: payload.collection,
        }))
      }

      setHooksDiagnostics(payload?.diagnostics || buildDiagnostics(payload?.collection || selectedCollection))
      setHooksForm(buildHooksForm(payload?.collection || selectedCollection))
      setNotice(payload?.message || 'Experiment and program governance hooks updated.')
    } catch (error) {
      setNotice(error.message || 'Failed to update experiment and program governance hooks.')
    } finally {
      setBusy('')
    }
  }

  const totalPrograms = Array.from(new Set(assignments.map((assignment) => assignment.program_key).filter(Boolean))).length
  const eligibleAssignments = assignments.filter((assignment) => assignment.collection?.placement_eligibility === true).length

  return (
    <>
      <Head>
        <title>{seo.title || 'Collection Programming — Skinbase Nova'}</title>
        <meta name="description" content={seo.description || 'Staff programming tools for collections.'} />
        {seo.canonical ? <link rel="canonical" href={seo.canonical} /> : null}
        <meta name="robots" content={seo.robots || 'noindex,follow'} />
      </Head>

      <ShareToast
        key={toast.id}
        message={toast.message}
        visible={toast.visible}
        variant={toast.variant}
        duration={toast.variant === 'error' ? 3200 : 2200}
        onHide={() => setToast((current) => ({ ...current, visible: false }))}
      />

      <div className="relative min-h-screen overflow-hidden pb-16">
        <div aria-hidden="true" className="pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-95" style={{ background: 'radial-gradient(circle at 18% 15%, rgba(56,189,248,0.18), transparent 28%), radial-gradient(circle at 85% 14%, rgba(132,204,22,0.16), transparent 26%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)' }} />
        <div aria-hidden="true" className="pointer-events-none absolute inset-0 -z-10 opacity-[0.05]" style={{ backgroundImage: 'url(/gfx/noise.png)', backgroundSize: '180px' }} />

        <div className="mx-auto max-w-7xl px-4 pt-8 md:px-6">
          <section className="rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80">Staff Programming</p>
                <h1 className="mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl">Collections programming studio</h1>
                <p className="mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]">
                  Manage program assignments, preview live pools, and run targeted diagnostics before collections hit discovery surfaces.
                </p>
                {notice ? <p className="mt-4 text-sm text-sky-100">{notice}</p> : null}
              </div>
              {endpoints.surfaces ? <a href={endpoints.surfaces} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-thumbtack fa-fw text-[11px]" />Open placement studio</a> : null}
            </div>
          </section>

          <section className="mt-8 grid gap-5 md:grid-cols-3">
            <StatCard label="Assignments" value={assignments.length} tone="sky" />
            <StatCard label="Program Keys" value={totalPrograms} tone="amber" />
            <StatCard label="Eligible" value={eligibleAssignments} tone="emerald" />
          </section>

          <section className="mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-200/80">Merge Queue</p>
                <h2 className="mt-2 text-2xl font-semibold text-white">Pending duplicates and recent decisions</h2>
                <p className="mt-3 max-w-3xl text-sm leading-relaxed text-slate-300">
                  Review what still needs merge attention and what staff already resolved. Each row links back into the collection studio for full compare-and-confirm actions.
                </p>
              </div>
              <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                <StatCard label="Pending" value={mergeQueue?.summary?.pending || 0} tone="amber" />
                <StatCard label="Approved" value={mergeQueue?.summary?.approved || 0} tone="sky" />
                <StatCard label="Rejected" value={mergeQueue?.summary?.rejected || 0} tone="emerald" />
                <StatCard label="Merged" value={mergeQueue?.summary?.completed || 0} tone="sky" />
              </div>
            </div>

            <div className="mt-6 grid gap-6 xl:grid-cols-2">
              <div className="rounded-[28px] border border-white/10 bg-slate-950/40 p-5">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-200/80">Needs Review</p>
                    <h3 className="mt-2 text-xl font-semibold text-white">Suggested duplicate pairs</h3>
                  </div>
                  <span className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300">{mergeQueue?.pending?.length || 0}</span>
                </div>

                <div className="mt-5 space-y-4">
                  {(mergeQueue?.pending || []).length ? mergeQueue.pending.map((item) => {
                    const activeQueueAction = queueBusy[item.id] || ''
                    const cardBusy = Boolean(activeQueueAction)

                    return (
                    <div key={`merge-pending-${item.id}`} className={`rounded-[24px] border border-white/10 bg-white/[0.04] p-4 transition ${cardBusy ? 'ring-1 ring-sky-300/25' : ''}`}>
                      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
                        <div className="flex flex-wrap gap-2">
                          {(item.comparison?.match_reasons || []).map((reason) => (
                            <span key={reason} className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300">{titleize(reason)}</span>
                          ))}
                        </div>
                        {cardBusy ? <span className="inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-sky-100"><i className="fa-solid fa-circle-notch fa-spin fa-fw text-[10px]" />Processing {titleize(activeQueueAction)}</span> : null}
                      </div>

                      <div className="grid gap-4 lg:grid-cols-2">
                        <div>
                          <p className="mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Source</p>
                          {item.source ? <CollectionCard collection={item.source} isOwner /> : null}
                        </div>
                        <div>
                          <p className="mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Candidate</p>
                          {item.target ? <CollectionCard collection={item.target} isOwner /> : null}
                        </div>
                      </div>

                      <div className="mt-4 grid gap-2 md:grid-cols-3 text-xs text-slate-400">
                        <div className="rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2">Shared artworks: <span className="font-semibold text-white">{item.comparison?.shared_artworks_count ?? 0}</span></div>
                        <div className="rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2">Source count: <span className="font-semibold text-white">{item.comparison?.source_artworks_count ?? 0}</span></div>
                        <div className="rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2">Target count: <span className="font-semibold text-white">{item.comparison?.target_artworks_count ?? 0}</span></div>
                      </div>

                      <div className="mt-4 flex flex-wrap gap-2">
                        {item.source?.manage_url ? <a href={item.source.manage_url} className="inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15"><i className="fa-solid fa-code-compare fa-fw text-[10px]" />Review source</a> : null}
                        {item.target?.manage_url ? <a href={item.target.manage_url} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" />Open target</a> : null}
                        {item.source?.id && historyPattern ? <a href={historyPattern.replace('__COLLECTION__', String(item.source.id))} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-timeline fa-fw text-[10px]" />History</a> : null}
                        <button type="button" onClick={() => handleQueueAction('canonicalize', item)} disabled={cardBusy} className="inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60"><i className={`fa-solid ${activeQueueAction === 'canonicalize' ? 'fa-circle-notch fa-spin' : 'fa-badge-check'} fa-fw text-[10px]`} />{activeQueueAction === 'canonicalize' ? 'Canonicalizing...' : 'Canonicalize'}</button>
                        <button type="button" onClick={() => handleQueueAction('merge', item)} disabled={cardBusy} className="inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-400/15 disabled:opacity-60"><i className={`fa-solid ${activeQueueAction === 'merge' ? 'fa-circle-notch fa-spin' : 'fa-code-merge'} fa-fw text-[10px]`} />{activeQueueAction === 'merge' ? 'Merging...' : 'Merge now'}</button>
                        <button type="button" onClick={() => handleQueueAction('reject', item)} disabled={cardBusy} className="inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-xs font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60"><i className={`fa-solid ${activeQueueAction === 'reject' ? 'fa-circle-notch fa-spin' : 'fa-ban'} fa-fw text-[10px]`} />{activeQueueAction === 'reject' ? 'Rejecting...' : 'Reject'}</button>
                      </div>
                    </div>
                  )}) : <div className="rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-10 text-sm text-slate-300">No pending merge candidates right now.</div>}
                </div>
              </div>

              <div className="rounded-[28px] border border-white/10 bg-slate-950/40 p-5">
                <div className="flex items-center justify-between gap-3">
                  <div>
                    <p className="text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80">Recent Decisions</p>
                    <h3 className="mt-2 text-xl font-semibold text-white">Canonical, reject, and merge history</h3>
                  </div>
                  <span className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300">{mergeQueue?.recent?.length || 0}</span>
                </div>

                <div className="mt-5 space-y-4">
                  {(mergeQueue?.recent || []).length ? mergeQueue.recent.map((item) => (
                    <div key={`merge-recent-${item.id}`} className="rounded-[24px] border border-white/10 bg-white/[0.04] p-4">
                      <div className="flex flex-wrap items-start justify-between gap-3">
                        <div>
                          <span className="inline-flex rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300">{titleize(item.action_type)}</span>
                          {item.summary ? <p className="mt-2 text-sm text-slate-300">{item.summary}</p> : null}
                          <p className="mt-2 text-xs text-slate-500">{item.updated_at ? new Date(item.updated_at).toLocaleString() : 'Unknown time'}{item.actor?.username ? ` • @${item.actor.username}` : ''}</p>
                        </div>
                      </div>

                      <div className="mt-4 grid gap-3 lg:grid-cols-2 text-sm text-slate-300">
                        <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3">
                          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Source</div>
                          <div className="mt-1 font-semibold text-white">{item.source?.title || 'Collection'}</div>
                        </div>
                        <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3">
                          <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Target</div>
                          <div className="mt-1 font-semibold text-white">{item.target?.title || 'Collection'}</div>
                        </div>
                      </div>

                      <div className="mt-4 flex flex-wrap gap-2">
                        {item.source?.manage_url ? <a href={item.source.manage_url} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-pen-to-square fa-fw text-[10px]" />Open source</a> : null}
                        {item.target?.manage_url ? <a href={item.target.manage_url} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" />Open target</a> : null}
                      </div>
                    </div>
                  )) : <div className="rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-10 text-sm text-slate-300">No recent merge decisions yet.</div>}
                </div>
              </div>
            </div>
          </section>

          <section className="mt-8 grid gap-6 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]">
            <form onSubmit={handleAssignmentSubmit} className="rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80">Assignment</p>
                <h2 className="mt-2 text-2xl font-semibold text-white">Program key and scope</h2>
              </div>
              <div className="mt-6 grid gap-4 md:grid-cols-2">
                <Field label="Collection">
                  <NovaSelect value={String(assignmentForm.collection_id || '')} onChange={(val) => setAssignmentForm((current) => ({ ...current, collection_id: val }))} options={collectionOptions.map((o) => ({ value: String(o.id), label: o.title }))} />
                </Field>
                <Field label="Program Key" help="Use stable internal names like discover-spring or homepage-hero.">
                  <input list="program-key-options" value={assignmentForm.program_key} onChange={(event) => setAssignmentForm((current) => ({ ...current, program_key: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                </Field>
                <Field label="Placement Scope" help="Optional placement scope such as homepage.hero or discover.rail.">
                  <input value={assignmentForm.placement_scope} onChange={(event) => setAssignmentForm((current) => ({ ...current, placement_scope: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                </Field>
                <Field label="Campaign Key">
                  <input value={assignmentForm.campaign_key} onChange={(event) => setAssignmentForm((current) => ({ ...current, campaign_key: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                </Field>
                <Field label="Priority">
                  <input type="number" min="-100" max="100" value={assignmentForm.priority} onChange={(event) => setAssignmentForm((current) => ({ ...current, priority: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" />
                </Field>
                <Field label="Starts At"><input type="datetime-local" value={assignmentForm.starts_at} onChange={(event) => setAssignmentForm((current) => ({ ...current, starts_at: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" /></Field>
                <Field label="Ends At"><input type="datetime-local" value={assignmentForm.ends_at} onChange={(event) => setAssignmentForm((current) => ({ ...current, ends_at: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" /></Field>
              </div>
              <Field label="Notes" help="Operational note for launch timing, overrides, or review context."><textarea value={assignmentForm.notes} onChange={(event) => setAssignmentForm((current) => ({ ...current, notes: event.target.value }))} className="mt-4 min-h-[120px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={1000} /></Field>
              <div className="mt-5 flex flex-wrap gap-3">
                <button type="submit" disabled={busy === 'assignment'} className="inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60"><i className={`fa-solid ${busy === 'assignment' ? 'fa-circle-notch fa-spin' : 'fa-sliders'} fa-fw`} />{assignmentForm.id ? 'Update Assignment' : 'Save Assignment'}</button>
                {assignmentForm.id ? <button type="button" onClick={resetAssignmentForm} className="inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-rotate-left fa-fw" />Cancel Edit</button> : null}
              </div>
              <datalist id="program-key-options">
                {programKeyOptions.map((option) => <option key={option} value={option} />)}
              </datalist>
            </form>

            <div className="space-y-6">
              <form onSubmit={handlePreview} className="rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7">
                <div>
                  <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80">Preview</p>
                  <h2 className="mt-2 text-2xl font-semibold text-white">Inspect a live program pool</h2>
                </div>
                <div className="mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_140px_auto]">
                  <Field label="Program Key"><input list="program-key-options" value={previewForm.program_key} onChange={(event) => setPreviewForm((current) => ({ ...current, program_key: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} /></Field>
                  <Field label="Limit"><input type="number" min="1" max="24" value={previewForm.limit} onChange={(event) => setPreviewForm((current) => ({ ...current, limit: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" /></Field>
                  <div className="flex items-end"><button type="submit" disabled={busy === 'preview'} className="inline-flex h-[50px] w-full items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60"><i className={`fa-solid ${busy === 'preview' ? 'fa-circle-notch fa-spin' : 'fa-binoculars'} fa-fw`} />Preview</button></div>
                </div>

                {previewCollections.length ? (
                  <div className="mt-6 grid gap-4 xl:grid-cols-2">
                    {previewCollections.map((collection) => (
                      <div key={collection.id} className="rounded-[24px] border border-white/10 bg-slate-950/40 p-4">
                        <CollectionCard collection={collection} isOwner />
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="mt-6 rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-8 text-sm text-slate-300">Run a preview to inspect which collections currently qualify for a given program key.</div>
                )}
              </form>

              <section className="rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7">
                <div>
                  <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80">Diagnostics</p>
                  <h2 className="mt-2 text-2xl font-semibold text-white">Eligibility, duplicate risk, and ranking refresh</h2>
                </div>
                <div className="mt-6 grid gap-4 xl:grid-cols-[320px_minmax(0,1fr)]">
                  <div className="rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300">
                    <p className="font-semibold text-white">Operations summary</p>
                    <div className="mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-1">
                      <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">
                        <div className="text-[11px] uppercase tracking-[0.16em] text-slate-400">Stale health</div>
                        <div className="mt-1 text-lg font-semibold text-white">{Number(observabilitySummary?.counts?.stale_health || 0)}</div>
                      </div>
                      <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">
                        <div className="text-[11px] uppercase tracking-[0.16em] text-slate-400">Stale recommendations</div>
                        <div className="mt-1 text-lg font-semibold text-white">{Number(observabilitySummary?.counts?.stale_recommendations || 0)}</div>
                      </div>
                      <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">
                        <div className="text-[11px] uppercase tracking-[0.16em] text-slate-400">Placement blocked</div>
                        <div className="mt-1 text-lg font-semibold text-white">{Number(observabilitySummary?.counts?.placement_blocked || 0)}</div>
                      </div>
                      <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">
                        <div className="text-[11px] uppercase tracking-[0.16em] text-slate-400">Duplicate risk</div>
                        <div className="mt-1 text-lg font-semibold text-white">{Number(observabilitySummary?.counts?.duplicate_risk || 0)}</div>
                      </div>
                    </div>
                    {observabilitySummary?.generated_at ? <p className="mt-4 text-xs text-slate-400">Generated {new Date(observabilitySummary.generated_at).toLocaleString()}</p> : null}
                  </div>
                  <div className="rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300">
                    <p className="font-semibold text-white">Watchlist</p>
                    {Array.isArray(observabilitySummary?.watchlist) && observabilitySummary.watchlist.length ? (
                      <div className="mt-4 grid gap-4 xl:grid-cols-2">
                        {observabilitySummary.watchlist.map((collection) => (
                          <div key={`watch-${collection.id}`} className="rounded-[20px] border border-white/10 bg-white/[0.04] p-3">
                            <CollectionCard collection={collection} isOwner />
                          </div>
                        ))}
                      </div>
                    ) : <p className="mt-3">No watchlist items are currently flagged.</p>}
                  </div>
                </div>
                <div className="mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_auto]">
                  <Field label="Target Collection" help="Leave a selection in place to inspect one collection. Change it any time before running a diagnostic.">
                    <NovaSelect value={String(selectedCollectionId || '')} onChange={(val) => setSelectedCollectionId(val)} options={collectionOptions.map((o) => ({ value: String(o.id), label: o.title }))} />
                  </Field>
                  <div className="flex items-end gap-3">
                    <button type="button" onClick={() => runDiagnostic('eligibility')} disabled={busy !== ''} className="inline-flex items-center gap-2 rounded-2xl border border-lime-300/20 bg-lime-400/10 px-4 py-3 text-sm font-semibold text-lime-100 transition hover:bg-lime-400/15 disabled:opacity-60"><i className={`fa-solid ${busy === 'eligibility' ? 'fa-circle-notch fa-spin' : 'fa-shield-check'} fa-fw`} />Eligibility</button>
                    <button type="button" onClick={() => runDiagnostic('duplicates')} disabled={busy !== ''} className="inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60"><i className={`fa-solid ${busy === 'duplicates' ? 'fa-circle-notch fa-spin' : 'fa-id-card'} fa-fw`} />Duplicates</button>
                    <button type="button" onClick={() => runDiagnostic('recommendations')} disabled={busy !== ''} className="inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60"><i className={`fa-solid ${busy === 'recommendations' ? 'fa-circle-notch fa-spin' : 'fa-arrows-rotate'} fa-fw`} />Refresh</button>
                  </div>
                </div>

                <div className="mt-6 grid gap-4 lg:grid-cols-3">
                  <div className="rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300">
                    <p className="font-semibold text-white">Eligibility</p>
                    {diagnostics.eligibility ? (
                      <div className="mt-3 space-y-2">
                        <p>{diagnostics.eligibility.status === 'queued' ? `${diagnostics.eligibility.count} collection(s) queued.` : `${diagnostics.eligibility.count} collection(s) evaluated.`}</p>
                        {diagnostics.eligibility.message ? <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">{diagnostics.eligibility.message}</div> : null}
                        {(diagnostics.eligibility.items || []).map((item) => <div key={item.collection_id} className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">{item.health_state || 'unknown'} · {item.readiness_state || 'unknown'} · {item.placement_eligibility ? 'eligible' : 'blocked'}</div>)}
                      </div>
                    ) : <p className="mt-3">Run an eligibility refresh to verify readiness and public placement safety.</p>}
                  </div>
                  <div className="rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300">
                    <p className="font-semibold text-white">Duplicate candidates</p>
                    {diagnostics.duplicates ? (
                      <div className="mt-3 space-y-2">
                        <p>{diagnostics.duplicates.status === 'queued' ? `${diagnostics.duplicates.count} collection(s) queued.` : `${diagnostics.duplicates.count} collection(s) with candidates.`}</p>
                        {diagnostics.duplicates.message ? <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">{diagnostics.duplicates.message}</div> : null}
                        {(diagnostics.duplicates.items || []).map((item) => (
                          <div key={item.collection_id} className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">
                            {item.candidates?.length ? item.candidates.map((candidate) => candidate.title).join(', ') : 'No candidates'}
                          </div>
                        ))}
                      </div>
                    ) : <p className="mt-3">Run duplicate scan to surface overlap before programming a collection widely.</p>}
                  </div>
                  <div className="rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300">
                    <p className="font-semibold text-white">Recommendation refresh</p>
                    {diagnostics.recommendations ? (
                      <div className="mt-3 space-y-2">
                        <p>{diagnostics.recommendations.status === 'queued' ? `${diagnostics.recommendations.count} collection(s) queued.` : `${diagnostics.recommendations.count} collection(s) refreshed.`}</p>
                        {diagnostics.recommendations.message ? <div className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">{diagnostics.recommendations.message}</div> : null}
                        {(diagnostics.recommendations.items || []).map((item) => <div key={item.collection_id} className="rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2">{titleize(item.recommendation_tier || 'unknown')} · {titleize(item.ranking_bucket || 'unknown')} · {titleize(item.search_boost_tier || 'unknown')}</div>)}
                      </div>
                    ) : <p className="mt-3">Run a recommendation refresh to update ranking and search tiers for this collection.</p>}
                  </div>
                </div>
              </section>

              <form onSubmit={handleHooksSubmit} className="rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7">
                <div className="flex flex-wrap items-start justify-between gap-4">
                  <div>
                    <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-fuchsia-200/80">Hooks</p>
                    <h2 className="mt-2 text-2xl font-semibold text-white">Experiment and program governance</h2>
                    <p className="mt-3 text-sm leading-relaxed text-slate-300">Control experiment keys, promotion tiers, and staff-only program governance hooks for the selected collection without leaving the programming studio.</p>
                  </div>
                  {selectedCollection?.program_key && endpoints.publicProgramPattern ? (
                    <a href={buildProgramUrl(endpoints.publicProgramPattern, selectedCollection.program_key)} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.07]">
                      <i className="fa-solid fa-arrow-up-right-from-square fa-fw text-[11px]" />Open public program landing
                    </a>
                  ) : null}
                </div>

                <div className="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                  <Field label="Experiment Key" help="Internal test or treatment key for cross-surface collection experiments.">
                    <input value={hooksForm.experiment_key} onChange={(event) => setHooksForm((current) => ({ ...current, experiment_key: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                  </Field>
                  <Field label="Treatment" help="Variant or treatment label tied to the experiment key.">
                    <input value={hooksForm.experiment_treatment} onChange={(event) => setHooksForm((current) => ({ ...current, experiment_treatment: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                  </Field>
                  <Field label="Placement Variant" help="Surface-specific placement variant such as homepage_a or search_dense.">
                    <input value={hooksForm.placement_variant} onChange={(event) => setHooksForm((current) => ({ ...current, placement_variant: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                  </Field>
                  <Field label="Ranking Variant" help="Override or annotate ranking mode experiments without changing the live pool logic.">
                    <input value={hooksForm.ranking_mode_variant} onChange={(event) => setHooksForm((current) => ({ ...current, ranking_mode_variant: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                  </Field>
                  <Field label="Pool Version" help="Snapshot or rollout version for the collection pool definition.">
                    <input value={hooksForm.collection_pool_version} onChange={(event) => setHooksForm((current) => ({ ...current, collection_pool_version: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                  </Field>
                  <Field label="Test Label" help="Human-readable campaign or experiment label for operations and diagnostics.">
                    <input value={hooksForm.test_label} onChange={(event) => setHooksForm((current) => ({ ...current, test_label: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={120} />
                  </Field>
                  <Field label="Promotion Tier" help="Optional internal tier for elevated or restrained programming treatment.">
                    <input value={hooksForm.promotion_tier} onChange={(event) => setHooksForm((current) => ({ ...current, promotion_tier: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={40} />
                  </Field>
                  {viewer.isAdmin ? (
                    <>
                      <Field label="Partner Key" help="Admin-only internal key for trusted partner or program ownership.">
                        <input value={hooksForm.partner_key} onChange={(event) => setHooksForm((current) => ({ ...current, partner_key: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                      </Field>
                      <Field label="Trust Tier" help="Admin-only trust marker used for internal partner/program review logic.">
                        <input value={hooksForm.trust_tier} onChange={(event) => setHooksForm((current) => ({ ...current, trust_tier: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={40} />
                      </Field>
                      <Field label="Sponsorship State" help="Admin-only state for sponsored, pending, or cleared program treatment.">
                        <input value={hooksForm.sponsorship_state} onChange={(event) => setHooksForm((current) => ({ ...current, sponsorship_state: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={40} />
                      </Field>
                      <Field label="Ownership Domain" help="Admin-only internal ownership domain such as editorial, partner, creator_program, or events.">
                        <input value={hooksForm.ownership_domain} onChange={(event) => setHooksForm((current) => ({ ...current, ownership_domain: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={80} />
                      </Field>
                      <Field label="Commercial Review" help="Admin-only commercial review status for future partner and sponsor programs.">
                        <input value={hooksForm.commercial_review_state} onChange={(event) => setHooksForm((current) => ({ ...current, commercial_review_state: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={40} />
                      </Field>
                      <Field label="Legal Review" help="Admin-only legal review status when collections need compliance approval before wider promotion.">
                        <input value={hooksForm.legal_review_state} onChange={(event) => setHooksForm((current) => ({ ...current, legal_review_state: event.target.value }))} className="w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" maxLength={40} />
                      </Field>
                    </>
                  ) : <div className="rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-4 py-4 text-sm text-slate-300 md:col-span-2 xl:col-span-3">Partner, sponsorship, ownership, and review metadata remain admin-only. Moderators can still manage experiment and promotion hooks here.</div>}
                </div>

                <div className="mt-4 flex items-center gap-3 rounded-[20px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-200">
                  <Checkbox checked={hooksForm.placement_eligibility} onChange={(event) => setHooksForm((current) => ({ ...current, placement_eligibility: event.target.checked }))} label="Placement eligible override" />
                </div>

                <div className="mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Experiment</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.experiment_key || selectedCollection?.experiment_key || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Treatment</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.experiment_treatment || selectedCollection?.experiment_treatment || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Placement Variant</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.placement_variant || selectedCollection?.placement_variant || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Workflow</div>
                    <div className="mt-1 font-semibold text-white">{titleize(hooksDiagnostics?.workflow_state || selectedCollection?.workflow_state || 'unknown')}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Health</div>
                    <div className="mt-1 font-semibold text-white">{titleize(hooksDiagnostics?.health_state || selectedCollection?.health_state || 'unknown')}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Recommendation Tier</div>
                    <div className="mt-1 font-semibold text-white">{titleize(hooksDiagnostics?.recommendation_tier || selectedCollection?.recommendation_tier || 'unknown')}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Ranking Bucket</div>
                    <div className="mt-1 font-semibold text-white">{titleize(hooksDiagnostics?.ranking_bucket || selectedCollection?.ranking_bucket || 'unknown')}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Ranking Variant</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.ranking_mode_variant || selectedCollection?.ranking_mode_variant || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Pool Version</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.collection_pool_version || selectedCollection?.collection_pool_version || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Test Label</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.test_label || selectedCollection?.test_label || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Promotion Tier</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.promotion_tier || selectedCollection?.promotion_tier || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Partner Key</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.partner_key || selectedCollection?.partner_key || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Trust Tier</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.trust_tier || selectedCollection?.trust_tier || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Sponsorship State</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.sponsorship_state || selectedCollection?.sponsorship_state || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Ownership Domain</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.ownership_domain || selectedCollection?.ownership_domain || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Commercial Review</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.commercial_review_state || selectedCollection?.commercial_review_state || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Legal Review</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.legal_review_state || selectedCollection?.legal_review_state || 'Not set'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Last Health Check</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.last_health_check_at ? new Date(hooksDiagnostics.last_health_check_at).toLocaleString() : 'Not yet'}</div>
                  </div>
                  <div className="rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300">
                    <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Last Recommendation Refresh</div>
                    <div className="mt-1 font-semibold text-white">{hooksDiagnostics?.last_recommendation_refresh_at ? new Date(hooksDiagnostics.last_recommendation_refresh_at).toLocaleString() : 'Not yet'}</div>
                  </div>
                </div>

                <div className="mt-5 flex flex-wrap gap-3">
                  <button type="submit" disabled={busy === 'hooks' || !selectedCollectionId} className="inline-flex items-center gap-2 rounded-2xl border border-fuchsia-300/20 bg-fuchsia-400/10 px-5 py-3 text-sm font-semibold text-fuchsia-100 transition hover:bg-fuchsia-400/15 disabled:opacity-60"><i className={`fa-solid ${busy === 'hooks' ? 'fa-circle-notch fa-spin' : 'fa-flask-vial'} fa-fw`} />Save Hooks</button>
                  {selectedCollection?.manage_url ? <a href={selectedCollection.manage_url} className="inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-arrow-up-right-from-square fa-fw" />Open collection</a> : null}
                </div>
              </form>
            </div>
          </section>

          <section className="mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7">
            <div className="flex flex-wrap items-center justify-between gap-3">
              <div>
                <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80">Assignments</p>
                <h2 className="mt-2 text-2xl font-semibold text-white">Current programming inventory</h2>
              </div>
              <span className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300">{assignments.length}</span>
            </div>

            <div className="mt-6 space-y-5">
              {assignments.length ? assignments.map((assignment) => (
                <div key={assignment.id} className="rounded-[28px] border border-white/10 bg-slate-950/40 p-5">
                  <div className="flex flex-wrap items-center justify-between gap-3">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100">{assignment.program_key}</span>
                      {assignment.placement_scope ? <span className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300">{assignment.placement_scope}</span> : null}
                      <span className="rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300">priority {assignment.priority}</span>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <button type="button" onClick={() => hydrateAssignment(assignment)} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-pen fa-fw text-[10px]" />Edit</button>
                      {endpoints.managePattern ? <a href={endpoints.managePattern.replace('__COLLECTION__', String(assignment.collection?.id || ''))} className="inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]"><i className="fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" />Manage</a> : null}
                    </div>
                  </div>

                  <div className="mt-4 grid gap-5 xl:grid-cols-[minmax(0,1fr)_280px]">
                    <div>
                      {assignment.collection ? <CollectionCard collection={assignment.collection} isOwner /> : null}
                    </div>
                    <div className="space-y-3 text-sm text-slate-300">
                      <div className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3">Campaign: {assignment.campaign_key || 'None'}</div>
                      <div className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3">Starts: {assignment.starts_at ? new Date(assignment.starts_at).toLocaleString() : 'Immediate'}</div>
                      <div className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3">Ends: {assignment.ends_at ? new Date(assignment.ends_at).toLocaleString() : 'Open-ended'}</div>
                      <div className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3">Placement: {assignment.collection?.placement_eligibility ? 'Eligible' : 'Blocked'}</div>
                      {assignment.notes ? <div className="rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3">{assignment.notes}</div> : null}
                    </div>
                  </div>
                </div>
              )) : <div className="rounded-[26px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300">No programming assignments yet. Create the first one above.</div>}
            </div>
          </section>
        </div>
      </div>
    </>
  )
}