// Main page React
const { useState, useEffect } = React;

const TWEAK_DEFAULS = /*EDITMODE-BEGIN*/{
  "primaryColor": "#1e3a8a",
  "primaryLight": "#3b82f6"
} /*EDITMODE-END*/;

const QUICK_MENUS = [
{ icon: 'fa-calculator', label: '원가계산용역', desc: '예정가격 결정 기초자료 작성', href: 'research-cost.html' },
{ icon: 'fa-microscope', label: '학술연구용역', desc: '정책·시책 자문을 위한 연구', href: 'research-academic.html' },
{ icon: 'fa-seedling', label: '탄소 ESG 연구', desc: '탄소중립 · ESG 경영 전략 연구', href: 'research-esg.html' },
{ icon: 'fa-file-contract', label: '개발부담금 E/S', desc: '계약금액 조정 산정 및 분석', href: 'research-burden.html' }];


const REPORTS = {
  all: [
  { cat: '경제/산업', chip: 'blue', org: '산업연구원', date: '2026.04.20', title: 'AI 기술 도입에 따른 중소기업 생산성 변화 분석 연구', excerpt: '본 연구는 국내 중소기업의 AI 도입 실태를 파악하고 기술 성숙도에 따른 생산성 변화 추이를 분석하여 맞춤형 지원 정책을 제안합니다.', author: '김철수', views: '1,245', pages: '256p' },
  { cat: '사회/복지', chip: 'green', org: '한국보건사회연구원', date: '2026.04.18', title: '저출생 대응을 위한 지역별 맞춤형 양육 서비스 지원 체계 개선 방안', excerpt: '지역별 인구 구조와 인프라 격차를 고려한 거점형 육아지원 모델을 설계하고 지자체 중심의 돌봄 거버넌스 강화 방안을 도출하였습니다.', author: '이영희', views: '892', pages: '184p' },
  { cat: '과학/기술', chip: 'purple', org: '과학기술정책연구원', date: '2026.04.15', title: '디지털 전환 시대의 공공부문 R&D 투자 전략 수립 연구', excerpt: 'DX 전환 가속화에 따른 공공 R&D 우선순위 재설정과 성과지표 개선을 위한 정책 제언을 포함한 실증 연구입니다.', author: '박민준', views: '1,503', pages: '312p' },
  { cat: '행정/안전', chip: 'orange', org: '한국행정연구원', date: '2026.04.12', title: '재난 대응 역량 강화를 위한 지방자치단체 협력 체계 구축 방안', excerpt: '기후위기 및 복합재난에 대응하는 광역-기초 자치단체 간 권한 배분과 실시간 정보공유 체계를 제안합니다.', author: '최수진', views: '678', pages: '198p' }],

  eco: [], soc: [], sci: [], adm: []
};
REPORTS.eco = REPORTS.all.filter((r) => r.cat === '경제/산업');
REPORTS.soc = REPORTS.all.filter((r) => r.cat === '사회/복지');
REPORTS.sci = REPORTS.all.filter((r) => r.cat === '과학/기술');
REPORTS.adm = REPORTS.all.filter((r) => r.cat === '행정/안전');

const NOTICES = [
{ badge: 'NEW', type: 'new', title: '2026년 상반기 우수 정책연구 보고서 포상 안내', date: '2026.04.19' },
{ badge: '공지', type: '', title: '시스템 점검에 따른 서비스 일시 중단 안내 (4/27 02:00~06:00)', date: '2026.04.17' },
{ badge: '공지', type: '', title: '개인정보처리방침 변경 안내 (시행일: 2026.05.01)', date: '2026.04.12' },
{ badge: '공지', type: '', title: '정책연구 등록 시스템 매뉴얼 v2.3 배포', date: '2026.04.08' },
{ badge: '공지', type: '', title: '연구과제 성과관리 워크숍 참여 안내', date: '2026.04.03' }];


const AGENCIES = [
{ name: '산업연구원', count: '12,482', short: 'KIET' },
{ name: '한국개발연구원', count: '18,234', short: 'KDI' },
{ name: '한국행정연구원', count: '9,156', short: 'KIPA' },
{ name: '보건사회연구원', count: '11,302', short: 'KIHASA' },
{ name: '과학기술정책연구원', count: '7,889', short: 'STEPI' },
{ name: '한국교육개발원', count: '8,412', short: 'KEDI' }];


function Hero({ primary, primaryLight }) {
  const bg = {
    backgroundImage: `
      radial-gradient(ellipse at top right, ${primaryLight}55, transparent 60%),
      radial-gradient(ellipse at bottom left, #0ea5e944, transparent 60%),
      linear-gradient(135deg, ${primary} 0%, ${primary} 50%, ${primaryLight} 120%)
    `
  };
  return (
    <section className="hero" style={{ ...bg, padding: "80px 0px" }}>
      <div className="prism-container hero-inner">
        <h1 className="hero-title" style={{ fontSize: "50px" }}>
          대한민국의 미래를 설계하는<br />
          <strong style={{ fontSize: "50px" }}>데이터 기반 정책 연구</strong>
        </h1>
        <p className="hero-sub">
          우리 연구원은 학술연구를 위한 정보, 조사 분석 허브를 지향합니다.<br />
          정책연구 검색, 과제 관리, 사후 활용 실적까지 정책연구의 모든 과정을 지원합니다.
        </p>
        <div className="hero-actions">
          <a href="about-intro.html" className="hero-btn primary" style={{ fontSize: "20px" }}>연구원 소개 <i className="fas fa-arrow-right"></i></a>
          <a href="about-greeting.html" className="hero-btn ghost" style={{ fontSize: "20px" }}>인사말 보기</a>
        </div>
      </div>
    </section>);

}

function StatsStrip() {
  const projects = [
  { cat: '원가계산', client: '○○광역시', date: '진행중', title: '폐기물 처리시설 원가계산 용역', desc: '환경기초시설 위탁 원가계산 및 예정가격 산정을 위한 기초자료 수집·분석을 수행하고 있습니다.', href: 'research-cost.html' },
  { cat: '학술연구', client: '○○지자체', date: '진행중', title: '지역 ESG 정책 기본계획 수립 연구', desc: '지속가능한 지역경제 발전을 위한 ESG 정책 도입 방안과 단계적 실행 로드맵을 연구하고 있습니다.', href: 'research-academic.html' },
  { cat: '개발부담금', client: '○○공사', date: '진행중', title: '건설공사 공기연장 계약금액 조정 분석', desc: '공기 연장에 따른 간접비 산정과 계약상대자 책임한계 분석을 통해 합리적 조정 방안을 도출합니다.', href: 'research-burden.html' }];

  return (
    <section className="current-research">
      <div className="prism-container">
        <div className="section-head">
          <div>
            <h2 className="section-title"><span className="section-title-em">현재</span> 진행 중인 연구</h2>
            <p className="section-sub">산업경영환경연구원이 지금 수행하고 있는 주요 연구 과제입니다</p>
          </div>
          <a href="#" className="section-more">전체보기 <i className="fas fa-chevron-right"></i></a>
        </div>
        <div className="cr-grid">
          {projects.map((p, i) =>
          <a key={i} href={p.href} className="cr-card">
              <div className="cr-meta">
                <span className="cr-chip">{p.cat}</span>
                <span className="cr-status"><span className="dot"></span>{p.date}</span>
              </div>
              <h3 className="cr-title">{p.title}</h3>
              <p className="cr-desc">{p.desc}</p>
              <div className="cr-foot">
                <span className="cr-more">자세히 보기</span>
                <i className="fas fa-arrow-right cr-arrow"></i>
              </div>
            </a>
          )}
        </div>
      </div>
    </section>);

}

function QuickMenus() {
  return (
    <section className="quickmenu-section">
      <div className="prism-container" data-comment-anchor="3d82d96431-div-113-7">
        <div className="section-head">
          <div>
            <h2 className="section-title"><span className="section-title-em">빠른</span> 메뉴</h2>
            <p className="section-sub">자주 찾는 서비스를 한 번에 이동하세요</p>
          </div>
        </div>
        <div className="quickmenu-grid">
          {QUICK_MENUS.map((m, i) =>
          <a key={i} href={m.href} className="quickmenu-card">
              <i className="fas fa-arrow-right quickmenu-arrow"></i>
              <div className="quickmenu-num">{String(i + 1).padStart(2, '0')}</div>
              <h4>{m.label}</h4>
              <p>{m.desc}</p>
            </a>
          )}
        </div>
      </div>
    </section>);

}

function ReportList() {
  const cases = [
  { icon: 'fa-calculator', cat: '원가계산용역', title: '공공기관 위탁사업 원가계산', desc: '국가·지자체 발주 위탁사업의 예정가격 결정을 위한 원가계산 분석 보고서 작성', count: '연 200+ 건' },
  { icon: 'fa-microscope', cat: '학술연구용역', title: '정책 타당성 검토 연구', desc: '경영진단·경영계획 수립, 공공요금 산정 등 정책 의사결정을 위한 학술적 자문 제공', count: '연 80+ 건' },
  { icon: 'fa-seedling', cat: '탄소 ESG 연구', title: '탄소중립 ESG 정책 연구', desc: '기업·지자체의 탄소중립 이행 전략과 ESG 경영 도입을 위한 정책 연구', count: '연 30+ 건' },
  { icon: 'fa-file-contract', cat: '개발부담금', title: '계약금액 조정 산정', desc: '개발이익 환수, 공기연장 간접비 산정 등 객관적·합리적인 조정금액 도출', count: '연 50+ 건' }];

  return (
    <div>
      <div className="section-head">
        <div>
          <h2 className="section-title"><span className="section-title-em">주요</span> 연구분야</h2>
          <p className="section-sub">전문 연구진이 수행하는 핵심 사업 영역을 소개합니다</p>
        </div>
      </div>
      <div className="field-list">
        {cases.map((c, i) =>
        <a key={i} href="#" className="field-card">
            <div className="field-num">{String(i + 1).padStart(2, '0')}</div>
            <div className="field-body">
              <div className="field-meta">
                <span className="field-chip">{c.cat}</span>
                <span className="field-count">{c.count}</span>
              </div>
              <h3 className="field-title">{c.title}</h3>
              <p className="field-desc">{c.desc}</p>
            </div>
            <i className="fas fa-chevron-right field-arrow"></i>
          </a>
        )}
      </div>
    </div>);

}

function Sidebar() {
  return (
    <aside className="sidebar">
      <div className="prism-card">
        <div className="prism-card-head">
          <h3><i className="fas fa-bullhorn" style={{ color: 'var(--prism-primary)', marginRight: 4 }}></i>공지사항</h3>
          <a href="notice.html" className="section-more">+ 전체</a>
        </div>
        <div className="prism-card-body" style={{ paddingTop: 4, paddingBottom: 4 }}>
          <ul className="notice-list">
            {NOTICES.slice(0, 4).map((n, i) =>
            <li key={i}>
                <a href="notice.html">
                  <span className={`notice-badge ${n.type}`}>{n.badge}</span>
                  <div className="notice-content">
                    <p className="notice-title">{n.title}</p>
                    <div className="notice-date">{n.date}</div>
                  </div>
                </a>
              </li>
            )}
          </ul>
        </div>
      </div>

      <div className="contact-widget">
        <h4>이용문의</h4>
        <p className="contact-tel">031-522-6803</p>
        <p className="contact-hour">평일 09:00 ~ 18:00 (점심 12:00~13:00 제외)</p>
        <div className="contact-btns">
          <a href="notice.html" className="contact-btn"><i className="far fa-comment-dots"></i>1:1 문의</a>
        </div>
      </div>
    </aside>);

}

function AgencySection() {
  return (
    <section className="agency-section">
      <div className="prism-container">
        <div className="section-head">
          <div>
            <h2 className="section-title"><span className="section-title-em">주요</span> 연구기관</h2>
            <p className="section-sub">국책연구기관별 보유 연구과제를 확인하세요</p>
          </div>
          <a href="#" className="section-more">전체 기관 <i className="fas fa-chevron-right"></i></a>
        </div>
        <div className="agency-list">
          {AGENCIES.map((a, i) =>
          <a key={i} href="#" className="agency-card">
              <div className="agency-emblem">{a.short.slice(0, 2)}</div>
              <h5>{a.name}</h5>
              <span className="count">{a.count}건</span>
            </a>
          )}
        </div>
      </div>
    </section>);

}

function App() {
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULS);
  const [tweakOpen, setTweakOpen] = useState(false);

  useEffect(() => {
    document.documentElement.style.setProperty('--prism-primary', tweaks.primaryColor);
    document.documentElement.style.setProperty('--prism-primary-light', tweaks.primaryLight);
  }, [tweaks]);

  useEffect(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.type === '__activate_edit_mode') setTweakOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setTweakOpen(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const updateTweak = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [k]: v } }, '*');
  };

  const presets = [
  { name: '기본 블루', primary: '#1e3a8a', light: '#3b82f6' },
  { name: '에메랄드', primary: '#065f46', light: '#10b981' },
  { name: '딥 네이비', primary: '#0f172a', light: '#1e40af' },
  { name: '버건디', primary: '#7f1d1d', light: '#dc2626' },
  { name: '인디고', primary: '#3730a3', light: '#6366f1' }];


  return (
    <>
      <Header active={null} />
      <Hero primary={tweaks.primaryColor} primaryLight={tweaks.primaryLight} />
      <StatsStrip />
      <QuickMenus />
      <div className="prism-container">
        <div className="main-grid">
          <ReportList />
          <Sidebar />
        </div>
      </div>
      <Footer />

      {tweakOpen &&
      <div style={{
        position: 'fixed', bottom: 20, right: 20, width: 300,
        background: 'white', border: '1px solid #e5e7eb', borderRadius: 10,
        boxShadow: '0 20px 40px rgba(0,0,0,0.15)', zIndex: 9999, padding: 18,
        fontFamily: 'Noto Sans KR, sans-serif'
      }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <strong style={{ fontSize: 14 }}>Tweaks</strong>
            <button onClick={() => {
            setTweakOpen(false);
            window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
          }} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 16 }}>×</button>
          </div>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#6b7280', marginBottom: 8 }}>메인 컬러 프리셋</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 6, marginBottom: 14 }}>
            {presets.map((p) =>
          <button key={p.name} title={p.name} onClick={() => {
            updateTweak('primaryColor', p.primary);
            updateTweak('primaryLight', p.light);
          }} style={{
            height: 40, border: tweaks.primaryColor === p.primary ? '2px solid #111' : '1px solid #e5e7eb',
            borderRadius: 6, cursor: 'pointer',
            background: `linear-gradient(135deg, ${p.primary}, ${p.light})`
          }} />
          )}
          </div>
          <div style={{ fontSize: 12, fontWeight: 600, color: '#6b7280', marginBottom: 6 }}>Primary</div>
          <input type="color" value={tweaks.primaryColor} onChange={(e) => updateTweak('primaryColor', e.target.value)} style={{ width: '100%', height: 36, border: '1px solid #e5e7eb', borderRadius: 4, cursor: 'pointer' }} />
          <div style={{ fontSize: 12, fontWeight: 600, color: '#6b7280', marginTop: 10, marginBottom: 6 }}>Primary Light</div>
          <input type="color" value={tweaks.primaryLight} onChange={(e) => updateTweak('primaryLight', e.target.value)} style={{ width: '100%', height: 36, border: '1px solid #e5e7eb', borderRadius: 4, cursor: 'pointer' }} />
        </div>
      }
    </>);

}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);