'use client'

import { LayoutGrid } from 'lucide-react'
import type { PageNode } from '@actuate-media/cms-core'
import { SectionRenderer } from './SectionRenderer.js'

export interface BuilderCanvasProps {
  tree: PageNode
  selectedNodeId: string | null
  showGridOverlay: boolean
  deviceMode: 'desktop' | 'tablet' | 'mobile'
  onSelectNode: (id: string | null) => void
}

const DEVICE_CLASSES: Record<BuilderCanvasProps['deviceMode'], string> = {
  desktop: 'w-full',
  tablet: 'max-w-[768px] mx-auto',
  mobile: 'max-w-[375px] mx-auto',
}

export function BuilderCanvas({
  tree,
  selectedNodeId,
  showGridOverlay,
  deviceMode,
  onSelectNode,
}: BuilderCanvasProps) {
  const handleCanvasClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onSelectNode(null)
    }
  }

  return (
    <div className="bg-muted relative flex-1 overflow-auto p-6" onClick={handleCanvasClick}>
      {showGridOverlay && <GridOverlay deviceMode={deviceMode} />}

      <div
        className={`bg-background relative min-h-full shadow-sm ${DEVICE_CLASSES[deviceMode]}`}
        onClick={handleCanvasClick}
      >
        {tree.children.map((child) => {
          if (child.type === 'section') {
            return (
              <SectionRenderer
                key={child.id}
                node={child}
                selectedNodeId={selectedNodeId}
                onSelectNode={onSelectNode}
              />
            )
          }
          return null
        })}

        {tree.children.length === 0 && (
          <div className="flex min-h-[400px] flex-col items-center justify-center text-center">
            <LayoutGrid size={32} className="text-muted-foreground mb-3" />
            <p className="text-foreground mb-1 text-sm font-medium">No sections yet</p>
            <p className="text-muted-foreground text-xs">
              Click "Add Section" below to start building your page
            </p>
          </div>
        )}
      </div>
    </div>
  )
}

function GridOverlay({ deviceMode }: { deviceMode: BuilderCanvasProps['deviceMode'] }) {
  return (
    <div
      className={`pointer-events-none absolute inset-0 z-50 p-6 ${
        deviceMode !== 'desktop' ? 'flex justify-center' : ''
      }`}
      aria-hidden="true"
    >
      <div
        className={`grid h-full grid-cols-12 gap-4 opacity-[0.08] ${DEVICE_CLASSES[deviceMode]}`}
      >
        {Array.from({ length: 12 }).map((_, i) => (
          <div key={i} className="bg-primary h-full rounded-sm" />
        ))}
      </div>
    </div>
  )
}
