/**
 * HTML 기반 스토리보드 PPTX 생성기
 * HTML 템플릿을 먼저 생성한 후 PPTX로 변환하는 방식
 *
 * 사용법:
 *   node generate-html-storyboard.js --config <설정파일.json> --output <출력폴더>
 */

const fs = require('fs');
const path = require('path');

// 색상 정의
const colors = {
    primary: '#0d9488',
    secondary: '#1e293b',
    accent: '#95C11F',
    warning: '#f59e0b',
    danger: '#dc2626',
    white: '#ffffff',
    lightGray: '#f1f5f9',
    darkGray: '#64748b',
    black: '#1a1a1a',
    wireframeBg: '#f8fafc',
    wireframeBorder: '#e2e8f0',
    tableBorder: '#334155'
};

// HTML 이스케이프
function escapeHtml(text) {
    if (!text) return '';
    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// 공통 스타일
const commonStyles = `
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
        width: 720pt;
        height: 405pt;
        font-family: 'Pretendard', 'Malgun Gothic', sans-serif;
        background: #ffffff;
    }
    p, h1, h2, h3 { margin: 0; }
`;

// ========================================
// 슬라이드 생성 함수들
// ========================================

function generateCoverSlide(config) {
    return `<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
    <style>
        ${commonStyles}
        body {
            background: ${colors.secondary};
            display: flex;
            flex-direction: column;
            padding: 30pt;
        }
        .accent-line {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6pt;
            background: ${colors.primary};
        }
        .logo {
            width: 80pt;
            height: 32pt;
            background: ${colors.primary};
            border-radius: 4pt;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .logo p {
            font-size: 14pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .title-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 100%;
            text-align: center;
            overflow: visible;
        }
        .main-title {
            font-size: 32pt;
            font-weight: 700;
            color: ${colors.white};
            margin-bottom: 12pt;
            white-space: nowrap;
            width: 100%;
            text-align: center;
        }
        .sub-title {
            font-size: 16pt;
            color: ${colors.primary};
            white-space: nowrap;
            width: 100%;
            text-align: center;
        }
        .version {
            font-size: 10pt;
            color: ${colors.darkGray};
            margin-top: 16pt;
            white-space: nowrap;
            width: 100%;
            text-align: center;
        }
        .footer {
            text-align: center;
        }
        .footer p {
            font-size: 9pt;
            color: ${colors.darkGray};
        }
    </style>
</head>
<body>
    <div class="accent-line"></div>
    <div class="logo">
        <p>${escapeHtml(config.company || 'SAM')}</p>
    </div>
    <div class="title-area">
        <p class="main-title">${escapeHtml(config.projectName || '프로젝트')}</p>
        <p class="sub-title">웹 기획서 및 스토리보드</p>
        <p class="version">Version D1.0</p>
    </div>
    <div class="footer">
        <p>${escapeHtml(config.date || '')} | ${escapeHtml(config.author || '기획팀')}</p>
    </div>
</body>
</html>`;
}

function generateHistorySlide(config) {
    return `<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
    <style>
        ${commonStyles}
        .header {
            background: ${colors.secondary};
            padding: 12pt 20pt;
        }
        .header p {
            font-size: 16pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .content {
            padding: 20pt;
        }
        .table {
            width: 100%;
            border: 0.5pt solid ${colors.darkGray};
        }
        .table-header {
            display: flex;
            background: ${colors.lightGray};
            border-bottom: 0.5pt solid ${colors.darkGray};
        }
        .table-row {
            display: flex;
            border-bottom: 0.5pt solid ${colors.darkGray};
        }
        .table-row:last-child {
            border-bottom: none;
        }
        .table-cell {
            padding: 8pt;
            border-right: 0.5pt solid ${colors.darkGray};
            display: flex;
            align-items: center;
        }
        .table-cell:last-child {
            border-right: none;
        }
        .table-cell p {
            font-size: 8pt;
            color: ${colors.secondary};
            white-space: nowrap;
        }
        .col-date { width: 80pt; }
        .col-ver { width: 50pt; }
        .col-main { width: 100pt; }
        .col-detail { flex: 1; }
        .col-note { width: 80pt; }
    </style>
</head>
<body>
    <div class="header">
        <p>Document History</p>
    </div>
    <div class="content">
        <div class="table">
            <div class="table-header">
                <div class="table-cell col-date"><p>날짜</p></div>
                <div class="table-cell col-ver"><p>버전</p></div>
                <div class="table-cell col-main"><p>주요 내용</p></div>
                <div class="table-cell col-detail"><p>상세 내용</p></div>
                <div class="table-cell col-note"><p>비고</p></div>
            </div>
            <div class="table-row">
                <div class="table-cell col-date"><p>${escapeHtml(config.date || '')}</p></div>
                <div class="table-cell col-ver"><p>D1.0</p></div>
                <div class="table-cell col-main"><p>초안 작성</p></div>
                <div class="table-cell col-detail"><p>${escapeHtml(config.projectName || '')} 기획서 초안 작성</p></div>
                <div class="table-cell col-note"><p></p></div>
            </div>
            <div class="table-row">
                <div class="table-cell col-date"><p></p></div>
                <div class="table-cell col-ver"><p></p></div>
                <div class="table-cell col-main"><p></p></div>
                <div class="table-cell col-detail"><p></p></div>
                <div class="table-cell col-note"><p></p></div>
            </div>
        </div>
    </div>
</body>
</html>`;
}

function generateTOCSlide(config) {
    const tocItems = config.tocItems || [];
    const itemsHtml = tocItems.map((item, idx) => `
        <div class="toc-item">
            <div class="toc-number">
                <p>${escapeHtml(item.num || String(idx + 1).padStart(2, '0'))}</p>
            </div>
            <div class="toc-title">
                <p>${escapeHtml(item.title)}</p>
            </div>
            <div class="toc-desc">
                <p>${escapeHtml(item.desc || '')}</p>
            </div>
        </div>
    `).join('');

    return `<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
    <style>
        ${commonStyles}
        .header {
            background: ${colors.secondary};
            padding: 12pt 20pt;
        }
        .header p {
            font-size: 16pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .content {
            padding: 20pt 40pt;
        }
        .toc-item {
            display: flex;
            align-items: center;
            margin-bottom: 16pt;
        }
        .toc-number {
            width: 36pt;
            height: 28pt;
            background: ${colors.primary};
            border-radius: 4pt;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 16pt;
        }
        .toc-number p {
            font-size: 12pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .toc-title {
            width: 180pt;
        }
        .toc-title p {
            font-size: 12pt;
            font-weight: 600;
            color: ${colors.secondary};
        }
        .toc-desc p {
            font-size: 9pt;
            color: ${colors.darkGray};
        }
    </style>
</head>
<body>
    <div class="header">
        <p>목차 (Table of Contents)</p>
    </div>
    <div class="content">
        ${itemsHtml}
    </div>
</body>
</html>`;
}

function generateOverviewSlide(config) {
    const features = config.features || [];
    const effects = config.effects || [];

    const featuresHtml = features.slice(0, 6).map(f => `
        <div class="feature-item">
            <p>✓ ${escapeHtml(f)}</p>
        </div>
    `).join('');

    const effectsHtml = effects.slice(0, 3).map(e => `
        <div class="effect-card">
            <p class="effect-icon">${escapeHtml(e.icon || '📌')}</p>
            <p class="effect-title">${escapeHtml(e.title)}</p>
            <p class="effect-desc">${escapeHtml(e.desc)}</p>
        </div>
    `).join('');

    return `<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
    <style>
        ${commonStyles}
        .header {
            background: ${colors.secondary};
            padding: 12pt 20pt;
        }
        .header p {
            font-size: 16pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .content {
            padding: 16pt 20pt;
            display: flex;
            flex-direction: column;
            gap: 12pt;
        }
        .row {
            display: flex;
            gap: 16pt;
        }
        .section {
            flex: 1;
        }
        .section-title {
            font-size: 11pt;
            font-weight: 700;
            color: ${colors.secondary};
            margin-bottom: 8pt;
        }
        .purpose-box {
            background: ${colors.lightGray};
            padding: 12pt;
            border-radius: 4pt;
            min-height: 80pt;
        }
        .purpose-box p {
            font-size: 9pt;
            color: ${colors.secondary};
            line-height: 1.5;
        }
        .feature-item {
            margin-bottom: 4pt;
        }
        .feature-item p {
            font-size: 8pt;
            color: ${colors.secondary};
        }
        .effects-row {
            display: flex;
            gap: 12pt;
        }
        .effect-card {
            flex: 1;
            background: ${colors.lightGray};
            border: 1pt solid ${colors.primary};
            border-radius: 4pt;
            padding: 10pt;
            text-align: center;
        }
        .effect-icon {
            font-size: 20pt;
            margin-bottom: 4pt;
        }
        .effect-title {
            font-size: 9pt;
            font-weight: 700;
            color: ${colors.secondary};
            margin-bottom: 4pt;
        }
        .effect-desc {
            font-size: 7pt;
            color: ${colors.darkGray};
        }
    </style>
</head>
<body>
    <div class="header">
        <p>01. 프로젝트 개요</p>
    </div>
    <div class="content">
        <div class="row">
            <div class="section">
                <p class="section-title">프로젝트 목적</p>
                <div class="purpose-box">
                    <p>${escapeHtml(config.purpose || '업무 프로세스를 시스템화하여 효율성 향상')}</p>
                </div>
            </div>
            <div class="section">
                <p class="section-title">주요 기능</p>
                ${featuresHtml}
            </div>
        </div>
        <div>
            <p class="section-title">기대 효과</p>
            <div class="effects-row">
                ${effectsHtml}
            </div>
        </div>
    </div>
</body>
</html>`;
}

function generateIASlide(config) {
    const menus = config.mainMenus || [];

    const menusHtml = menus.slice(0, 4).map((menu, idx) => `
        <div class="menu-column">
            <div class="menu-main">
                <p>${escapeHtml(menu.title)}</p>
            </div>
            ${(menu.children || []).slice(0, 3).map(child => `
                <div class="menu-sub">
                    <p>${escapeHtml(child)}</p>
                </div>
            `).join('')}
        </div>
    `).join('');

    const rootName = config.projectName ?
        config.projectName.replace(/시스템|프로젝트|기획/g, '').trim() :
        '시스템';

    return `<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
    <style>
        ${commonStyles}
        .header {
            background: ${colors.secondary};
            padding: 12pt 20pt;
        }
        .header p {
            font-size: 16pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .content {
            padding: 20pt;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .root-node {
            background: ${colors.secondary};
            padding: 10pt 24pt;
            border-radius: 4pt;
            margin-bottom: 12pt;
        }
        .root-node p {
            font-size: 10pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .connector-v {
            width: 1pt;
            height: 16pt;
            background: ${colors.darkGray};
        }
        .connector-h {
            height: 1pt;
            background: ${colors.darkGray};
            width: 500pt;
            margin-bottom: 12pt;
        }
        .menus-row {
            display: flex;
            gap: 12pt;
            justify-content: center;
        }
        .menu-column {
            width: 130pt;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .menu-main {
            background: ${colors.primary};
            padding: 8pt 12pt;
            border-radius: 4pt;
            width: 100%;
            text-align: center;
            margin-bottom: 8pt;
        }
        .menu-main p {
            font-size: 9pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .menu-sub {
            background: ${colors.lightGray};
            border: 0.5pt solid ${colors.wireframeBorder};
            padding: 6pt 8pt;
            border-radius: 2pt;
            width: 100%;
            text-align: center;
            margin-bottom: 4pt;
        }
        .menu-sub p {
            font-size: 7pt;
            color: ${colors.secondary};
        }
    </style>
</head>
<body>
    <div class="header">
        <p>02. 메뉴 구조 (Information Architecture)</p>
    </div>
    <div class="content">
        <div class="root-node">
            <p>${escapeHtml(rootName)}</p>
        </div>
        <div class="connector-v"></div>
        <div class="connector-h"></div>
        <div class="menus-row">
            ${menusHtml}
        </div>
    </div>
</body>
</html>`;
}

function generateStoryboardSlide(screen, pageNum, config) {
    const menuItems = config.mainMenus || [];
    const activeMenu = screen.taskName || '';

    // 사이드바는 항상 mainMenus 기반으로 별도 렌더링 (wireframeElements 유무와 관계없이)
    const sidebarHtml = menuItems.slice(0, 4).map(menu => {
        const isActive = menu.title === activeMenu;
        return `
            <div class="sidebar-item ${isActive ? 'active' : ''}">
                <p>${escapeHtml(menu.title)}</p>
            </div>
        `;
    }).join('');

    const descriptions = screen.descriptions || [];
    const descriptionsHtml = descriptions.slice(0, 4).map((desc, idx) => `
        <div class="description-item">
            <div class="description-item-header">
                <div class="description-number">
                    <p>${idx + 1}</p>
                </div>
                <div class="description-title">
                    <p>${escapeHtml(desc.title)}</p>
                </div>
            </div>
            <div class="description-content">
                <p>${escapeHtml(desc.content)}</p>
            </div>
        </div>
    `).join('');

    // wireframeElements가 있으면 사이드바 영역 요소 제외하고 콘텐츠만 렌더링
    const hasWireframeElements = screen.wireframeElements && screen.wireframeElements.length > 0;

    // 화면별 콘텐츠 생성
    let contentHtml = '';

    if (hasWireframeElements) {
        // 사이드바 영역(x < 1.5)을 제외한 콘텐츠 요소만 필터링
        contentHtml = generateWireframeContent(screen, config, true);
    } else if (screen.contentType === 'form') {
        contentHtml = generateFormContent(screen);
    } else if (screen.contentType === 'table') {
        contentHtml = generateTableContent(screen);
    } else if (screen.contentType === 'cards') {
        contentHtml = generateCardsContent(screen);
    } else {
        contentHtml = generateDefaultContent(screen);
    }

    return `<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/static/pretendard.min.css">
    <style>
        ${commonStyles}

        /* Header Table */
        .header-table {
            display: flex;
            flex-direction: column;
            border: 0.5pt solid ${colors.darkGray};
            margin: 4pt 8pt;
        }
        .header-row {
            display: flex;
            border-bottom: 0.5pt solid ${colors.darkGray};
        }
        .header-row:last-child {
            border-bottom: none;
        }
        .header-cell {
            display: flex;
            align-items: center;
            justify-content: center;
            border-right: 0.5pt solid ${colors.darkGray};
            background: ${colors.lightGray};
            padding: 4pt 6pt;
            height: 18pt;
        }
        .header-cell:last-child { border-right: none; }
        .header-cell.label {
            width: 55pt;
            background: #e2e8f0;
        }
        .header-cell.value { flex: 1; }
        .header-cell.small { width: 45pt; }
        .header-cell.medium { width: 70pt; }
        .header-cell p {
            font-size: 6pt;
            color: ${colors.secondary};
            white-space: nowrap;
        }

        /* Main Content */
        .main-content {
            display: flex;
            flex: 1;
            padding: 0 8pt 8pt 8pt;
            gap: 8pt;
        }

        /* Wireframe Area */
        .wireframe-area {
            flex: 1;
            background: ${colors.wireframeBg};
            border: 0.5pt solid ${colors.wireframeBorder};
            border-radius: 2pt;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }
        .wireframe-header {
            background: ${colors.secondary};
            padding: 5pt 10pt;
        }
        .wireframe-header p {
            font-size: 8pt;
            font-weight: 600;
            color: ${colors.white};
        }
        .wireframe-body {
            flex: 1;
            display: flex;
            padding: 8pt;
            gap: 8pt;
        }

        /* Sidebar */
        .sidebar {
            width: 65pt;
            background: ${colors.lightGray};
            border-radius: 2pt;
            padding: 5pt;
        }
        .sidebar-item {
            padding: 4pt 5pt;
            margin-bottom: 2pt;
            border-radius: 2pt;
            background: ${colors.white};
        }
        .sidebar-item.active {
            background: ${colors.primary};
        }
        .sidebar-item p {
            font-size: 5pt;
            color: ${colors.secondary};
        }
        .sidebar-item.active p {
            color: ${colors.white};
            font-weight: 600;
        }

        /* Content Area */
        .content-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 6pt;
        }
        .section-title p {
            font-size: 8pt;
            font-weight: 700;
            color: ${colors.secondary};
        }

        /* Cards */
        .cards-row {
            display: flex;
            gap: 6pt;
        }
        .card {
            flex: 1;
            background: ${colors.lightGray};
            border: 0.5pt solid ${colors.wireframeBorder};
            border-radius: 2pt;
            overflow: hidden;
        }
        .card.selected {
            border-color: ${colors.primary};
            border-width: 1pt;
        }
        .card-header {
            background: ${colors.secondary};
            padding: 3pt 5pt;
        }
        .card-header.primary {
            background: ${colors.primary};
        }
        .card-header p {
            font-size: 5pt;
            color: ${colors.white};
            font-weight: 600;
        }
        .card-body {
            padding: 5pt;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 25pt;
        }
        .card-body p {
            font-size: 7pt;
            color: ${colors.secondary};
            font-weight: 600;
        }

        /* Data Table */
        .data-table {
            background: ${colors.secondary};
            border-radius: 2pt;
            overflow: hidden;
        }
        .table-row {
            display: flex;
            border-bottom: 0.5pt solid ${colors.tableBorder};
        }
        .table-row:last-child { border-bottom: none; }
        .table-cell {
            flex: 1;
            padding: 4pt 8pt;
            display: flex;
            align-items: center;
        }
        .table-cell.label { flex: 0 0 100pt; }
        .table-cell p {
            font-size: 6pt;
            color: #94a3b8;
        }
        .table-cell.value p { color: ${colors.white}; }
        .table-cell.highlight p {
            font-size: 10pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .table-cell.accent p {
            color: ${colors.primary};
            font-weight: 600;
        }

        /* Warning Box */
        .warning-box {
            background: ${colors.danger};
            border-radius: 2pt;
            padding: 4pt 6pt;
        }
        .warning-box p {
            font-size: 5pt;
            color: ${colors.white};
        }

        /* Button */
        .button {
            background: ${colors.primary};
            border-radius: 2pt;
            padding: 5pt 12pt;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        .button p {
            font-size: 7pt;
            color: ${colors.white};
            font-weight: 600;
        }

        /* Description Panel - 흰색 배경, 투명한 항목 */
        .description-panel {
            width: 145pt;
            background: ${colors.white};
            border: 0.5pt solid ${colors.wireframeBorder};
            border-radius: 2pt;
            padding: 8pt;
            display: flex;
            flex-direction: column;
        }
        .description-header {
            background: ${colors.accent};
            padding: 4pt 8pt;
            border-radius: 2pt;
            margin-bottom: 10pt;
        }
        .description-header p {
            font-size: 7pt;
            font-weight: 600;
            color: ${colors.white};
            text-align: center;
        }
        .description-item {
            margin-bottom: 10pt;
            /* 배경 없음 - 투명 */
        }
        .description-item-header {
            display: flex;
            align-items: center;
            gap: 5pt;
            margin-bottom: 3pt;
        }
        .description-number {
            width: 14pt;
            height: 14pt;
            background: ${colors.danger};
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        .description-number p {
            font-size: 6pt;
            font-weight: 700;
            color: ${colors.white};
        }
        .description-title p {
            font-size: 6pt;
            font-weight: 700;
            color: ${colors.secondary};
        }
        .description-content {
            padding-left: 17pt;
        }
        .description-content p {
            font-size: 5pt;
            color: ${colors.darkGray};
            line-height: 1.4;
        }
    </style>
</head>
<body>
    <!-- Header Table -->
    <div class="header-table">
        <div class="header-row">
            <div class="header-cell label"><p>Task Name</p></div>
            <div class="header-cell value"><p>${escapeHtml(screen.taskName || '')}</p></div>
            <div class="header-cell label"><p>Ver.</p></div>
            <div class="header-cell small"><p>D1.0</p></div>
            <div class="header-cell label"><p>Page</p></div>
            <div class="header-cell small"><p>${pageNum}</p></div>
        </div>
        <div class="header-row">
            <div class="header-cell label"><p>Route</p></div>
            <div class="header-cell value"><p>${escapeHtml(screen.route || '')}</p></div>
            <div class="header-cell label"><p>Screen Name</p></div>
            <div class="header-cell value"><p>${escapeHtml(screen.screenName || '')}</p></div>
            <div class="header-cell label"><p>Screen ID</p></div>
            <div class="header-cell medium"><p>${escapeHtml(screen.screenId || '')}</p></div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Wireframe Area -->
        <div class="wireframe-area">
            <div class="wireframe-header">
                <p>${escapeHtml(config.projectName || '시스템')}</p>
            </div>
            <div class="wireframe-body">
                <div class="sidebar">
                    ${sidebarHtml}
                </div>
                <div class="content-area">
                    ${contentHtml}
                </div>
            </div>
        </div>

        <!-- Description Panel -->
        <div class="description-panel">
            <div class="description-header">
                <p>Description</p>
            </div>
            ${descriptionsHtml}
        </div>
    </div>
</body>
</html>`;
}

// 콘텐츠 타입별 생성 함수
function generateDefaultContent(screen) {
    return `
        <div class="section-title"><p>${escapeHtml(screen.screenName || '화면')}</p></div>
        <div style="flex: 1; background: ${colors.white}; border: 0.5pt dashed ${colors.wireframeBorder}; border-radius: 2pt; display: flex; align-items: center; justify-content: center;">
            <p style="font-size: 8pt; color: ${colors.darkGray};">콘텐츠 영역</p>
        </div>
    `;
}

function generateFormContent(screen) {
    const fields = screen.fields || [];
    const fieldsHtml = fields.map(f => `
        <div style="display: flex; gap: 8pt; margin-bottom: 4pt;">
            <div style="width: 60pt; background: ${colors.lightGray}; padding: 3pt 6pt; border-radius: 2pt;">
                <p style="font-size: 6pt; color: ${colors.secondary};">${escapeHtml(f.label)}</p>
            </div>
            <div style="flex: 1; background: ${colors.white}; border: 0.5pt solid ${colors.wireframeBorder}; padding: 3pt 6pt; border-radius: 2pt;">
                <p style="font-size: 6pt; color: ${colors.secondary};">${escapeHtml(f.value || '')}</p>
            </div>
        </div>
    `).join('');

    return `
        <div class="section-title"><p>${escapeHtml(screen.screenName || '입력 폼')}</p></div>
        ${fieldsHtml}
    `;
}

function generateTableContent(screen) {
    const rows = screen.tableRows || [];
    const rowsHtml = rows.map(r => `
        <div class="table-row">
            <div class="table-cell label"><p>${escapeHtml(r.label)}</p></div>
            <div class="table-cell value ${r.highlight ? 'highlight' : ''} ${r.accent ? 'accent' : ''}">
                <p>${escapeHtml(r.value)}</p>
            </div>
        </div>
    `).join('');

    return `
        <div class="section-title"><p>${escapeHtml(screen.screenName || '테이블')}</p></div>
        <div class="data-table">
            ${rowsHtml}
        </div>
    `;
}

function generateCardsContent(screen) {
    const cards = screen.cards || [];
    const cardsHtml = cards.map(c => `
        <div class="card ${c.selected ? 'selected' : ''}">
            <div class="card-header ${c.primary ? 'primary' : ''}">
                <p>${escapeHtml(c.title)}</p>
            </div>
            <div class="card-body">
                <p>${escapeHtml(c.value)}</p>
            </div>
        </div>
    `).join('');

    return `
        <div class="section-title"><p>${escapeHtml(screen.screenName || '선택')}</p></div>
        <div class="cards-row">
            ${cardsHtml}
        </div>
    `;
}

// wireframeElements 기반 콘텐츠 생성
// excludeSidebar: true면 사이드바 영역(x < 1.5) 요소 제외
function generateWireframeContent(screen, config, excludeSidebar = false) {
    let elements = screen.wireframeElements || [];
    const descriptions = screen.descriptions || [];

    // 사이드바 영역 제외 옵션
    if (excludeSidebar) {
        // x < 1.5인 요소들은 사이드바 영역이므로 제외
        elements = elements.filter(el => el.x >= 1.5);
    }

    // content-area 내에서의 상대 좌표 계산
    // 사이드바 제외 시: x가 1.5부터 시작하므로 baseX를 1.5로 조정
    const baseX = excludeSidebar ? 1.5 : 0.2;
    const baseY = 1.25;  // 헤더 테이블 아래
    const scaleX = 52;   // pt per inch (영역에 맞게 조정)
    const scaleY = 52;

    const elementsHtml = elements.map(el => {
        const left = (el.x - baseX) * scaleX;
        const top = (el.y - baseY) * scaleY;
        const width = el.w * scaleX;
        const height = el.h * scaleY;

        const bgColor = el.fill ? `#${el.fill}` : 'transparent';
        const textColor = el.color ? `#${el.color}` : colors.secondary;
        const fontSize = el.fontSize || 8;
        const fontWeight = el.bold ? '700' : '400';
        const textAlign = el.align || 'center';

        // 텍스트에 줄바꿈 처리
        const textContent = el.text ? el.text.replace(/\n/g, '<br>') : '';

        return `
            <div style="
                position: absolute;
                left: ${left}pt;
                top: ${top}pt;
                width: ${width}pt;
                height: ${height}pt;
                background: ${bgColor};
                border-radius: 2pt;
                display: flex;
                align-items: center;
                justify-content: ${textAlign === 'left' ? 'flex-start' : textAlign === 'right' ? 'flex-end' : 'center'};
                padding: 2pt 4pt;
                box-sizing: border-box;
            ">
                <p style="
                    font-size: ${fontSize * 0.7}pt;
                    color: ${textColor};
                    font-weight: ${fontWeight};
                    text-align: ${textAlign};
                    line-height: 1.3;
                    margin: 0;
                ">${textContent}</p>
            </div>
        `;
    }).join('');

    // Description 마커 생성 (빨간 번호)
    // descriptions에 markerX, markerY가 있으면 해당 위치에 마커 표시
    const markersHtml = descriptions.map((desc, idx) => {
        // 마커 위치가 지정되어 있으면 사용, 없으면 기본 위치 계산
        let markerX, markerY;

        if (desc.markerX !== undefined && desc.markerY !== undefined) {
            // 명시적으로 지정된 마커 위치 사용
            markerX = (desc.markerX - baseX) * scaleX;
            markerY = (desc.markerY - baseY) * scaleY;
        } else {
            // 기본 위치: 콘텐츠 영역 좌측에 세로로 배치
            markerX = 5 + idx * 0;  // 고정 x 위치
            markerY = 10 + idx * 55; // 세로로 간격
        }

        return `
            <div style="
                position: absolute;
                left: ${markerX}pt;
                top: ${markerY}pt;
                width: 14pt;
                height: 14pt;
                background: ${colors.danger};
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 100;
                box-shadow: 0 1pt 3pt rgba(0,0,0,0.3);
            ">
                <p style="
                    font-size: 7pt;
                    font-weight: 700;
                    color: white;
                    margin: 0;
                ">${idx + 1}</p>
            </div>
        `;
    }).join('');

    return `
        <div style="position: relative; flex: 1; min-height: 200pt;">
            ${elementsHtml}
            ${markersHtml}
        </div>
    `;
}

// ========================================
// 메인 실행
// ========================================

async function main() {
    const args = process.argv.slice(2);
    let configFile = null;
    let outputDir = null;

    for (let i = 0; i < args.length; i++) {
        if (args[i] === '--config' && args[i + 1]) {
            configFile = args[i + 1];
            i++;
        } else if (args[i] === '--output' && args[i + 1]) {
            outputDir = args[i + 1];
            i++;
        }
    }

    if (!configFile) {
        console.error('Usage: node generate-html-storyboard.js --config <config.json> --output <output_dir>');
        process.exit(1);
    }

    const config = JSON.parse(fs.readFileSync(configFile, 'utf-8'));
    outputDir = outputDir || path.join(path.dirname(configFile), 'html_slides');

    if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, { recursive: true });
    }

    console.log('🚀 HTML 스토리보드 생성 시작\n');

    // 슬라이드 생성
    const slides = [];

    // 1. 표지
    slides.push({ name: 'slide_01_cover.html', content: generateCoverSlide(config) });
    console.log('✅ 슬라이드 1: 표지 생성 완료');

    // 2. Document History
    slides.push({ name: 'slide_02_history.html', content: generateHistorySlide(config) });
    console.log('✅ 슬라이드 2: Document History 생성 완료');

    // 3. 목차
    slides.push({ name: 'slide_03_toc.html', content: generateTOCSlide(config) });
    console.log('✅ 슬라이드 3: 목차 생성 완료');

    // 4. 프로젝트 개요
    slides.push({ name: 'slide_04_overview.html', content: generateOverviewSlide(config) });
    console.log('✅ 슬라이드 4: 프로젝트 개요 생성 완료');

    // 5. IA
    slides.push({ name: 'slide_05_ia.html', content: generateIASlide(config) });
    console.log('✅ 슬라이드 5: 메뉴 구조 (IA) 생성 완료');

    // 6+. 스토리보드
    const screens = config.screens || [];
    screens.forEach((screen, idx) => {
        const pageNum = idx + 6;
        slides.push({
            name: `slide_${String(pageNum).padStart(2, '0')}_${screen.screenId || 'screen'}.html`,
            content: generateStoryboardSlide(screen, pageNum, config)
        });
        console.log(`✅ 슬라이드 ${pageNum}: ${screen.screenName} 생성 완료`);
    });

    // HTML 파일 저장
    for (const slide of slides) {
        const filePath = path.join(outputDir, slide.name);
        fs.writeFileSync(filePath, slide.content, 'utf-8');
    }

    console.log(`\n🎉 HTML 슬라이드 생성 완료!`);
    console.log(`📁 저장 위치: ${outputDir}`);
    console.log(`📊 총 슬라이드: ${slides.length}장`);
    console.log(`\n다음 단계: html2pptx.js로 PPTX 변환`);
}

main().catch(console.error);
