from markupsafe import Markup, escape


def generate_report_html(synthesis: dict, language: str = "ar", references: list = None) -> str:
    if not isinstance(synthesis, dict) or "raw_text" in synthesis:
        raw = synthesis.get("raw_text", str(synthesis)) if isinstance(synthesis, dict) else str(synthesis)
        return f"<div class='report-section'><pre>{escape(raw)}</pre></div>"

    direction = "rtl" if language == "ar" else "ltr"
    sections = []

    verdict = synthesis.get("verdict", "N/A")
    verdict_class = {
        "GO": "text-green-600 bg-green-50 border-green-200",
        "NO-GO": "text-red-600 bg-red-50 border-red-200",
        "CONDITIONAL": "text-yellow-600 bg-yellow-50 border-yellow-200",
    }.get(verdict, "text-gray-600 bg-gray-50 border-gray-200")

    verdict_label = {
        "GO": {"ar": "موصى به", "en": "Recommended"},
        "NO-GO": {"ar": "غير موصى به", "en": "Not Recommended"},
        "CONDITIONAL": {"ar": "موصى به بشروط", "en": "Conditionally Recommended"},
    }.get(verdict, {"ar": verdict, "en": verdict})

    sections.append(f"""
    <div class="mb-8 p-6 rounded-xl border-2 {verdict_class}">
        <div class="text-3xl font-bold text-center mb-2">{escape(verdict_label.get(language, verdict))}</div>
        <div class="text-center text-sm opacity-75">{escape(synthesis.get('verdict_explanation', ''))}</div>
    </div>
    """)

    sections.append(_viability_score(synthesis, language))

    sections.append(_section(
        {"ar": "الملخص التنفيذي", "en": "Executive Summary"}.get(language),
        f"<p class='leading-relaxed'>{escape(synthesis.get('executive_summary', ''))}</p>", "clipboard-document-list"
    ))

    sections.append(_section(
        {"ar": "وصف المشروع", "en": "Project Description"}.get(language),
        f"<p class='leading-relaxed'>{escape(synthesis.get('project_description', ''))}</p>", "light-bulb"
    ))

    sections.append(_tam_sam_som(synthesis, language))

    sections.append(_section(
        {"ar": "تحليل السوق", "en": "Market Analysis"}.get(language),
        f"<p class='leading-relaxed'>{escape(synthesis.get('market_analysis_summary', ''))}</p>", "chart-bar"
    ))

    sections.append(_financial_highlights(synthesis, language))

    sections.append(_section(
        {"ar": "التحليل التنافسي", "en": "Competitive Analysis"}.get(language),
        f"<p class='leading-relaxed'>{escape(synthesis.get('competitive_analysis_summary', ''))}</p>", "shield-check"
    ))

    sections.append(_swot(synthesis, language))
    sections.append(_pestel(synthesis, language))
    sections.append(_porters(synthesis, language))
    sections.append(_vrio(synthesis, language))
    sections.append(_bmc(synthesis, language))
    sections.append(_lean_canvas(synthesis, language))
    sections.append(_gtm(synthesis, language))
    sections.append(_mvp(synthesis, language))
    sections.append(_target_audience(synthesis, language))
    sections.append(_marketing_strategy(synthesis, language))
    sections.append(_startup_cost_breakdown(synthesis, language))
    sections.append(_monthly_operating_costs(synthesis, language))
    sections.append(_staffing_plan(synthesis, language))
    sections.append(_revenue_streams(synthesis, language))
    sections.append(_industry_benchmarks(synthesis, language))
    sections.append(_usp(synthesis, language))
    sections.append(_risks(synthesis, language))
    sections.append(_recommendations(synthesis, language))

    fv = synthesis.get("final_verdict", "")
    if fv:
        sections.append(f"""
        <div class="mt-8 p-6 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl text-white">
            <h3 class="text-xl font-bold mb-3">{"الحكم النهائي" if language == "ar" else "Final Verdict"}</h3>
            <p class="leading-relaxed">{escape(str(fv))}</p>
        </div>
        """)

    score = synthesis.get("confidence_score", 0)
    sections.append(f"""
    <div class="mt-6 text-center text-sm text-gray-500">
        {"درجة الثقة" if language == "ar" else "Confidence Score"}: <span class="font-bold text-indigo-600">{escape(str(score))}%</span>
    </div>
    """)

    # References section
    if references and isinstance(references, list) and len(references) > 0:
        sections.append(_references_section(references, language))

    filtered = [s for s in sections if s]
    return f"<div dir='{direction}' class='report-content'>{''.join(filtered)}</div>"


def _viability_score(synthesis, language):
    vs = synthesis.get("viability_score", {})
    if not isinstance(vs, dict) or not vs:
        return ""
    overall = vs.get("overall", 0)
    dims = [
        ("market", {"ar": "السوق", "en": "Market"}),
        ("financial", {"ar": "المالي", "en": "Financial"}),
        ("competitive", {"ar": "التنافسي", "en": "Competitive"}),
        ("team_readiness", {"ar": "جاهزية الفريق", "en": "Team Readiness"}),
        ("innovation", {"ar": "الابتكار", "en": "Innovation"}),
    ]
    color = "emerald" if overall >= 70 else ("yellow" if overall >= 40 else "red")
    bars = ""
    for key, labels in dims:
        val = vs.get(key, 0)
        bc = "emerald" if val >= 70 else ("yellow" if val >= 40 else "red")
        bars += f"""
        <div class="flex items-center gap-3 mb-2">
            <span class="text-xs text-gray-500 w-24 text-left">{escape(labels.get(language, labels['en']))}</span>
            <div class="flex-1 bg-gray-200 rounded-full h-2.5 overflow-hidden">
                <div class="bg-{bc}-500 h-2.5 rounded-full" style="width:{val}%"></div>
            </div>
            <span class="text-xs font-bold text-gray-600 w-10 text-right">{val}%</span>
        </div>
        """
    title = {"ar": "مؤشر الجدوى", "en": "Viability Score"}.get(language)
    content = f"""
    <div class="flex items-center gap-8 mb-6">
        <div class="text-center">
            <div class="text-5xl font-bold text-{color}-500">{overall}</div>
            <div class="text-xs text-gray-500 mt-1">/ 100</div>
        </div>
        <div class="flex-1">{bars}</div>
    </div>
    """
    return _section(title, content, "chart-pie")


def _tam_sam_som(synthesis, language):
    ts = synthesis.get("tam_sam_som", {})
    if not isinstance(ts, dict) or not ts:
        return ""
    title = {"ar": "حجم السوق (TAM/SAM/SOM)", "en": "Market Size (TAM/SAM/SOM)"}.get(language)
    items = [
        ("TAM", ts.get("tam", ""), ts.get("tam_value", ""), "blue"),
        ("SAM", ts.get("sam", ""), ts.get("sam_value", ""), "indigo"),
        ("SOM", ts.get("som", ""), ts.get("som_value", ""), "purple"),
    ]
    cards = ""
    for label, desc, val, c in items:
        cards += f"""
        <div class="bg-{c}-50 p-4 rounded-xl border border-{c}-200">
            <div class="text-xs font-mono text-{c}-600 mb-1">{label}</div>
            <div class="font-bold text-{c}-700 text-lg mb-1">{escape(str(val))}</div>
            <div class="text-xs text-gray-600">{escape(str(desc))}</div>
        </div>
        """
    return _section(title, f"<div class='grid grid-cols-1 md:grid-cols-3 gap-4'>{cards}</div>", "chart-bar-square")


def _financial_highlights(synthesis, language):
    fh = synthesis.get("financial_highlights", {})
    if not isinstance(fh, dict) or not fh:
        return ""
    labels = {
        "ar": {"estimated_startup_cost": "تكلفة التأسيس", "monthly_costs": "التكاليف الشهرية",
                "break_even": "نقطة التعادل", "revenue_potential": "إمكانية الإيرادات", "roi_estimate": "تقدير العائد",
                "year1_revenue": "إيرادات السنة 1", "year2_revenue": "إيرادات السنة 2", "year3_revenue": "إيرادات السنة 3"},
        "en": {"estimated_startup_cost": "Startup Cost", "monthly_costs": "Monthly Costs",
                "break_even": "Break Even", "revenue_potential": "Revenue Potential", "roi_estimate": "ROI Estimate",
                "year1_revenue": "Year 1 Revenue", "year2_revenue": "Year 2 Revenue", "year3_revenue": "Year 3 Revenue"},
    }.get(language, {})
    cards = ""
    for key, label in labels.items():
        val = fh.get(key, "")
        if not val:
            continue
        cards += f"<div class='bg-white p-4 rounded-lg shadow-sm border'><div class='text-xs text-gray-500 mb-1'>{escape(label)}</div><div class='font-semibold text-gray-800'>{escape(str(val))}</div></div>"
    title = {"ar": "التحليل المالي", "en": "Financial Analysis"}.get(language)
    summary = synthesis.get("financial_analysis_summary", "")
    chart_data = _build_revenue_chart_data(fh)
    cost_chart_data = _build_cost_chart_data(fh)
    chart_html = ""
    if chart_data:
        chart_html = f"""
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
            <div><div class="text-xs text-gray-500 mb-2 text-center font-semibold">{'الإيرادات السنوية' if language == 'ar' else 'Annual Revenue'}</div><canvas id="revenueChart" height="200"></canvas></div>
            <div><div class="text-xs text-gray-500 mb-2 text-center font-semibold">{'التكاليف مقابل الإيرادات' if language == 'ar' else 'Costs vs Revenue'}</div><canvas id="costChart" height="200"></canvas></div>
        </div>
        <script>
        document.addEventListener('DOMContentLoaded', function() {{
            if(typeof Chart !== 'undefined') {{
                Chart.defaults.color = '#94a3b8';
                var chartOpts = {{responsive:true, plugins:{{legend:{{display:true,labels:{{color:'#94a3b8'}}}}}}, scales:{{y:{{beginAtZero:true,ticks:{{color:'#94a3b8'}},grid:{{color:'rgba(255,255,255,0.05)'}}}},x:{{ticks:{{color:'#94a3b8'}},grid:{{display:false}}}}}}}};
                new Chart(document.getElementById('revenueChart'), {{type:'bar', data:{chart_data}, options:chartOpts}});
                {f"new Chart(document.getElementById('costChart'), {{type:'line', data:{cost_chart_data}, options:chartOpts}});" if cost_chart_data else ""}
            }}
        }});
        </script>
        """
    content = f"<p class='leading-relaxed mb-4'>{escape(summary)}</p><div class='grid grid-cols-2 md:grid-cols-4 gap-3'>{cards}</div>{chart_html}"
    return _section(title, content, "banknotes")


def _build_revenue_chart_data(fh):
    import re
    def _extract_num(val):
        if not val:
            return 0
        s = str(val).replace(",", "").replace("٬", "")
        m = re.search(r'[\d.]+', s)
        return float(m.group()) if m else 0

    y1 = _extract_num(fh.get("year1_revenue", ""))
    y2 = _extract_num(fh.get("year2_revenue", ""))
    y3 = _extract_num(fh.get("year3_revenue", ""))
    if not any([y1, y2, y3]):
        return ""
    return (
        "{labels:['Year 1','Year 2','Year 3'],"
        "datasets:[{label:'Revenue',data:[" + f"{y1},{y2},{y3}" +
        "],backgroundColor:['rgba(99,102,241,0.6)','rgba(139,92,246,0.6)','rgba(168,85,247,0.6)'],"
        "borderRadius:8}]}"
    )


def _build_cost_chart_data(fh):
    import re
    def _extract_num(val):
        if not val:
            return 0
        s = str(val).replace(",", "").replace("٬", "")
        m = re.search(r'[\d.]+', s)
        return float(m.group()) if m else 0

    startup = _extract_num(fh.get("estimated_startup_cost", ""))
    monthly = _extract_num(fh.get("monthly_costs", ""))
    y1_rev = _extract_num(fh.get("year1_revenue", ""))
    y2_rev = _extract_num(fh.get("year2_revenue", ""))
    y3_rev = _extract_num(fh.get("year3_revenue", ""))
    if not any([startup, monthly, y1_rev]):
        return ""
    y1_cost = startup + monthly * 12
    y2_cost = monthly * 12
    y3_cost = monthly * 12
    return (
        "{labels:['Year 1','Year 2','Year 3'],"
        "datasets:["
        f"{{label:'Revenue',data:[{y1_rev},{y2_rev},{y3_rev}],borderColor:'rgba(99,102,241,1)',backgroundColor:'rgba(99,102,241,0.1)',fill:true,tension:0.3}},"
        f"{{label:'Costs',data:[{y1_cost},{y2_cost},{y3_cost}],borderColor:'rgba(239,68,68,1)',backgroundColor:'rgba(239,68,68,0.1)',fill:true,tension:0.3}}"
        "]}"
    )


def _swot(synthesis, language):
    swot = synthesis.get("swot", {})
    if not isinstance(swot, dict) or not swot:
        return ""
    swot_labels = {"ar": {"strengths": "نقاط القوة", "weaknesses": "نقاط الضعف", "opportunities": "الفرص", "threats": "التهديدات"},
                   "en": {"strengths": "Strengths", "weaknesses": "Weaknesses", "opportunities": "Opportunities", "threats": "Threats"}}
    colors = {"strengths": "green", "weaknesses": "red", "opportunities": "blue", "threats": "yellow"}
    swot_html = "<div class='grid grid-cols-1 md:grid-cols-2 gap-4'>"
    for key in ["strengths", "weaknesses", "opportunities", "threats"]:
        items = swot.get(key, [])
        c = colors[key]
        label = swot_labels.get(language, swot_labels["en"]).get(key, key)
        lis = "".join(f"<li class='py-1'>{escape(str(it))}</li>" for it in (items if isinstance(items, list) else [items]))
        swot_html += f"<div class='bg-{c}-50 p-4 rounded-lg border border-{c}-200'><h4 class='font-bold text-{c}-700 mb-2'>{escape(label)}</h4><ul class='list-disc list-inside text-sm'>{lis}</ul></div>"
    swot_html += "</div>"
    return _section({"ar": "تحليل SWOT", "en": "SWOT Analysis"}.get(language), swot_html, "squares-2x2")


def _pestel(synthesis, language):
    pestel = synthesis.get("pestel", {})
    if not isinstance(pestel, dict) or not pestel:
        return ""
    pestel_labels = {"ar": {"political": "سياسي", "economic": "اقتصادي", "social": "اجتماعي", "technological": "تقني", "environmental": "بيئي", "legal": "قانوني"},
                     "en": {"political": "Political", "economic": "Economic", "social": "Social", "technological": "Technological", "environmental": "Environmental", "legal": "Legal"}}
    rows = ""
    for key in ["political", "economic", "social", "technological", "environmental", "legal"]:
        label = pestel_labels.get(language, pestel_labels["en"]).get(key, key)
        val = pestel.get(key, "")
        rows += f"<tr class='border-b'><td class='py-2 px-3 font-medium bg-gray-50 w-1/4'>{escape(label)}</td><td class='py-2 px-3'>{escape(str(val))}</td></tr>"
    return _section({"ar": "تحليل PESTEL", "en": "PESTEL Analysis"}.get(language),
        f"<table class='w-full border rounded-lg overflow-hidden'>{rows}</table>", "globe-alt")


def _porters(synthesis, language):
    pf = synthesis.get("porters_five_forces", {})
    if not isinstance(pf, dict) or not pf:
        return ""
    pf_labels = {"ar": {"threat_new_entrants": "تهديد الداخلين الجدد", "bargaining_power_suppliers": "قوة الموردين",
                        "bargaining_power_buyers": "قوة المشترين", "threat_substitutes": "تهديد البدائل", "industry_rivalry": "حدة المنافسة"},
                 "en": {"threat_new_entrants": "Threat of New Entrants", "bargaining_power_suppliers": "Supplier Power",
                        "bargaining_power_buyers": "Buyer Power", "threat_substitutes": "Threat of Substitutes", "industry_rivalry": "Industry Rivalry"}}
    rows = ""
    for key in pf_labels.get(language, pf_labels["en"]):
        label = pf_labels.get(language, pf_labels["en"]).get(key, key)
        val = pf.get(key, "")
        rows += f"<tr class='border-b'><td class='py-2 px-3 font-medium bg-gray-50 w-1/3'>{escape(label)}</td><td class='py-2 px-3'>{escape(str(val))}</td></tr>"
    return _section({"ar": "قوى بورتر الخمس", "en": "Porter's Five Forces"}.get(language),
        f"<table class='w-full border rounded-lg overflow-hidden'>{rows}</table>", "presentation-chart-bar")


def _bmc(synthesis, language):
    bmc = synthesis.get("business_model_canvas", {})
    if not isinstance(bmc, dict) or not bmc:
        return ""
    title = {"ar": "نموذج العمل التجاري", "en": "Business Model Canvas"}.get(language)
    blocks = {
        "ar": {"key_partners": "الشركاء الرئيسيون", "key_activities": "الأنشطة الرئيسية", "key_resources": "الموارد الرئيسية",
               "value_propositions": "القيمة المقترحة", "customer_relationships": "علاقات العملاء", "channels": "القنوات",
               "customer_segments": "شرائح العملاء", "cost_structure": "هيكل التكاليف", "revenue_streams": "مصادر الإيرادات"},
        "en": {"key_partners": "Key Partners", "key_activities": "Key Activities", "key_resources": "Key Resources",
               "value_propositions": "Value Propositions", "customer_relationships": "Customer Relationships", "channels": "Channels",
               "customer_segments": "Customer Segments", "cost_structure": "Cost Structure", "revenue_streams": "Revenue Streams"}
    }
    colors = ["blue", "indigo", "purple", "emerald", "teal", "cyan", "amber", "red", "green"]
    html = "<div class='grid grid-cols-1 md:grid-cols-3 gap-3'>"
    for i, (key, label) in enumerate(blocks.get(language, blocks["en"]).items()):
        items = bmc.get(key, [])
        c = colors[i % len(colors)]
        if isinstance(items, list):
            lis = "".join(f"<li class='text-xs py-0.5'>{escape(str(it))}</li>" for it in items)
            content = f"<ul class='list-disc list-inside'>{lis}</ul>"
        else:
            content = f"<p class='text-xs'>{escape(str(items))}</p>"
        html += f"<div class='bg-{c}-50 p-3 rounded-lg border border-{c}-200'><div class='font-bold text-{c}-700 text-xs mb-2 uppercase'>{escape(label)}</div>{content}</div>"
    html += "</div>"
    return _section(title, html, "table-cells")


def _lean_canvas(synthesis, language):
    lc = synthesis.get("lean_canvas", {})
    if not isinstance(lc, dict) or not lc:
        return ""
    title = {"ar": "مخطط Lean Canvas", "en": "Lean Canvas"}.get(language)
    blocks = {
        "ar": {"problem": "المشكلة", "solution": "الحل", "unique_value": "القيمة الفريدة",
               "unfair_advantage": "الميزة التنافسية", "customer_segments": "شرائح العملاء",
               "key_metrics": "المقاييس الرئيسية", "channels": "القنوات",
               "cost_structure": "هيكل التكاليف", "revenue_streams": "مصادر الإيرادات"},
        "en": {"problem": "Problem", "solution": "Solution", "unique_value": "Unique Value Prop",
               "unfair_advantage": "Unfair Advantage", "customer_segments": "Customer Segments",
               "key_metrics": "Key Metrics", "channels": "Channels",
               "cost_structure": "Cost Structure", "revenue_streams": "Revenue Streams"}
    }
    html = "<div class='grid grid-cols-1 md:grid-cols-3 gap-3'>"
    for key, label in blocks.get(language, blocks["en"]).items():
        items = lc.get(key, "")
        if isinstance(items, list):
            lis = "".join(f"<li class='text-xs py-0.5'>{escape(str(it))}</li>" for it in items)
            content = f"<ul class='list-disc list-inside'>{lis}</ul>"
        else:
            content = f"<p class='text-xs'>{escape(str(items))}</p>"
        html += f"<div class='bg-white p-3 rounded-lg border'><div class='font-bold text-gray-700 text-xs mb-2 uppercase'>{escape(label)}</div>{content}</div>"
    html += "</div>"
    return _section(title, html, "rectangle-group")


def _gtm(synthesis, language):
    gtm = synthesis.get("gtm_strategy", {})
    if not isinstance(gtm, dict) or not gtm:
        return ""
    title = {"ar": "استراتيجية دخول السوق", "en": "Go-to-Market Strategy"}.get(language)
    phases = [
        ("phase1", {"ar": "المرحلة 1", "en": "Phase 1"}, "blue"),
        ("phase2", {"ar": "المرحلة 2", "en": "Phase 2"}, "indigo"),
        ("phase3", {"ar": "المرحلة 3", "en": "Phase 3"}, "purple"),
    ]
    html = "<div class='space-y-3 mb-4'>"
    for key, labels, c in phases:
        val = gtm.get(key, "")
        if val:
            html += f"<div class='bg-{c}-50 p-4 rounded-lg border border-{c}-200'><div class='font-bold text-{c}-700 text-sm mb-1'>{labels.get(language)}</div><p class='text-xs text-gray-600'>{escape(str(val))}</p></div>"
    html += "</div>"
    pricing = gtm.get("pricing_strategy", "")
    if pricing:
        html += f"<p class='text-sm mb-2'><strong>{'استراتيجية التسعير' if language == 'ar' else 'Pricing'}:</strong> {escape(str(pricing))}</p>"
    channels = gtm.get("distribution_channels", [])
    if channels:
        tags = "".join(f"<span class='inline-block bg-blue-100 text-blue-700 text-xs px-2 py-1 rounded-full mr-1 mb-1'>{escape(str(ch))}</span>" for ch in channels)
        html += f"<div class='mt-2'><strong class='text-sm'>{'قنوات التوزيع' if language == 'ar' else 'Distribution'}:</strong><div class='mt-1'>{tags}</div></div>"
    return _section(title, html, "rocket-launch")


def _mvp(synthesis, language):
    mvp = synthesis.get("mvp_definition", {})
    if not isinstance(mvp, dict) or not mvp:
        return ""
    title = {"ar": "تعريف المنتج الأولي (MVP)", "en": "MVP Definition"}.get(language)
    html = ""
    core = mvp.get("core_features", [])
    if core:
        lis = "".join(f"<li class='py-0.5 flex items-start gap-2'><span class='text-emerald-500'>&#10003;</span><span class='text-sm'>{escape(str(f))}</span></li>" for f in core)
        html += f"<div class='mb-3'><div class='font-bold text-sm mb-1'>{'الميزات الأساسية' if language == 'ar' else 'Core Features'}</div><ul>{lis}</ul></div>"
    nice = mvp.get("nice_to_have", [])
    if nice:
        lis = "".join(f"<li class='py-0.5 flex items-start gap-2'><span class='text-gray-400'>&#9675;</span><span class='text-sm'>{escape(str(f))}</span></li>" for f in nice)
        html += f"<div class='mb-3'><div class='font-bold text-sm mb-1'>{'ميزات إضافية' if language == 'ar' else 'Nice to Have'}</div><ul>{lis}</ul></div>"
    timeline = mvp.get("estimated_timeline", "")
    cost = mvp.get("estimated_cost", "")
    if timeline or cost:
        html += f"<div class='flex gap-4 mt-3'>"
        if timeline:
            html += f"<div class='bg-white p-3 rounded-lg border flex-1'><div class='text-xs text-gray-500'>{'الجدول الزمني' if language == 'ar' else 'Timeline'}</div><div class='font-bold text-gray-800'>{escape(str(timeline))}</div></div>"
        if cost:
            html += f"<div class='bg-white p-3 rounded-lg border flex-1'><div class='text-xs text-gray-500'>{'التكلفة' if language == 'ar' else 'Cost'}</div><div class='font-bold text-gray-800'>{escape(str(cost))}</div></div>"
        html += "</div>"
    return _section(title, html, "beaker")


def _target_audience(synthesis, language):
    ta = synthesis.get("target_audience", [])
    if not isinstance(ta, list) or not ta:
        return ""
    cards = ""
    for persona in ta:
        if isinstance(persona, dict):
            name = persona.get("persona_name", "")
            desc = persona.get("description", "")
            needs = persona.get("needs", [])
            needs_html = "".join(f"<span class='inline-block bg-indigo-100 text-indigo-700 text-xs px-2 py-1 rounded-full mr-1 mb-1'>{escape(str(n))}</span>" for n in (needs if isinstance(needs, list) else []))
            cards += f"<div class='bg-white p-4 rounded-lg shadow-sm border'><div class='font-bold mb-1'>{escape(str(name))}</div><p class='text-sm text-gray-600 mb-2'>{escape(str(desc))}</p><div>{needs_html}</div></div>"
    return _section({"ar": "الجمهور المستهدف", "en": "Target Audience"}.get(language),
        f"<div class='grid grid-cols-1 md:grid-cols-2 gap-4'>{cards}</div>", "users")


def _marketing_strategy(synthesis, language):
    ms = synthesis.get("marketing_strategy", {})
    if not isinstance(ms, dict) or not ms:
        return ""
    ms_html = f"<p class='leading-relaxed mb-3'><strong>{'التموضع' if language == 'ar' else 'Positioning'}:</strong> {escape(str(ms.get('positioning', '')))}</p>"
    ms_html += f"<p class='leading-relaxed mb-3'><strong>{'العلامة التجارية' if language == 'ar' else 'Branding'}:</strong> {escape(str(ms.get('branding', '')))}</p>"
    channels = ms.get("channels", [])
    if channels:
        ch = "".join(f"<span class='inline-block bg-blue-100 text-blue-700 text-xs px-3 py-1 rounded-full mr-1 mb-1'>{escape(str(c))}</span>" for c in channels)
        ms_html += f"<div class='mb-3'><strong>{'القنوات' if language == 'ar' else 'Channels'}:</strong><div class='mt-1'>{ch}</div></div>"
    slogans = ms.get("slogan_ideas", [])
    if slogans:
        sl = "".join(f"<li class='italic text-gray-700'>\"{escape(str(s))}\"</li>" for s in slogans)
        ms_html += f"<div><strong>{'أفكار شعارات' if language == 'ar' else 'Slogan Ideas'}:</strong><ul class='list-disc list-inside mt-1'>{sl}</ul></div>"
    return _section({"ar": "استراتيجية التسويق", "en": "Marketing Strategy"}.get(language), ms_html, "megaphone")


def _risks(synthesis, language):
    risks = synthesis.get("risks_and_mitigations", [])
    if not isinstance(risks, list) or not risks:
        return ""
    rows = ""
    for r in risks:
        if isinstance(r, dict):
            sev_color = {"high": "red", "medium": "yellow", "low": "green"}.get(str(r.get("severity", "")).lower(), "gray")
            rows += f"<tr class='border-b'><td class='py-2 px-3'>{escape(str(r.get('risk', '')))}</td><td class='py-2 px-3 text-center'><span class='bg-{sev_color}-100 text-{sev_color}-700 text-xs px-2 py-1 rounded-full'>{escape(str(r.get('severity', '')))}</span></td><td class='py-2 px-3'>{escape(str(r.get('mitigation', '')))}</td></tr>"
    header = {"ar": "<th class='py-2 px-3 text-right'>المخاطر</th><th class='py-2 px-3'>الحدة</th><th class='py-2 px-3 text-right'>التخفيف</th>",
              "en": "<th class='py-2 px-3 text-left'>Risk</th><th class='py-2 px-3'>Severity</th><th class='py-2 px-3 text-left'>Mitigation</th>"}
    return _section({"ar": "المخاطر والتخفيف", "en": "Risks & Mitigations"}.get(language),
        f"<table class='w-full border rounded-lg overflow-hidden'><thead class='bg-gray-100'><tr>{header.get(language, header['en'])}</tr></thead><tbody>{rows}</tbody></table>", "exclamation-triangle")


def _recommendations(synthesis, language):
    recs = synthesis.get("recommendations", [])
    if not isinstance(recs, list) or not recs:
        return ""
    lis = "".join(f"<li class='py-1 flex items-start gap-2'><span class='text-indigo-500 mt-1'>&#10003;</span><span>{escape(str(r))}</span></li>" for r in recs)
    return _section({"ar": "التوصيات", "en": "Recommendations"}.get(language),
        f"<ul class='space-y-1'>{lis}</ul>", "check-badge")


def _section(title, content, icon="document-text"):
    return f"""
    <div class="report-section mb-6" x-data="{{ open: true }}">
        <button @click="open = !open" class="w-full flex items-center justify-between p-4 bg-white rounded-lg shadow-sm border hover:bg-gray-50 transition">
            <h3 class="text-lg font-bold text-gray-800">{escape(str(title))}</h3>
            <svg class="w-5 h-5 transform transition-transform" :class="{{ 'rotate-180': open }}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
        </button>
        <div x-show="open" x-transition class="p-4 bg-white border border-t-0 rounded-b-lg">
            {content}
        </div>
    </div>
    """


def _vrio(synthesis, language):
    vrio = synthesis.get("vrio", {})
    if not isinstance(vrio, dict) or not vrio:
        return ""
    title = {"ar": "تحليل VRIO", "en": "VRIO Analysis"}.get(language)
    headers = {
        "ar": ["المورد/القدرة", "القيمة", "الندرة", "صعوبة التقليد", "الاستغلال المؤسسي", "الميزة التنافسية"],
        "en": ["Resource", "Valuable", "Rare", "Inimitable", "Organized", "Advantage"]
    }
    h = headers.get(language, headers["en"])
    head = "".join(f"<th class='py-2 px-2 text-xs'>{escape(x)}</th>" for x in h)
    rows = ""
    items = vrio.get("resources", []) if isinstance(vrio.get("resources"), list) else []
    if not items and isinstance(vrio, dict):
        for k, v in vrio.items():
            if isinstance(v, dict):
                items.append(v)
    for item in items:
        if not isinstance(item, dict):
            continue
        def _yn(val):
            if isinstance(val, bool):
                return "✓" if val else "✗"
            return str(val)[:10]
        name = escape(str(item.get("name", item.get("resource", ""))))
        adv = escape(str(item.get("advantage", item.get("competitive_advantage", ""))))
        adv_color = "emerald" if "sustain" in adv.lower() else ("yellow" if "tempor" in adv.lower() else "gray")
        rows += f"<tr class='border-b'><td class='py-2 px-2 font-medium text-xs'>{name}</td>"
        for key in ["valuable", "rare", "inimitable", "organized"]:
            val = _yn(item.get(key, ""))
            color = "emerald" if val == "✓" else ("red" if val == "✗" else "gray")
            rows += f"<td class='py-2 px-2 text-center text-{color}-600 text-xs'>{val}</td>"
        rows += f"<td class='py-2 px-2 text-center'><span class='bg-{adv_color}-100 text-{adv_color}-700 text-xs px-2 py-0.5 rounded-full'>{adv}</span></td></tr>"
    if not rows:
        return ""
    return _section(title, f"<table class='w-full border rounded-lg overflow-hidden'><thead class='bg-gray-100'><tr>{head}</tr></thead><tbody>{rows}</tbody></table>", "squares-plus")


def _startup_cost_breakdown(synthesis, language):
    scb = synthesis.get("startup_cost_breakdown", {})
    if not isinstance(scb, dict) or not scb:
        return ""
    title = {"ar": "تفصيل تكاليف التأسيس", "en": "Startup Cost Breakdown"}.get(language)
    items = scb.get("items", [])
    if not isinstance(items, list):
        items = []
    if not items:
        for k, v in scb.items():
            if k not in ("total", "items", "notes"):
                items.append({"item": k, "cost": v})
    if not items:
        return ""
    rows = ""
    for item in items:
        if isinstance(item, dict):
            rows += f"<tr class='border-b'><td class='py-2 px-3 text-sm'>{escape(str(item.get('item', item.get('name', ''))))}</td><td class='py-2 px-3 text-sm font-semibold text-right'>{escape(str(item.get('cost', item.get('amount', ''))))}</td></tr>"
    total = scb.get("total", "")
    if total:
        rows += f"<tr class='bg-gray-100 font-bold'><td class='py-2 px-3'>{'الإجمالي' if language == 'ar' else 'Total'}</td><td class='py-2 px-3 text-right'>{escape(str(total))}</td></tr>"
    header = {"ar": "<th class='py-2 px-3 text-right'>البند</th><th class='py-2 px-3 text-left'>التكلفة</th>",
              "en": "<th class='py-2 px-3 text-left'>Item</th><th class='py-2 px-3 text-right'>Cost</th>"}
    return _section(title, f"<table class='w-full border rounded-lg overflow-hidden'><thead class='bg-gray-100'><tr>{header.get(language, header['en'])}</tr></thead><tbody>{rows}</tbody></table>", "calculator")


def _revenue_streams(synthesis, language):
    rs = synthesis.get("revenue_streams_detail", {})
    if not isinstance(rs, dict) and not isinstance(rs, list):
        return ""
    title = {"ar": "مصادر الإيرادات", "en": "Revenue Streams"}.get(language)
    items = rs if isinstance(rs, list) else rs.get("streams", [])
    if not isinstance(items, list) or not items:
        return ""
    cards = ""
    colors = ["blue", "indigo", "purple", "emerald", "teal", "amber"]
    for i, item in enumerate(items):
        c = colors[i % len(colors)]
        if isinstance(item, dict):
            name = escape(str(item.get("name", item.get("stream", ""))))
            desc = escape(str(item.get("description", "")))
            pct = item.get("percentage", "")
            cards += f"<div class='bg-{c}-50 p-4 rounded-lg border border-{c}-200'><div class='flex justify-between'><span class='font-bold text-{c}-700 text-sm'>{name}</span>"
            if pct:
                cards += f"<span class='bg-{c}-100 text-{c}-700 text-xs px-2 py-0.5 rounded-full'>{escape(str(pct))}</span>"
            cards += f"</div><p class='text-xs text-gray-600 mt-1'>{desc}</p></div>"
        elif isinstance(item, str):
            cards += f"<div class='bg-{c}-50 p-3 rounded-lg border border-{c}-200 text-sm'>{escape(item)}</div>"
    return _section(title, f"<div class='grid grid-cols-1 md:grid-cols-2 gap-3'>{cards}</div>", "currency-dollar")


def _monthly_operating_costs(synthesis, language):
    moc = synthesis.get("monthly_operating_costs", {})
    if not isinstance(moc, dict) or not moc:
        return ""
    title = {"ar": "التكاليف التشغيلية الشهرية", "en": "Monthly Operating Costs"}.get(language)
    items = moc.get("items", [])
    if not isinstance(items, list):
        items = []
    if not items:
        for k, v in moc.items():
            if k not in ("total", "items", "notes"):
                items.append({"item": k, "cost": v})
    if not items:
        return ""
    rows = ""
    for item in items:
        if isinstance(item, dict):
            rows += f"<tr class='border-b'><td class='py-2 px-3 text-sm'>{escape(str(item.get('item', item.get('name', ''))))}</td><td class='py-2 px-3 text-sm font-semibold text-right'>{escape(str(item.get('cost', item.get('amount', ''))))}</td></tr>"
    total = moc.get("total", "")
    if total:
        rows += f"<tr class='bg-gray-100 font-bold'><td class='py-2 px-3'>{'الإجمالي الشهري' if language == 'ar' else 'Monthly Total'}</td><td class='py-2 px-3 text-right'>{escape(str(total))}</td></tr>"
    header = {"ar": "<th class='py-2 px-3 text-right'>البند</th><th class='py-2 px-3 text-left'>التكلفة الشهرية</th>",
              "en": "<th class='py-2 px-3 text-left'>Item</th><th class='py-2 px-3 text-right'>Monthly Cost</th>"}
    return _section(title, f"<table class='w-full border rounded-lg overflow-hidden'><thead class='bg-gray-100'><tr>{header.get(language, header['en'])}</tr></thead><tbody>{rows}</tbody></table>", "banknotes")


def _staffing_plan(synthesis, language):
    sp = synthesis.get("staffing_plan", [])
    if not isinstance(sp, list) or not sp:
        return ""
    title = {"ar": "خطة التوظيف", "en": "Staffing Plan"}.get(language)
    rows = ""
    total_salary = 0
    total_count = 0
    for item in sp:
        if isinstance(item, dict):
            role = escape(str(item.get("role", "")))
            count = item.get("count", 1)
            salary = escape(str(item.get("monthly_salary", "")))
            rows += f"<tr class='border-b'><td class='py-2 px-3 text-sm'>{role}</td><td class='py-2 px-3 text-sm text-center'>{count}</td><td class='py-2 px-3 text-sm font-semibold text-right'>{salary}</td></tr>"
            total_count += int(count) if isinstance(count, (int, float)) else 0
    if total_count:
        rows += f"<tr class='bg-gray-100 font-bold'><td class='py-2 px-3'>{'الإجمالي' if language == 'ar' else 'Total'}</td><td class='py-2 px-3 text-center'>{total_count}</td><td class='py-2 px-3 text-right'>—</td></tr>"
    header = {
        "ar": "<th class='py-2 px-3 text-right'>الدور الوظيفي</th><th class='py-2 px-3 text-center'>العدد</th><th class='py-2 px-3 text-left'>الراتب الشهري</th>",
        "en": "<th class='py-2 px-3 text-left'>Role</th><th class='py-2 px-3 text-center'>Count</th><th class='py-2 px-3 text-right'>Monthly Salary</th>"
    }
    return _section(title, f"<table class='w-full border rounded-lg overflow-hidden'><thead class='bg-gray-100'><tr>{header.get(language, header['en'])}</tr></thead><tbody>{rows}</tbody></table>", "user-group")


def _industry_benchmarks(synthesis, language):
    ib = synthesis.get("industry_benchmarks", {})
    if not isinstance(ib, dict) or not ib:
        return ""
    title = {"ar": "معايير القطاع", "en": "Industry Benchmarks"}.get(language)
    items = [
        ({"ar": "القطاع", "en": "Industry"}.get(language), ib.get("industry", "")),
        ({"ar": "متوسط هامش الربح", "en": "Avg. Margin"}.get(language), ib.get("avg_margin", "")),
        ({"ar": "متوسط النمو", "en": "Avg. Growth"}.get(language), ib.get("avg_growth", "")),
        ({"ar": "حجم السوق", "en": "Market Size"}.get(language), ib.get("market_size", "")),
    ]
    cards = ""
    for label, val in items:
        if val:
            cards += f"<div class='bg-white p-4 rounded-lg shadow-sm border'><div class='text-xs text-gray-500 mb-1'>{escape(str(label))}</div><div class='font-semibold text-gray-800'>{escape(str(val))}</div></div>"
    notes = ib.get("comparison_notes", "")
    notes_html = f"<p class='leading-relaxed mt-4 text-sm'>{escape(str(notes))}</p>" if notes else ""
    return _section(title, f"<div class='grid grid-cols-2 md:grid-cols-4 gap-3'>{cards}</div>{notes_html}", "chart-bar")


def _usp(synthesis, language):
    usp = synthesis.get("usp", "")
    if not usp:
        return ""
    title = {"ar": "عرض القيمة الفريد (USP)", "en": "Unique Selling Proposition"}.get(language)
    return _section(title, f"<div class='p-4 bg-indigo-50 rounded-lg border border-indigo-200'><p class='text-lg font-semibold text-indigo-700'>{escape(str(usp))}</p></div>", "sparkles")


def _references_section(references: list, language: str) -> str:
    """Generate HTML section for references/sources."""
    if not references or not isinstance(references, list) or len(references) == 0:
        return ""

    title = {"ar": "المصادر والمراجع", "en": "Sources and References"}.get(language)
    subtitle = {"ar": "المصادر الموثوقة التي تم الرجوع إليها في إعداد هذا التقرير", "en": "Authoritative sources referenced in preparing this report"}.get(language)

    # Group references by source
    by_source = {}
    for ref in references:
        if isinstance(ref, dict):
            source = ref.get("source", "General")
            if source not in by_source:
                by_source[source] = []
            by_source[source].append(ref)
        elif isinstance(ref, str):
            if "General" not in by_source:
                by_source["General"] = []
            by_source["General"].append({"text": ref})

    content = f"<p class='text-sm text-slate-600 mb-6'>{subtitle}</p>"

    for source_name, refs in by_source.items():
        source_label = {"ar": "عام", "en": "General"}.get(language, source_name) if source_name == "General" else source_name
        content += f"<div class='mb-6'>"
        content += f"<h4 class='font-bold text-accent-gold text-sm uppercase tracking-wider mb-3'>{escape(str(source_label))}</h4>"
        content += f"<div class='space-y-3'>"

        for ref in refs:
            if isinstance(ref, dict):
                ref_title = ref.get("title", ref.get("text", ""))
                url = ref.get("url", "")
                desc = ref.get("description", "")

                # Display as clickable card with external link icon
                card = "<div class='bg-white/30 p-4 rounded-lg border border-white/10 hover:border-accent-gold/30 transition-colors'>"
                if ref_title and url:
                    # Make title a clickable link
                    card += f"<div class='font-semibold text-slate-300 text-sm mb-1'>"
                    card += f"<a href='{escape(url)}' target='_blank' rel='noopener noreferrer' class='hover:text-accent-gold transition-colors flex items-center gap-2'>"
                    card += f"<span>{escape(str(ref_title))}</span>"
                    card += f"<svg class='w-3 h-3 flex-shrink-0' fill='none' stroke='currentColor' viewBox='0 0 24 24'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14'/></svg>"
                    card += f"</a></div>"
                elif ref_title:
                    card += f"<div class='font-semibold text-slate-300 text-sm mb-1'>{escape(str(ref_title))}</div>"
                if desc:
                    card += f"<p class='text-xs text-slate-400 mb-2'>{escape(str(desc))}</p>"
                if url and not ref_title:
                    card += f"<a href='{escape(url)}' target='_blank' rel='noopener noreferrer' class='text-sm text-indigo-400 hover:text-indigo-300 flex items-center gap-1'>"
                    card += f"<span class='truncate'>{escape(url)}</span>"
                    card += f"<svg class='w-3 h-3 flex-shrink-0' fill='none' stroke='currentColor' viewBox='0 0 24 24'><path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14'/></svg>"
                    card += f"</a>"
                card += "</div>"
                content += card
            elif isinstance(ref, str):
                content += f"<div class='bg-white/30 p-3 rounded-lg border border-white/10 text-sm text-slate-400'>{escape(str(ref))}</div>"

        content += "</div></div>"

    return _section(title, content, "book-open")
