'use client';
import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import BookPreview from '@/components/BookPreview';
import { book, auth, type User } from '@/utils/api';
import toast from 'react-hot-toast';

export default function BookPage() {
  const { bookId } = useParams<{ bookId: string }>();
  const router = useRouter();
  const [data, setData] = useState<{ bookDraft: string; client: any } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const init = async () => {
      try {
        const token = localStorage.getItem('muse_token');
        if (!token) { router.push('/'); return; }
        await auth.verify();
        const res = await book.get(bookId);
        setData(res);
      } catch (err: any) {
        toast.error(err.message || 'Failed to load book');
        router.push('/');
      } finally {
        setLoading(false);
      }
    };
    init();
  }, [bookId, router]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bg-primary)' }}>
        <div className="flex gap-1.5">
          <div className="typing-dot" />
          <div className="typing-dot" style={{ animationDelay: '0.2s' }} />
          <div className="typing-dot" style={{ animationDelay: '0.4s' }} />
        </div>
      </div>
    );
  }

  if (!data) return null;

  return (
    <BookPreview
      bookDraft={data.bookDraft}
      client={data.client}
      clientId={bookId}
      onBack={() => window.location.href = '/'}
    />
  );
}
