import React, { useState, useEffect } from 'react';
import { IconZap, IconRuler, IconMoney, IconPhone, IconBarChart, IconBuilding, IconDownload } from '../components/Icons';
import { Routes, Route, NavLink } from 'react-router-dom';
import './Common.css';
import './Support.css';

const SUB_NAV = [
  { path: '/support/notice',  label: '공지사항' },
  { path: '/support/faq',     label: 'FAQ' },
  { path: '/support/catalog', label: '카탈로그' },
  { path: '/support/contact', label: '문의하기' },
];

function SubNav({ title }) {
  return (
    <>
      <div className="page-hero">
        <div className="container">
          <span className="section-label">Support</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>
    </>
  );
}

/* ── 공지사항 ── */
const CAT_COLORS = { '공지':'var(--primary)', '보안':'#dc2626', '이벤트':'var(--accent)', '공지사항':'var(--primary)' };

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

function Notice() {
  const [notices, setNotices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState(null);

  useEffect(() => {
    fetch('/api/news?category=공지사항&size=30')
      .then(r => r.json())
      .then(d => setNotices(d.content ?? d))
      .catch(() => setNotices([]))
      .finally(() => setLoading(false));
  }, []);

  const item = notices.find(n => n.id === selected);

  return (
    <main id="main-content" className="inner-page">
      <SubNav title="공지사항" />
      <section className="section">
        <div className="container" style={{ maxWidth: '860px' }}>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '60px', color: 'var(--gray-400)' }}>불러오는 중...</div>
          ) : item ? (
            <div className="notice-detail">
              <button className="notice-back" onClick={() => setSelected(null)}>← 목록으로</button>
              <div className="notice-detail-header">
                <span className="notice-cat" style={{ background: 'var(--primary-light)', color: 'var(--primary)' }}>{item.category}</span>
                <h2>{item.title}</h2>
                <p className="notice-date">{formatDate(item.createdAt)}</p>
              </div>
              <div className="notice-body">
                {item.content
                  ? item.content.split('\n').map((p, i) => p.trim() ? <p key={i}>{p}</p> : null)
                  : <><p>안녕하세요, (주)지오정보기술입니다.</p><p>자세한 사항은 고객지원팀(031-483-1766)으로 문의해 주시기 바랍니다.</p></>}
              </div>
            </div>
          ) : notices.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--gray-400)' }}>
              <p style={{ fontSize: '48px' }}>📋</p>
              <p>등록된 공지사항이 없습니다.</p>
            </div>
          ) : (
            <div className="notice-list">
              <div className="notice-header-row">
                <span>구분</span><span>제목</span><span>등록일</span>
              </div>
              {notices.map(n => (
                <div key={n.id} className="notice-row" onClick={() => setSelected(n.id)}>
                  <span className="notice-cat" style={{ background: 'var(--primary-light)', color: 'var(--primary)' }}>{n.category}</span>
                  <span className="notice-title-text">{n.title}</span>
                  <span className="notice-date">{formatDate(n.createdAt)}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>
    </main>
  );
}

/* ── FAQ ── */
function FAQ() {
  const [faqs, setFaqs]   = useState([]);
  const [loading, setLoading] = useState(true);
  const [openIdx, setOpenIdx] = useState({});
  const toggle = (ci, qi) => setOpenIdx(p => ({ ...p, [`${ci}-${qi}`]: !p[`${ci}-${qi}`] }));

  useEffect(() => {
    fetch('/api/faq')
      .then(r => r.json())
      .then(data => setFaqs(data))
      .catch(() => setFaqs([]))
      .finally(() => setLoading(false));
  }, []);

  return (
    <main id="main-content" className="inner-page">
      <SubNav title="자주 묻는 질문" />
      <section className="section">
        <div className="container" style={{ maxWidth: '860px' }}>
          <div className="section-header">
            <span className="section-label">FAQ</span>
            <h2 className="section-title">자주 묻는 질문</h2>
          </div>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '60px', color: 'var(--gray-400)' }}>불러오는 중...</div>
          ) : faqs.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '60px', color: 'var(--gray-400)' }}>
              <p style={{ fontSize: '40px' }}>❓</p><p>등록된 FAQ가 없습니다.</p>
            </div>
          ) : faqs.map((cat, ci) => (
            <div key={ci} className="faq-cat-wrap">
              <h3 className="faq-cat-title">{cat.cat}</h3>
              {cat.items.map((item, qi) => {
                const key = `${ci}-${qi}`;
                const open = openIdx[key];
                return (
                  <div key={qi} className={`faq-item ${open ? 'open' : ''}`}>
                    <button className="faq-q" onClick={() => toggle(ci, qi)}>
                      <span className="faq-icon">{open ? '−' : '+'}</span>
                      {item.q}
                    </button>
                    {open && <div className="faq-a">{item.a}</div>}
                  </div>
                );
              })}
            </div>
          ))}
          <div className="faq-more">
            <p>원하시는 답변을 찾지 못하셨나요?</p>
            <a href="/support/contact" className="btn btn-primary">1:1 문의하기</a>
          </div>
        </div>
      </section>
    </main>
  );
}

/* ── 카탈로그 ── */
const CATALOGS = [
  { title:'GUARDiA ITSM v2.0 제품 카탈로그',   desc:'GUARDiA ITSM 전체 기능 및 도입 가이드',        pages:'24p', size:'4.2MB', date:'2026.05', icon:<IconZap size={28} color="var(--primary)"/>,    color:'var(--primary)' },
  { title:'GUARDiA ITSM 기술 명세서',          desc:'API 명세, 아키텍처, 보안 설계 문서',            pages:'48p', size:'8.1MB', date:'2026.05', icon:<IconRuler size={28} color="#7c3aed"/>,           color:'#7c3aed' },
  { title:'ERP 솔루션 카탈로그',               desc:'공공·중견기업 맞춤형 ERP 모듈 소개',           pages:'16p', size:'3.5MB', date:'2026.03', icon:<IconMoney size={28} color="#059669"/>,            color:'#059669' },
  { title:'CRM 솔루션 카탈로그',               desc:'AI 기반 고객관리 플랫폼 소개',                 pages:'12p', size:'2.8MB', date:'2026.03', icon:<IconPhone size={28} color="#d97706"/>,            color:'#d97706' },
  { title:'BI 솔루션 카탈로그',                desc:'경영 분석 및 대시보드 플랫폼 소개',            pages:'12p', size:'2.4MB', date:'2026.02', icon:<IconBarChart size={28} color="#0891b2"/>,         color:'#0891b2' },
  { title:'지오정보기술 회사 소개서',           desc:'회사 연혁, 사업 영역, 주요 레퍼런스',          pages:'20p', size:'5.6MB', date:'2026.01', icon:<IconBuilding size={28} color="var(--secondary)"/>, color:'var(--secondary)' },
];

function Catalog() {
  return (
    <main id="main-content" className="inner-page">
      <SubNav title="카탈로그" />
      <section className="section">
        <div className="container">
          <div className="section-header">
            <span className="section-label">Catalog</span>
            <h2 className="section-title">자료실</h2>
            <p className="section-desc">제품 카탈로그 및 기술 문서를 다운로드하세요</p>
          </div>
          <div className="grid-3">
            {CATALOGS.map((c, i) => (
              <div key={i} className="card catalog-card">
                <div className="catalog-icon-wrap" style={{ background: c.color + '18' }}>
                  <span className="catalog-icon" style={{ color: c.color, display:'flex' }}>{c.icon}</span>
                </div>
                <div className="catalog-info">
                  <h3 className="catalog-title">{c.title}</h3>
                  <p className="catalog-desc">{c.desc}</p>
                  <div className="catalog-meta">
                    <span>{c.pages}</span>
                    <span>{c.size}</span>
                    <span>{c.date}</span>
                  </div>
                </div>
                <button className="catalog-btn" onClick={() => alert('문의하기 페이지에서 카탈로그를 요청해주세요.')}>
                  📥 다운로드
                </button>
              </div>
            ))}
          </div>
          <div className="catalog-request">
            <h3>다른 자료가 필요하신가요?</h3>
            <p>NDA 자료, 기술 제안서, 가격표 등 별도 문서는 영업팀에 요청해 주십시오.</p>
            <a href="/support/contact" className="btn btn-outline btn-lg">자료 요청하기</a>
          </div>
        </div>
      </section>
    </main>
  );
}

export default function Support() {
  return (
    <Routes>
      <Route path="notice"  element={<Notice />} />
      <Route path="faq"     element={<FAQ />} />
      <Route path="catalog" element={<Catalog />} />
      <Route path="*"       element={<Notice />} />
    </Routes>
  );
}
