'use client'

import type { BlockPreviewProps } from './index.js'

export function TextPreview({ data, variant = 'prose' }: BlockPreviewProps) {
  const body = (data.body as string) || ''
  const heading = (data.heading as string) || ''
  const headingLevel = (data.headingLevel as string) || 'h2'

  const truncatedBody = body.length > 300 ? body.slice(0, 300) + '…' : body

  const validLevels = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] as const
  const HeadingTag = (validLevels.includes(headingLevel as any) ? headingLevel : 'h2') as
    | 'h1'
    | 'h2'
    | 'h3'
    | 'h4'
    | 'h5'
    | 'h6'
  const headingSizeClass =
    HeadingTag === 'h1' ? 'text-2xl' : HeadingTag === 'h2' ? 'text-xl' : 'text-lg'

  if (variant === 'two-column') {
    const midpoint = Math.ceil(truncatedBody.length / 2)
    const col1 = truncatedBody.slice(0, midpoint)
    const col2 = truncatedBody.slice(midpoint)

    return (
      <div className="border-border rounded-md border p-5">
        {heading && (
          <HeadingTag className={`${headingSizeClass} text-foreground mb-3 font-medium`}>
            {heading}
          </HeadingTag>
        )}
        <div className="grid grid-cols-2 gap-4">
          <p className="text-muted-foreground text-sm leading-relaxed">
            {col1 || 'Column one text content…'}
          </p>
          <p className="text-muted-foreground text-sm leading-relaxed">
            {col2 || 'Column two text content…'}
          </p>
        </div>
      </div>
    )
  }

  if (variant === 'with-sidebar') {
    return (
      <div className="border-border grid grid-cols-[1fr_200px] gap-4 rounded-md border p-5">
        <div>
          {heading && (
            <HeadingTag className={`${headingSizeClass} text-foreground mb-3 font-medium`}>
              {heading}
            </HeadingTag>
          )}
          <p className="text-muted-foreground text-sm leading-relaxed">
            {truncatedBody || 'Body text content goes here…'}
          </p>
        </div>
        <aside className="bg-muted rounded-md p-3">
          <div className="bg-border h-3 w-3/4 rounded" />
          <div className="bg-border mt-2 h-2 w-full rounded" />
          <div className="bg-border mt-1 h-2 w-2/3 rounded" />
        </aside>
      </div>
    )
  }

  return (
    <div className="border-border rounded-md border p-5">
      {heading && (
        <HeadingTag className={`${headingSizeClass} text-foreground mb-3 font-medium`}>
          {heading}
        </HeadingTag>
      )}
      <p className="text-muted-foreground text-sm leading-relaxed">
        {truncatedBody || <span className="italic">Body text content goes here…</span>}
      </p>
    </div>
  )
}
