'use client';

import React, { useEffect, useState } from 'react';
import { apiRequest } from '../../../lib/api';
import { PageHeader } from '../../../components/PageHeader';
import { ErrorBlock, LoadingBlock } from '../../../components/StateBlock';

export default function TermsPage() {
  const [doc, setDoc] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const load = async () => {
    setLoading(true);
    try {
      const res = await apiRequest('/settings?category=GENERAL');
      const hit = (res.data || []).find((s: any) => s.key === 'TERMS_CONTENT');
      setDoc(hit?.value || { title: 'Terms of use', body: 'Content not configured yet. Check back soon.' });
      setError('');
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  if (loading) return <LoadingBlock />;
  if (error) {
    return (
      <div className="space-y-3">
        <PageHeader title="Terms" backHref="/profile" backLabel="Account" />
        <ErrorBlock message={error} onRetry={load} />
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <PageHeader title={doc.title || 'Terms'} backHref="/profile" backLabel="Account" />
      <article className="d11-card p-5 sm:p-6">
        <p className="whitespace-pre-wrap text-sm leading-relaxed text-d11-muted">{doc.body}</p>
      </article>
    </div>
  );
}
