"""
ui/dashboard_page.py
- Welcome dashboard with CLICKABLE feature cards
"""

import streamlit as st
from core.database import list_entries


def _goto(target_menu: str):
    """Callback — runs BEFORE widgets are instantiated"""
    st.session_state.menu = target_menu


def _feature_card(col, icon, title, desc, target_menu, key):
    with col:
        st.markdown(f"""
        <div style="
            text-align:center;
            padding:1.2rem 0.5rem;
            background: linear-gradient(135deg, #1e2130, #252a3d);
            border-radius: 12px;
            border: 1px solid #2d3349;
            margin-bottom: 0.5rem;
            height: 140px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        ">
            <div style="font-size:2.5rem; line-height:1;">{icon}</div>
            <div style="font-weight:700; margin-top:0.4rem; color:#fff;">{title}</div>
            <div style="font-size:0.8rem; color:#8b93a7; margin-top:0.2rem;">{desc}</div>
        </div>
        """, unsafe_allow_html=True)

        st.button(
            "Open ->",
            key=key,
            use_container_width=True,
            on_click=_goto,           # ← KEY FIX: use callback
            args=(target_menu,),
        )


def render_dashboard():
    st.subheader("🏠 Dashboard")
    st.markdown("### Welcome to YT Analyzer Pro 🎬")
    st.info("Click any feature card below or use the sidebar menu.")

    features = [
        ("📥", "Feature 1", "Full Data Extraction", "📥 Analyze Video (URL)"),
        ("🔑", "Feature 2", "Trending Keywords", "🔑 Trending Keywords"),
        ("🔥", "Feature 3", "Trending Videos", "🔥 Trending Videos"),
        ("🧠", "Feature 4", "AI Video Analyzer", "🧠 Video Analyzer (AI)"),
        ("⚖️", "Feature 5", "Compare Videos", "⚖️ Compare Videos"),
    ]

    cols = st.columns(5)
    for col, (icon, title, desc, target) in zip(cols, features):
        _feature_card(col, icon, title, desc, target, key=f"nav_{title}")

    # Recent activity
    st.markdown("---")
    recent = list_entries(limit=5)
    if recent:
        st.markdown("### 🕒 Recent Activity")
        icon_map = {
            "video": "📥", "keywords": "🔑", "trending": "🔥",
            "analyze": "🧠", "compare": "⚖️",
        }
        for e in recent:
            icon = icon_map.get(e["kind"], "📄")
            st.markdown(
                f"{icon} `{e['kind']}` **{e['title'][:70]}** — {e['created_at'][:16]}"
            )
    else:
        st.caption("No history yet — start analyzing!")