'use client'

import { useEffect, useMemo } from 'react'
import { SeoEditorPane } from './seo/SeoEditorPane.js'
import { ResizableAside } from './ui/ResizableAside.js'
import { buildEditorContentHtml } from '../lib/editor-seo-content.js'
import type { PageSection } from '@actuate-media/cms-core/page-sections'

const INSPECTOR_SHELL = 'bg-card border-border flex h-full flex-col border-l'

export interface EditorSeoAsideProps {
  entityType: 'page' | 'post'
  /** Saved document id — when absent, draft mode with live analysis. */
  entityId: string | null
  title: string
  slug: string
  seoTitle: string
  seoDescription: string
  /** Post body HTML and/or section content for live SEO analysis. */
  sections?: PageSection[]
  bodyHtml?: string
  canEdit: boolean
  onClose: () => void
  onDraftChange?: (patch: { seoTitle?: string; seoDescription?: string }) => void
  onSaved?: () => void
}

/** Right-side SEO panel for the Page / Post section editors. */
export function EditorSeoAside({
  entityType,
  entityId,
  slug,
  seoTitle,
  seoDescription,
  sections = [],
  bodyHtml = '',
  onClose,
  onDraftChange,
  onSaved,
}: EditorSeoAsideProps) {
  const contentHtml = useMemo(
    () => buildEditorContentHtml(sections, bodyHtml),
    [sections, bodyHtml],
  )

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [onClose])

  return (
    <ResizableAside role="dialog" aria-label="SEO settings" className={INSPECTOR_SHELL}>
      <SeoEditorPane
        entityType={entityType}
        entityId={entityId}
        slug={slug}
        contentHtml={contentHtml}
        draftMeta={{ seoTitle, seoDescription }}
        onDraftChange={onDraftChange}
        onClose={onClose}
        onSaved={onSaved}
      />
    </ResizableAside>
  )
}
