import TemplateCard from '@/components/TemplateCard';
import { useI18n } from '@/hooks/useI18n';
import { i18nManager } from '@/i18n/manager';
import { api, Template } from '@/services/api';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './index.css';

export default function Home() {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [templates, setTemplates] = useState<Template[]>([]);

  useEffect(() => {
    const loadTemplates = async () => {
      try {
        const templates = await api.getAllTemplates();
        setTemplates(templates);
      } catch (error) {
        console.error('加载模板失败:', error);
        alert(t('home.loadTemplatesFailed'));
      }
    };
    loadTemplates();
    // 设置页面标题
    i18nManager.updateNavigationBarTitle('home');
  }, []);

  const handleTemplateClick = async (template: Template) => {
    navigate(`/create/${template.code}`);
    return;
  };

  return (
    <div className="home">
      <div className="home-header">
        New User 50% Off : <span className="coupon-text">NEWUSER</span>
      </div>
      <div className="home-scroll">
        <div className="template-grid">
          {templates.map(template => (
            <TemplateCard key={template.code} template={template} onClick={handleTemplateClick} />
          ))}
        </div>
      </div>
    </div>
  );
}
