import React, { useState, useEffect } from 'react';
import { Routes, Route, NavLink } from 'react-router-dom';
import './Common.css';
import './NewsPage.css';

const SUB_NAV = [
  { path: '/news/newsroom', label: '뉴스룸' },
  { path: '/news/blog',     label: '기술 블로그' },
];

function SubNav({ title }) {
  return (
    <>
      <div className="page-hero">
        <div className="container">
          <span className="section-label">News</span>
          <h1 className="page-hero-title">{title}</h1>
        </div>
      </div>
      <nav className="sub-nav">
        <div className="container">
          {SUB_NAV.map(n => (
            <NavLink key={n.path} to={n.path}
              className={({ isActive }) => 'sub-nav-item' + (isActive ? ' active' : '')}>
              {n.label}
            </NavLink>
          ))}
        </div>
      </nav>
    </>
  );
}

function useNews(category) {
  const [news, setNews]   = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    fetch(`/api/news?category=${encodeURIComponent(category)}&size=20`)
      .then(r => r.json())
      .then(data => setNews(data.content ?? data))
      .catch(() => setNews([]))
      .finally(() => setLoading(false));
  }, [category]);
  return { news, loading };
}

function formatDate(dt) {
  if (!dt) return '';
  return String(dt).slice(0, 10).replace(/-/g, '.');
}

/* ── 뉴스룸 ── */
function Newsroom() {
  const { news, loading } = useNews('뉴스룸');
  const [selected, setSelected] = useState(null);
  const item = news.find(n => n.id === selected);

  if (loading) return (
    <main className="inner-page">
      <SubNav title="뉴스룸" />
      <section className="section"><div className="container" style={{textAlign:'center',padding:'60px',color:'var(--gray-400)'}}>불러오는 중...</div></section>
    </main>
  );

  return (
    <main id="main-content" className="inner-page">
      <SubNav title="뉴스룸" />
      <section className="section">
        <div className="container">
          {item ? (
            <div style={{ maxWidth: '760px', margin: '0 auto' }}>
              <button className="notice-back" onClick={() => setSelected(null)}>← 뉴스 목록</button>
              <div className="news-detail card" style={{ padding: '40px' }}>
                <span className="news-cat-badge" style={{ background: 'var(--primary-light)', color: 'var(--primary)' }}>{item.category}</span>
                <h2 style={{ fontSize: '24px', fontWeight: '900', margin: '16px 0 8px', lineHeight: '1.4' }}>{item.title}</h2>
                <p style={{ fontSize: '13px', color: 'var(--gray-400)', marginBottom: '32px' }}>{formatDate(item.createdAt)}</p>
                <div className="divider divider-left" style={{ marginBottom: '32px' }} />
                {(item.content || item.summary || '').split('\n').map((p, i) => (
                  p.trim() ? <p key={i} style={{ fontSize: '15px', color: 'var(--gray-700)', lineHeight: '1.85', marginBottom: '16px' }}>{p}</p> : null
                ))}
              </div>
            </div>
          ) : news.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--gray-400)' }}>
              <p style={{ fontSize: '48px', marginBottom: '16px' }}>📰</p>
              <p>등록된 뉴스가 없습니다.</p>
              <p style={{ fontSize: '13px', marginTop: '8px' }}>관리자 페이지에서 뉴스를 추가해 주세요.</p>
            </div>
          ) : (
            <>
              <div className="news-main card" onClick={() => setSelected(news[0].id)} style={{ cursor: 'pointer' }}>
                <div className="news-main-content">
                  <span className="news-cat-badge hot">🔥 {news[0].category}</span>
                  <h2 className="news-main-title">{news[0].title}</h2>
                  <p className="news-main-summary">{news[0].summary}</p>
                  <span className="news-date">{formatDate(news[0].createdAt)}</span>
                </div>
              </div>
              <div className="grid-3" style={{ marginTop: '24px' }}>
                {news.slice(1).map(n => (
                  <div key={n.id} className="card news-card" onClick={() => setSelected(n.id)} style={{ cursor: 'pointer' }}>
                    <span className="news-cat-badge" style={{ background: 'var(--primary-light)', color: 'var(--primary)' }}>{n.category}</span>
                    <h3 className="news-card-title">{n.title}</h3>
                    <p className="news-card-summary">{n.summary}</p>
                    <span className="news-date">{formatDate(n.createdAt)}</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </section>
    </main>
  );
}

/* ── 기술 블로그 ── */
function Blog() {
  const { news: blogs, loading } = useNews('기술블로그');
  const [selected, setSelected] = useState(null);
  const item = blogs.find(b => b.id === selected);

  if (loading) return (
    <main className="inner-page">
      <SubNav title="기술 블로그" />
      <section className="section"><div className="container" style={{textAlign:'center',padding:'60px',color:'var(--gray-400)'}}>불러오는 중...</div></section>
    </main>
  );

  return (
    <main id="main-content" className="inner-page">
      <SubNav title="기술 블로그" />
      <section className="section">
        <div className="container">
          {item ? (
            <div style={{ maxWidth: '760px', margin: '0 auto' }}>
              <button className="notice-back" onClick={() => setSelected(null)}>← 블로그 목록</button>
              <div className="news-detail card" style={{ padding: '40px' }}>
                <span className="news-cat-badge" style={{ background: '#7c3aed18', color: '#7c3aed' }}>{item.category}</span>
                <h2 style={{ fontSize: '24px', fontWeight: '900', margin: '16px 0 8px', lineHeight: '1.4' }}>{item.title}</h2>
                <p style={{ fontSize: '13px', color: 'var(--gray-400)', marginBottom: '32px' }}>{formatDate(item.createdAt)}</p>
                <div className="divider divider-left" style={{ marginBottom: '32px' }} />
                {(item.content || item.summary || '').split('\n').map((p, i) => (
                  p.trim() ? <p key={i} style={{ fontSize: '15px', color: 'var(--gray-700)', lineHeight: '1.85', marginBottom: '16px' }}>{p}</p> : null
                ))}
              </div>
            </div>
          ) : blogs.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--gray-400)' }}>
              <p style={{ fontSize: '48px', marginBottom: '16px' }}>✍️</p>
              <p>등록된 블로그 포스트가 없습니다.</p>
              <p style={{ fontSize: '13px', marginTop: '8px' }}>관리자 페이지에서 블로그를 추가해 주세요.</p>
            </div>
          ) : (
            <>
              <div className="section-header">
                <span className="section-label">Tech Blog</span>
                <h2 className="section-title">기술 인사이트 공유</h2>
                <p className="section-desc">20년 이상의 프로젝트 경험에서 얻은 기술 노하우를 공유합니다</p>
              </div>
              <div className="grid-3">
                {blogs.map(b => (
                  <div key={b.id} className="card blog-card" onClick={() => setSelected(b.id)} style={{ cursor: 'pointer' }}>
                    <div className="blog-tag" style={{ background: '#7c3aed18', color: '#7c3aed' }}>
                      {b.category}
                    </div>
                    <h3 className="blog-title">{b.title}</h3>
                    <p className="blog-summary">{b.summary}</p>
                    <div className="blog-meta">
                      <span>📅 {formatDate(b.createdAt)}</span>
                    </div>
                    <button className="blog-read-btn" onClick={e => { e.stopPropagation(); setSelected(b.id); }}>
                      읽기 →
                    </button>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </section>
    </main>
  );
}

export default function NewsPage() {
  return (
    <Routes>
      <Route path="newsroom" element={<Newsroom />} />
      <Route path="blog"     element={<Blog />} />
      <Route path="press"    element={<Newsroom />} />
      <Route path="*"        element={<Newsroom />} />
    </Routes>
  );
}
