'use client'

import { useEffect, useState } from 'react'
import LandingPage from '@/components/LandingPage'
import type { LandingContent } from '@/lib/content'

// Renders the homepage from in-progress editor state stashed in localStorage
// by the admin/content editor's "Preview" button. Lets Mahlin see what a save
// would look like on the live site without committing it.
export default function PreviewPage() {
  const [content, setContent] = useState<LandingContent | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    try {
      const raw = localStorage.getItem('preview-content')
      if (!raw) {
        setError('No preview data found. Open the content editor and click Preview.')
        return
      }
      setContent(JSON.parse(raw))
    } catch {
      setError('Could not load preview data — the stash in localStorage may be corrupt.')
    }
  }, [])

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6 bg-gray-100">
        <div className="bg-white p-8 rounded-2xl shadow-md max-w-md text-center">
          <i className="fas fa-eye-slash text-4xl text-gray-400 mb-4"></i>
          <p className="text-gray-700 mb-0">{error}</p>
        </div>
      </div>
    )
  }

  if (!content) return null

  return (
    <>
      <LandingPage content={content} year={new Date().getFullYear()} />
      <div className="fixed bottom-0 left-0 right-0 z-[100] bg-amber-500 text-white text-center py-2 text-sm font-semibold shadow-lg">
        <i className="fas fa-eye mr-2"></i>Preview mode &mdash; these changes are not yet saved
        <button
          onClick={() => window.close()}
          className="ml-4 underline hover:opacity-80"
        >
          close
        </button>
      </div>
    </>
  )
}
