"""HTML Report Generator - Full Money Forward Style"""
from pathlib import Path
from datetime import datetime
from typing import Optional
import json

from ..data_models import FinancialReport, PLItem, KPICard
from ..pdf.styles import format_currency


class HTMLReportGenerator:
    """HTML Report Generator with Chart.js, Google Fonts, and AI Analysis"""

    def __init__(
        self,
        output_path: Path,
        report_data: FinancialReport,
        use_ai: bool = True
    ):
        self.output_path = Path(output_path)
        self.data = report_data
        self.use_ai = use_ai
        self.ai_summary = None
        self.ai_variance = None
        self.ai_highlights = None

    def generate(self) -> Path:
        """Generate HTML report"""
        # Generate AI content if enabled
        if self.use_ai:
            self._generate_ai_content()

        html_content = self._build_html()

        self.output_path.parent.mkdir(parents=True, exist_ok=True)
        self.output_path.write_text(html_content, encoding='utf-8')

        return self.output_path

    def _generate_ai_content(self):
        """Generate AI-powered content"""
        try:
            from ..ai_client import get_gemini_client
            client = get_gemini_client()

            print("    Generating AI summary...")
            self.ai_summary = self._clean_ai_response(
                client.generate_financial_summary(self.data)
            )

            print("    Generating AI variance analysis...")
            self.ai_variance = self._clean_ai_response(
                client.generate_variance_analysis(self.data)
            )

            print("    Generating AI financial highlights...")
            self.ai_highlights = client.generate_financial_highlights(self.data)

        except Exception as e:
            print(f"    AI generation failed: {e}")
            self.ai_summary = None
            self.ai_variance = None
            self.ai_highlights = None

    def _clean_ai_response(self, response: str) -> str:
        """Clean AI response by removing markdown code blocks"""
        if not response:
            return response
        # Remove markdown code block wrappers
        import re
        # Remove ```html and ``` wrappers
        cleaned = re.sub(r'```html\s*', '', response)
        cleaned = re.sub(r'```\s*', '', cleaned)
        return cleaned.strip()

    def _build_html(self) -> str:
        """Build complete HTML document"""
        return f"""<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{self.data.company_name} - {self.data.fiscal_year} Financial Report</title>

    <!-- Google Fonts - Noto Sans JP -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700&display=swap" rel="stylesheet">

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <style>
        {self._get_styles()}
    </style>
</head>
<body>
    <div class="container">
        {self._build_header()}

        <!-- Navigation -->
        <nav class="nav-tabs">
            <a href="#dashboard" class="nav-tab active">業績見通し</a>
            <a href="#summary" class="nav-tab">サマリ</a>
            <a href="#pl-table" class="nav-tab">損益計算書</a>
            <a href="#analysis" class="nav-tab">業績分析表</a>
            <a href="#highlights" class="nav-tab">財務ハイライト</a>
        </nav>

        <!-- Page 1: Dashboard -->
        <section id="dashboard" class="page">
            {self._build_dashboard_page()}
        </section>

        <!-- Page 2: Summary (AI Generated) -->
        <section id="summary" class="page">
            {self._build_summary_page()}
        </section>

        <!-- Page 3: P/L Table -->
        <section id="pl-table" class="page">
            {self._build_pl_table_page()}
        </section>

        <!-- Page 4: Performance Analysis -->
        <section id="analysis" class="page">
            {self._build_analysis_page()}
        </section>

        <!-- Page 5: Financial Highlights -->
        <section id="highlights" class="page">
            {self._build_highlights_page()}
        </section>

        {self._build_footer()}
    </div>

    <script>
        {self._build_chart_scripts()}
        {self._build_nav_scripts()}
    </script>
</body>
</html>"""

    def _get_styles(self) -> str:
        """CSS styles"""
        return """
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Noto Sans JP', sans-serif;
            background-color: #f8fafc;
            color: #334155;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        /* Header */
        .header {
            background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
            color: white;
            padding: 40px;
            border-radius: 16px;
            margin-bottom: 24px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .header .subtitle {
            font-size: 16px;
            opacity: 0.9;
        }

        .header .period {
            font-size: 14px;
            opacity: 0.8;
            margin-top: 12px;
        }

        /* Navigation */
        .nav-tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 24px;
            background: white;
            padding: 8px;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            flex-wrap: wrap;
        }

        .nav-tab {
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            transition: all 0.2s;
        }

        .nav-tab:hover {
            background: #f1f5f9;
            color: #334155;
        }

        .nav-tab.active {
            background: #2563eb;
            color: white;
        }

        /* Page sections */
        .page {
            display: none;
        }

        .page.active {
            display: block;
        }

        /* Section */
        .section {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 24px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .section-title {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 24px;
            padding-bottom: 12px;
            border-bottom: 2px solid #e2e8f0;
        }

        .section-subtitle {
            font-size: 16px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 16px;
        }

        /* Two column layout */
        .two-columns {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }

        /* KPI Cards */
        .kpi-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 16px;
        }

        .kpi-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            border-left: 4px solid;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .kpi-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .kpi-card.blue { border-left-color: #2563eb; }
        .kpi-card.green { border-left-color: #16a34a; }
        .kpi-card.red { border-left-color: #dc2626; }
        .kpi-card.purple { border-left-color: #8b5cf6; }
        .kpi-card.cyan { border-left-color: #0891b2; }
        .kpi-card.orange { border-left-color: #f59e0b; }

        .kpi-label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 4px;
        }

        .kpi-title {
            font-size: 13px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .kpi-value {
            font-size: 24px;
            font-weight: 700;
            color: #1e293b;
        }

        .kpi-value.negative {
            color: #dc2626;
        }

        .kpi-variance {
            font-size: 13px;
            margin-top: 8px;
            padding: 4px 8px;
            border-radius: 4px;
            display: inline-block;
        }

        .kpi-variance.positive {
            background: #dcfce7;
            color: #16a34a;
        }

        .kpi-variance.negative {
            background: #fee2e2;
            color: #dc2626;
        }

        .kpi-target {
            font-size: 11px;
            color: #94a3b8;
            margin-top: 4px;
        }

        /* Charts */
        .chart-container {
            background: #f8fafc;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
        }

        .chart-title {
            font-size: 14px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 16px;
            text-align: center;
        }

        /* Tables */
        .table-wrapper {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        th, td {
            padding: 10px 12px;
            text-align: right;
            border-bottom: 1px solid #e2e8f0;
        }

        th {
            background: #2563eb;
            color: white;
            font-weight: 500;
            position: sticky;
            top: 0;
        }

        th:first-child, td:first-child {
            text-align: left;
            position: sticky;
            left: 0;
            background: inherit;
            z-index: 1;
        }

        tr:nth-child(even) {
            background: #f8fafc;
        }

        tr:hover {
            background: #f1f5f9;
        }

        tr.total-row {
            background: #dbeafe !important;
            font-weight: 600;
        }

        tr.sub-item td:first-child {
            padding-left: 24px;
            color: #64748b;
            font-size: 12px;
        }

        .negative { color: #dc2626; }
        .positive { color: #16a34a; }

        /* AI Summary Box */
        .ai-summary {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 12px;
            padding: 24px;
            border-left: 4px solid #0891b2;
        }

        .ai-summary h3 {
            color: #0891b2;
            font-size: 16px;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .ai-summary ul {
            list-style: none;
            padding: 0;
        }

        .ai-summary li {
            padding: 8px 0;
            padding-left: 20px;
            position: relative;
            line-height: 1.6;
        }

        .ai-summary li:before {
            content: "•";
            position: absolute;
            left: 0;
            color: #0891b2;
            font-weight: bold;
        }

        /* Radar Chart Container */
        .radar-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 40px;
            flex-wrap: wrap;
        }

        .radar-chart-wrapper {
            width: 400px;
            height: 400px;
        }

        /* Score Cards */
        .score-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 16px;
        }

        .score-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 16px;
            text-align: center;
        }

        .score-card .label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 8px;
        }

        .score-card .score {
            font-size: 28px;
            font-weight: 700;
            color: #2563eb;
        }

        .score-card .max {
            font-size: 14px;
            color: #94a3b8;
        }

        .grade-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2563eb, #1d4ed8);
            color: white;
            font-size: 36px;
            font-weight: 700;
            margin-bottom: 16px;
        }

        /* Footer */
        .footer {
            text-align: center;
            padding: 20px;
            color: #64748b;
            font-size: 13px;
        }

        /* Print styles */
        @media print {
            body { background: white; }
            .container { max-width: 100%; padding: 0; }
            .nav-tabs { display: none; }
            .page { display: block !important; page-break-after: always; }
            .section { box-shadow: none; border: 1px solid #e2e8f0; }
            .header { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
        }

        @media (max-width: 768px) {
            .two-columns { grid-template-columns: 1fr; }
            .score-grid { grid-template-columns: repeat(2, 1fr); }
            .kpi-grid { grid-template-columns: repeat(2, 1fr); }
            .radar-container { flex-direction: column; }
        }
        """

    def _build_header(self) -> str:
        """Build header section"""
        return f"""
        <header class="header">
            <h1>業績見通し</h1>
            <div class="subtitle">組織名：{self.data.company_name}</div>
            <div class="period">会計期間：{self.data.fiscal_year}（{self.data.period}）</div>
            <div class="period">対象：{self.data.target_month}</div>
        </header>
        """

    def _build_dashboard_page(self) -> str:
        """Build dashboard page (業績見通し)"""
        # Annual KPIs
        annual_kpis_html = self._build_kpi_section(
            self.data.annual_kpis[:6],
            "着地見込"
        )

        # Monthly KPIs (use same data with different label)
        monthly_kpis_html = self._build_kpi_section(
            self.data.annual_kpis[:6],
            self.data.target_month
        )

        return f"""
        <div class="section">
            <h2 class="section-title">業績見通し</h2>
            <p style="text-align: right; color: #64748b; margin-bottom: 16px;">（単位：円）</p>

            <div class="two-columns">
                <div>
                    <h3 class="section-subtitle">年間着地見込</h3>
                    <div class="kpi-grid">
                        {annual_kpis_html}
                    </div>
                </div>
                <div>
                    <div class="chart-container">
                        <div class="chart-title">売上高・利益推移（年間）</div>
                        <canvas id="chart-annual" height="250"></canvas>
                    </div>
                </div>
            </div>

            <div style="margin-top: 32px;" class="two-columns">
                <div>
                    <h3 class="section-subtitle">{self.data.target_month}実績</h3>
                    <div class="kpi-grid">
                        {monthly_kpis_html}
                    </div>
                </div>
                <div>
                    <div class="chart-container">
                        <div class="chart-title">売上高・利益推移（月次）</div>
                        <canvas id="chart-monthly" height="250"></canvas>
                    </div>
                </div>
            </div>
        </div>
        """

    def _build_kpi_section(self, kpis: list, label: str) -> str:
        """Build KPI cards HTML"""
        color_map = {
            "#2563eb": "blue",
            "#16a34a": "green",
            "#dc2626": "red",
            "#8b5cf6": "purple",
            "#0891b2": "cyan",
            "#f59e0b": "orange",
        }

        cards_html = ""
        for kpi in kpis:
            color_class = color_map.get(kpi.color, "blue")
            is_negative = kpi.value < 0
            value_class = "negative" if is_negative else ""

            variance_html = ""
            if kpi.target_value and kpi.target_value != 0:
                variance = kpi.value - kpi.target_value
                var_class = "positive" if variance >= 0 else "negative"
                var_sign = "+" if variance >= 0 else ""
                variance_html = f'''
                <div class="kpi-target">予算: {format_currency(kpi.target_value)}</div>
                <div class="kpi-variance {var_class}">{var_sign}{format_currency(variance)}</div>
                '''

            cards_html += f"""
            <div class="kpi-card {color_class}">
                <div class="kpi-title">{kpi.title}</div>
                <div class="kpi-value {value_class}">{kpi.formatted_value}</div>
                <div class="kpi-label">{label}</div>
                {variance_html}
            </div>
            """

        return cards_html

    def _build_summary_page(self) -> str:
        """Build summary page with AI analysis"""
        ai_content = ""
        if self.ai_summary:
            ai_content = f"""
            <div class="ai-summary">
                <h3>🤖 AI分析サマリ</h3>
                {self.ai_summary}
            </div>
            """
        else:
            ai_content = """
            <div class="ai-summary">
                <h3>📊 財務サマリ</h3>
                <p>AIサマリを生成するには、GOOGLE_API_KEYを設定してください。</p>
            </div>
            """

        # Financial summary table
        summary_table = self._build_summary_table()

        return f"""
        <div class="section">
            <h2 class="section-title">サマリ</h2>

            {ai_content}

            <div style="margin-top: 24px;">
                <h3 class="section-subtitle">主要指標サマリ</h3>
                {summary_table}
            </div>
        </div>
        """

    def _build_summary_table(self) -> str:
        """Build summary table"""
        summary_items = [
            item for item in self.data.pl_items
            if any(kw in item.name for kw in ["売上高", "売上原価", "売上総", "営業", "経常", "純利益"])
            and item.level == 0
        ]

        if not summary_items:
            return "<p>データがありません</p>"

        rows_html = ""
        for item in summary_items[:10]:
            budget = item.total_budget
            actual = item.total_actual
            variance = item.total_variance
            rate = item.total_achievement_rate

            var_class = "positive" if variance >= 0 else "negative"
            rate_class = "positive" if rate and rate >= 100 else "negative" if rate else ""

            rows_html += f"""
            <tr class="{'total-row' if item.is_total else ''}">
                <td>{item.name}</td>
                <td>{format_currency(budget)}</td>
                <td>{format_currency(actual)}</td>
                <td class="{var_class}">{format_currency(variance)}</td>
                <td class="{rate_class}">{f'{rate:.1f}%' if rate else '-'}</td>
            </tr>
            """

        return f"""
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>科目</th>
                        <th>予算（累計）</th>
                        <th>実績（累計）</th>
                        <th>差異</th>
                        <th>達成率</th>
                    </tr>
                </thead>
                <tbody>
                    {rows_html}
                </tbody>
            </table>
        </div>
        """

    def _build_pl_table_page(self) -> str:
        """Build P/L table page"""
        if not self.data.pl_items:
            return '<div class="section"><p>データがありません</p></div>'

        month_labels = self.data.month_labels[:12]

        header_html = "<th>科目</th>"
        for month in month_labels:
            header_html += f"<th>{month}</th>"
        header_html += "<th>合計</th>"

        rows_html = ""
        for item in self.data.pl_items:
            row_class = ""
            if item.is_total:
                row_class = "total-row"
            elif item.level > 0:
                row_class = "sub-item"

            cells = f"<td>{item.name}</td>"
            for i, month in enumerate(month_labels):
                if i < len(item.monthly_values):
                    val = item.monthly_values[i].actual
                    val_class = "negative" if val < 0 else ""
                    cells += f'<td class="{val_class}">{format_currency(val)}</td>'
                else:
                    cells += "<td>-</td>"

            total_class = "negative" if item.total_actual < 0 else ""
            cells += f'<td class="{total_class}">{format_currency(item.total_actual)}</td>'

            rows_html += f'<tr class="{row_class}">{cells}</tr>'

        return f"""
        <div class="section">
            <h2 class="section-title">損益計算書</h2>
            <p style="text-align: right; color: #64748b; margin-bottom: 16px;">（単位：円）</p>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>{header_html}</tr>
                    </thead>
                    <tbody>
                        {rows_html}
                    </tbody>
                </table>
            </div>
        </div>
        """

    def _build_analysis_page(self) -> str:
        """Build performance analysis page (業績分析表)"""
        ai_analysis = ""
        if self.ai_variance:
            ai_analysis = f"""
            <div class="ai-summary" style="margin-bottom: 24px;">
                <h3>🤖 AI差異分析</h3>
                {self.ai_variance}
            </div>
            """

        # Build comparison KPIs
        comparison_html = self._build_comparison_kpis()

        return f"""
        <div class="section">
            <h2 class="section-title">業績分析表</h2>
            <p style="color: #64748b; margin-bottom: 24px;">対象：{self.data.target_month}</p>

            {ai_analysis}

            <div class="two-columns">
                <div>
                    <h3 class="section-subtitle">{self.data.target_month} 実績</h3>
                    {comparison_html}
                </div>
                <div>
                    <div class="chart-container">
                        <div class="chart-title">予算 vs 実績比較</div>
                        <canvas id="chart-comparison" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>
        """

    def _build_comparison_kpis(self) -> str:
        """Build comparison KPI cards"""
        key_items = ["売上高", "売上総", "営業", "純利益"]
        cards = ""

        for item in self.data.pl_items:
            if any(kw in item.name and item.level == 0 for kw in key_items):
                if item.monthly_values:
                    last_month = item.monthly_values[-1] if item.monthly_values else None
                    if last_month:
                        variance = last_month.actual - last_month.budget
                        var_class = "positive" if variance >= 0 else "negative"
                        var_sign = "+" if variance >= 0 else ""

                        cards += f"""
                        <div class="kpi-card blue" style="margin-bottom: 12px;">
                            <div class="kpi-title">{item.name}</div>
                            <div class="kpi-value">{format_currency(last_month.actual)}</div>
                            <div class="kpi-target">予算: {format_currency(last_month.budget)}</div>
                            <div class="kpi-variance {var_class}">{var_sign}{format_currency(variance)}</div>
                        </div>
                        """

        return cards if cards else "<p>データがありません</p>"

    def _build_highlights_page(self) -> str:
        """Build financial highlights page (財務ハイライト)"""
        if self.ai_highlights:
            total_score = self.ai_highlights.get("total_score", 21)
            grade = self.ai_highlights.get("grade", "B")
            scores = self.ai_highlights.get("scores", {})
            comment = self.ai_highlights.get("overall_comment", "")

            score_cards = ""
            for name, data in scores.items():
                score = data.get("score", 3)
                score_cards += f"""
                <div class="score-card">
                    <div class="label">{name}</div>
                    <div class="score">{score}<span class="max">/5</span></div>
                </div>
                """
        else:
            total_score = 21
            grade = "B"
            comment = "財務分析を行うにはAI機能を有効にしてください。"
            score_cards = """
            <div class="score-card"><div class="label">売上持続性</div><div class="score">3<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">収益性</div><div class="score">4<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">生産性</div><div class="score">4<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">健全性</div><div class="score">4<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">効率性</div><div class="score">3<span class="max">/5</span></div></div>
            <div class="score-card"><div class="label">安全性</div><div class="score">3<span class="max">/5</span></div></div>
            """

        return f"""
        <div class="section">
            <h2 class="section-title">財務ハイライト</h2>
            <p style="color: #64748b; margin-bottom: 24px;">対象：{self.data.target_month}</p>

            <div class="radar-container">
                <div style="text-align: center;">
                    <h3 class="section-subtitle">総合評価</h3>
                    <div class="grade-badge">{grade}</div>
                    <div style="font-size: 24px; font-weight: 700;">{total_score}<span style="font-size: 16px; color: #64748b;">/30</span></div>
                    <p style="margin-top: 16px; color: #64748b; max-width: 300px;">{comment}</p>
                </div>

                <div class="radar-chart-wrapper">
                    <canvas id="chart-radar"></canvas>
                </div>
            </div>

            <div style="margin-top: 32px;">
                <h3 class="section-subtitle">評価詳細</h3>
                <div class="score-grid">
                    {score_cards}
                </div>
            </div>
        </div>
        """

    def _build_footer(self) -> str:
        """Build footer"""
        return f"""
        <footer class="footer">
            <p>Generated: {self.data.generated_at.strftime('%Y-%m-%d %H:%M')} | {self.data.company_name}</p>
            <p style="margin-top: 8px; font-size: 12px;">Print this page (Ctrl+P / Cmd+P) to save as PDF</p>
            <p style="margin-top: 4px; font-size: 11px; color: #94a3b8;">Powered by Gemini AI</p>
        </footer>
        """

    def _build_chart_scripts(self) -> str:
        """Build all Chart.js scripts"""
        scripts = []

        # Annual combo chart
        scripts.append(self._build_annual_chart())

        # Monthly combo chart
        scripts.append(self._build_monthly_chart())

        # Comparison chart
        scripts.append(self._build_comparison_chart())

        # Radar chart
        scripts.append(self._build_radar_chart())

        return "\n".join(scripts)

    def _build_annual_chart(self) -> str:
        """Build annual combo chart"""
        labels = json.dumps(self.data.month_labels[:12])

        sales_data = []
        profit_data = []

        sales_item = next((item for item in self.data.pl_items if item.name == "売上高"), None)
        profit_item = next((item for item in self.data.pl_items if "営業" in item.name and "損益" in item.name), None)

        if sales_item:
            sales_data = [float(v.actual) for v in sales_item.monthly_values[:12]]
        if profit_item:
            profit_data = [float(v.actual) for v in profit_item.monthly_values[:12]]

        return f"""
        new Chart(document.getElementById('chart-annual'), {{
            type: 'bar',
            data: {{
                labels: {labels},
                datasets: [
                    {{
                        label: '売上高',
                        data: {json.dumps(sales_data)},
                        backgroundColor: '#93c5fd',
                        borderColor: '#2563eb',
                        borderWidth: 1,
                        yAxisID: 'y'
                    }},
                    {{
                        label: '営業利益',
                        data: {json.dumps(profit_data)},
                        type: 'line',
                        borderColor: '#dc2626',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        tension: 0.1,
                        yAxisID: 'y1'
                    }}
                ]
            }},
            options: {{
                responsive: true,
                interaction: {{ mode: 'index', intersect: false }},
                scales: {{
                    y: {{
                        type: 'linear',
                        position: 'left',
                        ticks: {{ callback: v => (v/10000).toLocaleString() + '万' }}
                    }},
                    y1: {{
                        type: 'linear',
                        position: 'right',
                        grid: {{ drawOnChartArea: false }},
                        ticks: {{ callback: v => (v/10000).toLocaleString() + '万' }}
                    }}
                }},
                plugins: {{ legend: {{ position: 'bottom' }} }}
            }}
        }});
        """

    def _build_monthly_chart(self) -> str:
        """Build monthly chart"""
        labels = json.dumps(self.data.month_labels[-6:] if len(self.data.month_labels) > 6 else self.data.month_labels)

        sales_data = []
        profit_data = []

        sales_item = next((item for item in self.data.pl_items if item.name == "売上高"), None)
        profit_item = next((item for item in self.data.pl_items if "営業" in item.name and "損益" in item.name), None)

        if sales_item:
            sales_data = [float(v.actual) for v in sales_item.monthly_values[-6:]]
        if profit_item:
            profit_data = [float(v.actual) for v in profit_item.monthly_values[-6:]]

        return f"""
        new Chart(document.getElementById('chart-monthly'), {{
            type: 'bar',
            data: {{
                labels: {labels},
                datasets: [
                    {{
                        label: '売上高',
                        data: {json.dumps(sales_data)},
                        backgroundColor: '#93c5fd'
                    }},
                    {{
                        label: '営業利益',
                        data: {json.dumps(profit_data)},
                        backgroundColor: '#1e40af'
                    }}
                ]
            }},
            options: {{
                responsive: true,
                scales: {{
                    y: {{ ticks: {{ callback: v => (v/10000).toLocaleString() + '万' }} }}
                }},
                plugins: {{ legend: {{ position: 'bottom' }} }}
            }}
        }});
        """

    def _build_comparison_chart(self) -> str:
        """Build budget vs actual comparison chart"""
        labels = ["売上高", "売上総利益", "営業利益", "経常利益"]
        budget_data = []
        actual_data = []

        for label in labels:
            item = next((i for i in self.data.pl_items if label in i.name and i.level == 0), None)
            if item:
                budget_data.append(float(item.total_budget))
                actual_data.append(float(item.total_actual))
            else:
                budget_data.append(0)
                actual_data.append(0)

        return f"""
        new Chart(document.getElementById('chart-comparison'), {{
            type: 'bar',
            data: {{
                labels: {json.dumps(labels)},
                datasets: [
                    {{
                        label: '予算',
                        data: {json.dumps(budget_data)},
                        backgroundColor: '#cbd5e1'
                    }},
                    {{
                        label: '実績',
                        data: {json.dumps(actual_data)},
                        backgroundColor: '#2563eb'
                    }}
                ]
            }},
            options: {{
                responsive: true,
                scales: {{
                    y: {{ ticks: {{ callback: v => (v/10000).toLocaleString() + '万' }} }}
                }},
                plugins: {{ legend: {{ position: 'bottom' }} }}
            }}
        }});
        """

    def _build_radar_chart(self) -> str:
        """Build radar chart for financial highlights"""
        if self.ai_highlights and "scores" in self.ai_highlights:
            scores = self.ai_highlights["scores"]
            data = [scores.get(k, {}).get("score", 3) for k in
                    ["売上持続性", "収益性", "生産性", "健全性", "効率性", "安全性"]]
        else:
            data = [3, 4, 4, 4, 3, 3]

        labels = json.dumps(["売上持続性", "収益性", "生産性", "健全性", "効率性", "安全性"])
        benchmark = [3, 3, 3, 3, 3, 3]

        return f"""
        new Chart(document.getElementById('chart-radar'), {{
            type: 'radar',
            data: {{
                labels: {labels},
                datasets: [
                    {{
                        label: '当社',
                        data: {json.dumps(data)},
                        backgroundColor: 'rgba(37, 99, 235, 0.2)',
                        borderColor: '#2563eb',
                        borderWidth: 2,
                        pointBackgroundColor: '#2563eb'
                    }},
                    {{
                        label: '業種基準',
                        data: {json.dumps(benchmark)},
                        backgroundColor: 'transparent',
                        borderColor: '#94a3b8',
                        borderWidth: 1,
                        borderDash: [5, 5],
                        pointBackgroundColor: '#94a3b8'
                    }}
                ]
            }},
            options: {{
                responsive: true,
                scales: {{
                    r: {{
                        beginAtZero: true,
                        max: 5,
                        ticks: {{ stepSize: 1 }}
                    }}
                }},
                plugins: {{ legend: {{ position: 'bottom' }} }}
            }}
        }});
        """

    def _build_nav_scripts(self) -> str:
        """Build navigation scripts"""
        return """
        // Tab navigation
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.addEventListener('click', function(e) {
                e.preventDefault();

                // Remove active from all tabs
                document.querySelectorAll('.nav-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));

                // Add active to clicked tab
                this.classList.add('active');

                // Show corresponding page
                const targetId = this.getAttribute('href').substring(1);
                document.getElementById(targetId).classList.add('active');
            });
        });

        // Show first page by default
        document.querySelector('.page').classList.add('active');
        """
