'use client'

import { useEffect, useState, useCallback } from 'react'
import { useParams } from 'next/navigation'
import { Language, PitchData } from '@/lib/types'
import PitchDeck from '@/components/PitchDeck'

export default function PreviewPage() {
  const { versionId } = useParams<{ versionId: string }>()
  const [data, setData] = useState<PitchData | null>(null)
  const [versionMeta, setVersionMeta] = useState<{ name: string; status: string } | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [lang, setLang] = useState<Language>('de')

  const toggleLanguage = useCallback(() => {
    setLang(prev => prev === 'de' ? 'en' : 'de')
  }, [])

  useEffect(() => {
    if (!versionId) return
    setLoading(true)
    fetch(`/api/preview-data/${versionId}`)
      .then(async r => {
        if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || 'Failed to load')
        return r.json()
      })
      .then(d => {
        if (d._version) {
          setVersionMeta(d._version)
          delete d._version
        }
        setData(d)
      })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false))
  }, [versionId])

  if (loading) {
    return (
      <div className="h-screen flex items-center justify-center bg-[#0a0a1a]">
        <div className="text-center">
          <div className="w-12 h-12 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin mx-auto mb-4" />
          <p className="text-white/40 text-sm">Loading preview...</p>
        </div>
      </div>
    )
  }

  if (error || !data) {
    return (
      <div className="h-screen flex items-center justify-center bg-[#0a0a1a]">
        <div className="text-center max-w-md px-6">
          <p className="text-rose-400 mb-2">Preview Error</p>
          <p className="text-white/40 text-sm">{error || 'No data found for this version'}</p>
          <p className="text-white/30 text-xs mt-4">Make sure you are logged in as an admin.</p>
        </div>
      </div>
    )
  }

  // Render PitchDeck with no investor (no watermark, no audit) — admin preview only
  // The banner at the top indicates this is a preview
  return (
    <div className="relative">
      {/* Preview banner */}
      <div className="fixed top-0 left-0 right-0 z-[100] bg-amber-500/90 text-black text-center py-1.5 text-xs font-semibold tracking-wide">
        PREVIEW: {versionMeta?.name ?? 'Loading...'} — {versionMeta?.status === 'draft' ? 'Draft' : 'Committed'}
      </div>
      <PitchDeck
        lang={lang}
        onToggleLanguage={toggleLanguage}
        investor={null}
        onLogout={() => {}}
        previewData={data}
      />
    </div>
  )
}
