"use client";

import { useEffect, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

interface PlanViewerProps {
	url: string;
}

export default function PlanViewer({ url }: PlanViewerProps) {
	const [markdown, setMarkdown] = useState<string | null>(null);
	const [error, setError] = useState<string | null>(null);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		setLoading(true);
		setError(null);
		setMarkdown(null);

		fetch(`/api/fetch-markdown?url=${encodeURIComponent(url)}`)
			.then(async res => {
				if (!res.ok) {
					const body = await res.json().catch(() => ({}));
					throw new Error(body.error ?? `Failed to fetch (${res.status})`);
				}
				return res.text();
			})
			.then(setMarkdown)
			.catch(err => setError(err.message))
			.finally(() => setLoading(false));
	}, [url]);

	if (loading) {
		return (
			<div className="bg-surface border border-border rounded-lg p-6 text-sm text-text-secondary animate-pulse">
				Loading markdown...
			</div>
		);
	}

	if (error) {
		return (
			<div className="bg-surface border border-danger/30 rounded-lg p-6 text-sm text-danger">
				{error}
			</div>
		);
	}

	return (
		<div className="bg-surface border border-border rounded-lg p-6 markdown-content">
			<ReactMarkdown remarkPlugins={[remarkGfm]}>{markdown ?? ""}</ReactMarkdown>
		</div>
	);
}
