'use client'

import { Image as ImageIcon, ExternalLink } from 'lucide-react'
import type { FigureUnit } from '@/lib/sdk/advisor/evidence'
import { PaneHeader } from './PaneHeader'

function FigureCard({ fig }: { fig: FigureUnit }) {
  const canOpen = !!fig.imageUrl && /^https?:\/\//i.test(fig.imageUrl)
  return (
    <div className="rounded-lg border border-gray-200 bg-white p-2.5">
      <div className="flex items-start justify-between gap-2">
        <div className="text-xs font-semibold text-gray-900">
          {fig.label}
          {fig.caption ? <span className="font-normal text-gray-600"> — {fig.caption}</span> : null}
        </div>
        {canOpen && (
          <a
            href={fig.imageUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="flex flex-shrink-0 items-center gap-0.5 rounded px-1.5 py-0.5 text-[11px] font-medium text-indigo-600 hover:bg-indigo-50"
          >
            <ExternalLink className="h-3 w-3" />
            Original anzeigen
          </a>
        )}
      </div>
      <div className="mt-0.5 text-[11px] text-gray-500">
        Quelle: {fig.source.short}
        {fig.section ? ` · ${fig.section}` : ''}
      </div>
      {canOpen ? (
        <a href={fig.imageUrl} target="_blank" rel="noopener noreferrer" className="mt-1.5 block">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={fig.imageUrl}
            alt={fig.caption || fig.label}
            loading="lazy"
            className="max-h-44 w-full rounded border border-gray-100 object-contain"
          />
        </a>
      ) : (
        <div className="mt-1.5 flex items-center justify-center rounded border border-dashed border-gray-200 bg-gray-50 px-3 py-5 text-[11px] text-gray-400">
          Original-Abbildung folgt
        </div>
      )}
      {fig.visionSummary && (
        <p className="mt-1.5 text-[11px] italic text-gray-500">{fig.visionSummary}</p>
      )}
    </div>
  )
}

/** Figures pane (C8) — original document figures, rendered only when present. */
export function FiguresPane({ figures }: { figures: FigureUnit[] }) {
  if (figures.length === 0) return null
  return (
    <section>
      <PaneHeader
        icon={<ImageIcon className="h-3.5 w-3.5 text-gray-500" />}
        title="Abbildungen & Diagramme"
        count={figures.length}
      />
      <div className="space-y-1.5">
        {figures.map((f) => (
          <FigureCard key={f.id} fig={f} />
        ))}
      </div>
    </section>
  )
}
