import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import api from '../api/client';

function Stars({ rating }) {
  if (!rating) return <span className="text-muted">리뷰 없음</span>;
  return <span className="stars">{'★'.repeat(Math.round(rating))}{'☆'.repeat(5 - Math.round(rating))}</span>;
}

export default function Home() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading]   = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    api.get('/products?sort=popular&limit=6')
      .then(r => setProducts(r.data.products || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return (
    <div>
      {/* Hero */}
      <div style={{ background: 'var(--bg2)', borderBottom: '1px solid var(--border)', padding: '60px 0' }}>
        <div className="container text-center">
          <h1 style={{ fontSize: 36, marginBottom: 16, color: 'var(--accent2)' }}>
            ESP32 DIY 플랫폼
          </h1>
          <p style={{ color: 'var(--text2)', fontSize: 16, marginBottom: 32, maxWidth: 500, margin: '0 auto 32px' }}>
            직접 만든 ESP32 프로젝트를 공유하고 판매하세요.<br />
            펌웨어 구매 후 브라우저에서 바로 플래시까지.
          </p>
          <div style={{ display: 'flex', gap: 12, justifyContent: 'center' }}>
            <Link to="/shop" className="btn btn-primary">상점 둘러보기</Link>
            <Link to="/projects" className="btn btn-outline">프로젝트 탐색</Link>
          </div>
        </div>
      </div>

      {/* 인기 상품 */}
      <div className="container page">
        <div className="flex items-center justify-between" style={{ marginBottom: 20 }}>
          <h2 style={{ fontSize: 20 }}>인기 상품</h2>
          <Link to="/shop" className="text-muted" style={{ fontSize: 13 }}>전체 보기 →</Link>
        </div>

        {loading ? <div className="spinner" /> : (
          <div className="card-grid">
            {products.map(p => (
              <div key={p.id} className="project-card" onClick={() => navigate(`/shop/${p.id}`)}>
                {p.project.files[0]
                  ? <img src={p.project.files[0].thumbnailUrl || p.project.files[0].url} alt={p.project.title} />
                  : <div style={{ height: 180, background: 'var(--bg3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text2)' }}>이미지 없음</div>
                }
                <div className="project-card-body">
                  <div className="project-card-title">{p.project.title}</div>
                  <div className="project-card-meta">
                    <span>{p.project.user.nickname}</span>
                    <Stars rating={p.avgRating} />
                    <span style={{ marginLeft: 'auto', color: 'var(--accent2)', fontWeight: 600 }}>
                      ₩{p.price.toLocaleString()}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {products.length === 0 && !loading && (
          <div className="card text-center" style={{ padding: 48 }}>
            <p className="text-muted">아직 등록된 상품이 없습니다.</p>
            <Link to="/dashboard/projects/new" className="btn btn-primary" style={{ marginTop: 16 }}>
              첫 프로젝트 등록하기
            </Link>
          </div>
        )}
      </div>

      {/* 특징 소개 */}
      <div style={{ background: 'var(--bg2)', borderTop: '1px solid var(--border)', padding: '48px 0' }}>
        <div className="container">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 24 }}>
            {[
              { icon: '🔧', title: '프로젝트 공유', desc: '회로도, STL, 부품 목록을 함께 공유' },
              { icon: '💸', title: '수익화', desc: '내 프로젝트에서 펌웨어 판매 수익 창출' },
              { icon: '⚡', title: '브라우저 플래시', desc: '구매 후 USB 연결만으로 즉시 플래시' },
              { icon: '⭐', title: '리뷰 시스템', desc: '완성품 사진·영상으로 제품 평가' },
            ].map(f => (
              <div key={f.title} className="card" style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 32, marginBottom: 12 }}>{f.icon}</div>
                <div style={{ fontWeight: 600, marginBottom: 6 }}>{f.title}</div>
                <div className="text-muted" style={{ fontSize: 13 }}>{f.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
