'use client'

import { useState } from 'react'
import type { ContainerNode } from '@actuate-media/cms-core'
import { RowRenderer } from './RowRenderer.js'

export interface ContainerRendererProps {
  node: ContainerNode
  selectedNodeId: string | null
  onSelectNode: (id: string | null) => void
}

export function ContainerRenderer({ node, selectedNodeId, onSelectNode }: ContainerRendererProps) {
  const [hovered, setHovered] = useState(false)
  const isSelected = selectedNodeId === node.id
  const maxWidth = node.settings.maxWidth ?? '1200px'
  const alignment = node.settings.alignment ?? 'center'
  const padding = node.settings.padding

  const marginMap: Record<string, string> = {
    left: '0 auto 0 0',
    center: '0 auto',
    right: '0 0 0 auto',
  }

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation()
    onSelectNode(node.id)
  }

  return (
    <div
      data-node-id={node.id}
      className={`relative transition-shadow ${
        isSelected ? 'ring-primary ring-2 ring-offset-2' : hovered ? 'ring-primary/50 ring-1' : ''
      }`}
      style={{
        maxWidth,
        margin: marginMap[alignment] ?? '0 auto',
        padding,
      }}
      onClick={handleClick}
      onMouseEnter={(e) => {
        e.stopPropagation()
        setHovered(true)
      }}
      onMouseLeave={() => setHovered(false)}
    >
      {(hovered || isSelected) && (
        <span className="bg-primary text-primary-foreground absolute -top-2 -left-1 z-10 rounded px-1.5 py-0.5 text-xs font-medium">
          Container
        </span>
      )}

      <div className="flex flex-col gap-4">
        {node.children.map((row) => (
          <RowRenderer
            key={row.id}
            node={row}
            selectedNodeId={selectedNodeId}
            onSelectNode={onSelectNode}
          />
        ))}
      </div>
    </div>
  )
}
