/**
 * Shois Chat Button — Analytics Dashboard
 *
 * KPI cards, line chart (impressions vs clicks), top platforms bar,
 * device breakdown, and date range picker.
 *
 * @package ShoisChatButton
 */
import { useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

/**
 * Mini bar chart (pure CSS, no Chart.js dependency).
 *
 * @param {Object} props      Component props.
 * @param {Array}  props.data Array of { date, impressions, clicks }.
 * @return {JSX.Element} Chart.
 */
function MiniChart({ data }) {
    if (!data || data.length === 0) {
        return <div className="shcb-chart-empty">{__('No data yet', 'shois-chat-button')}</div>;
    }

    const maxVal = Math.max(...data.map((d) => Math.max(d.impressions, d.clicks)), 1);

    return (
        <div className="shcb-mini-chart">
            <div className="shcb-chart-bars">
                {data.slice(-30).map((d, i) => (
                    <div key={i} className="shcb-chart-bar-group" title={`${d.date}: ${d.impressions} imp, ${d.clicks} clicks`}>
                        <div
                            className="shcb-chart-bar shcb-chart-bar-imp"
                            style={{ height: `${(d.impressions / maxVal) * 100}%` }}
                        />
                        <div
                            className="shcb-chart-bar shcb-chart-bar-click"
                            style={{ height: `${(d.clicks / maxVal) * 100}%` }}
                        />
                    </div>
                ))}
            </div>
            <div className="shcb-chart-legend">
                <span className="shcb-legend-item"><span className="shcb-legend-dot shcb-legend-imp" /> {__('Impressions', 'shois-chat-button')}</span>
                <span className="shcb-legend-item"><span className="shcb-legend-dot shcb-legend-click" /> {__('Clicks', 'shois-chat-button')}</span>
            </div>
        </div>
    );
}

/**
 * Platform breakdown list.
 *
 * @param {Object} props           Component props.
 * @param {Object} props.platforms Platform clicks { platform: count }.
 * @return {JSX.Element} Platform list.
 */
function PlatformBreakdown({ platforms }) {
    const entries = Object.entries(platforms || {});
    if (entries.length === 0) {
        return <p className="shcb-no-data">{__('No platform clicks yet', 'shois-chat-button')}</p>;
    }

    const max = Math.max(...entries.map(([, c]) => c), 1);

    return (
        <div className="shcb-platform-breakdown">
            {entries.slice(0, 10).map(([platform, count]) => (
                <div key={platform} className="shcb-platform-stat">
                    <span className="shcb-platform-stat-name">{platform}</span>
                    <div className="shcb-platform-stat-bar-wrap">
                        <div
                            className="shcb-platform-stat-bar"
                            style={{ width: `${(count / max) * 100}%` }}
                        />
                    </div>
                    <span className="shcb-platform-stat-count">{count}</span>
                </div>
            ))}
        </div>
    );
}

/**
 * KPI Card.
 */
function KpiCard({ label, value, icon, change }) {
    return (
        <div className="shcb-kpi-card">
            <div className="shcb-kpi-icon">{icon}</div>
            <div className="shcb-kpi-content">
                <span className="shcb-kpi-value">{value}</span>
                <span className="shcb-kpi-label">{label}</span>
            </div>
            {change !== undefined && (
                <span className={`shcb-kpi-change ${change >= 0 ? 'shcb-kpi-up' : 'shcb-kpi-down'}`}>
                    {change >= 0 ? '↑' : '↓'} {Math.abs(change)}%
                </span>
            )}
        </div>
    );
}

/**
 * AnalyticsPage — analytics dashboard.
 *
 * @return {JSX.Element} Analytics page.
 */
export default function AnalyticsPage() {
    const [period, setPeriod] = useState(30);
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const isProUser = window.shcbAdmin?.isPro || false;

    useEffect(() => {
        if (!isProUser) {
            setLoading(false);
            return;
        }
        setLoading(true);
        apiFetch({ path: `/shois-chat/v1/analytics?days=${period}` })
            .then((resp) => setData(resp))
            .catch(() => setData(null))
            .finally(() => setLoading(false));
    }, [period, isProUser]);

    // PRO upsell overlay for free users
    if (!isProUser) {
        const fakeData = {
            impressions: 1284,
            clicks: 342,
            ctr: '26.6',
            platform_clicks: { whatsapp: 198, telegram: 87, messenger: 57 },
            devices: { mobile: 820, desktop: 464 },
            daily: Array.from({ length: 14 }, (_, i) => ({
                date: `Day ${i + 1}`,
                impressions: Math.floor(Math.random() * 120 + 60),
                clicks: Math.floor(Math.random() * 40 + 10),
            })),
        };
        const fakeMobilePct = Math.round((fakeData.devices.mobile / (fakeData.devices.mobile + fakeData.devices.desktop)) * 100);

        return (
            <div className="shcb-analytics-page">
                {/* PRO locked overlay wrapper */}
                <div style={{ position: 'relative' }}>
                    {/* Blur overlay */}
                    <div style={{
                        position: 'absolute', inset: 0, zIndex: 10,
                        backdropFilter: 'blur(6px)',
                        backgroundColor: 'rgba(255,255,255,0.55)',
                        borderRadius: '12px',
                        display: 'flex', flexDirection: 'column',
                        alignItems: 'center', justifyContent: 'center',
                        gap: '12px',
                        padding: '40px 20px',
                    }}>
                        <div style={{ fontSize: '40px' }}>📊</div>
                        <h3 style={{ margin: 0, fontSize: '18px', fontWeight: '700', color: '#0f172a' }}>
                            {__('Analytics is a PRO Feature', 'shois-chat-button')}
                        </h3>
                        <p style={{ margin: 0, color: '#64748b', textAlign: 'center', maxWidth: '380px', fontSize: '14px' }}>
                            {__('Track impressions, clicks, CTR, top platforms, and device breakdown. Upgrade to PRO to unlock full analytics.', 'shois-chat-button')}
                        </p>
                        <span className="shcb-pro-badge" style={{ fontSize: '13px', padding: '4px 12px' }}>PRO</span>
                    </div>

                    {/* Fake data underneath (blurred) */}
                    <div style={{ filter: 'blur(4px)', pointerEvents: 'none', userSelect: 'none' }}>
                        <div className="shcb-modern-card">
                            <div className="shcb-modern-card-header">
                                <span>📊</span>
                                <h3>{__('Analytics', 'shois-chat-button')}</h3>
                            </div>
                        </div>
                        <div className="shcb-kpi-grid">
                            <KpiCard label={__('Impressions', 'shois-chat-button')} value={fakeData.impressions.toLocaleString()} icon="👁" />
                            <KpiCard label={__('Clicks', 'shois-chat-button')} value={fakeData.clicks.toLocaleString()} icon="👆" />
                            <KpiCard label={__('CTR', 'shois-chat-button')} value={fakeData.ctr + '%'} icon="📈" />
                            <KpiCard label={__('Mobile', 'shois-chat-button')} value={fakeMobilePct + '%'} icon="📱" />
                        </div>
                        <div className="shcb-modern-card">
                            <div className="shcb-modern-card-header"><span>📈</span><h3>{__('Daily Overview', 'shois-chat-button')}</h3></div>
                            <MiniChart data={fakeData.daily} />
                        </div>
                        <div className="shcb-analytics-columns">
                            <div className="shcb-modern-card">
                                <div className="shcb-modern-card-header"><span>💬</span><h3>{__('Top Platforms', 'shois-chat-button')}</h3></div>
                                <PlatformBreakdown platforms={fakeData.platform_clicks} />
                            </div>
                            <div className="shcb-modern-card">
                                <div className="shcb-modern-card-header"><span>📱</span><h3>{__('Device Breakdown', 'shois-chat-button')}</h3></div>
                                <div className="shcb-device-breakdown">
                                    <div className="shcb-device-bar"><div className="shcb-device-mobile" style={{ width: fakeMobilePct + '%' }} /></div>
                                    <div className="shcb-device-labels">
                                        <span>📱 {__('Mobile', 'shois-chat-button')}: {fakeData.devices.mobile}</span>
                                        <span>🖥 {__('Desktop', 'shois-chat-button')}: {fakeData.devices.desktop}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    if (loading) {
        return (
            <div className="shcb-analytics-page">
                <div className="shcb-loading">{__('Loading analytics...', 'shois-chat-button')}</div>
            </div>
        );
    }

    const isValidData = data && !data.code && data.devices;
    const summary = isValidData ? data : {
        impressions: 0,
        clicks: 0,
        ctr: 0,
        platform_clicks: {},
        devices: { mobile: 0, desktop: 0 },
        daily: [],
    };

    const totalDevices = summary.devices.mobile + summary.devices.desktop;
    const mobilePercent = totalDevices > 0 ? Math.round((summary.devices.mobile / totalDevices) * 100) : 0;

    return (
        <div className="shcb-analytics-page">
            <div className="shcb-modern-card">
                <div className="shcb-modern-card-header">
                    <span>📊</span>
                    <h3>{__('Analytics', 'shois-chat-button')}</h3>
                    <div className="shcb-period-selector">
                        {[7, 30, 90].map((p) => (
                            <button
                                key={p}
                                className={`shcb-period-btn ${period === p ? 'shcb-period-btn-active' : ''}`}
                                onClick={() => setPeriod(p)}
                                type="button"
                            >
                                {p}{__('d', 'shois-chat-button')}
                            </button>
                        ))}
                    </div>
                </div>
            </div>

            { /* KPI Cards */}
            <div className="shcb-kpi-grid">
                <KpiCard label={__('Impressions', 'shois-chat-button')} value={summary.impressions.toLocaleString()} icon="👁" />
                <KpiCard label={__('Clicks', 'shois-chat-button')} value={summary.clicks.toLocaleString()} icon="👆" />
                <KpiCard label={__('CTR', 'shois-chat-button')} value={summary.ctr + '%'} icon="📈" />
                <KpiCard label={__('Mobile', 'shois-chat-button')} value={mobilePercent + '%'} icon="📱" />
            </div>

            { /* Chart */}
            <div className="shcb-modern-card">
                <div className="shcb-modern-card-header">
                    <span>📈</span>
                    <h3>{__('Daily Overview', 'shois-chat-button')}</h3>
                </div>
                <MiniChart data={summary.daily} />
            </div>

            { /* Platform Breakdown */}
            <div className="shcb-analytics-columns">
                <div className="shcb-modern-card">
                    <div className="shcb-modern-card-header">
                        <span>💬</span>
                        <h3>{__('Top Platforms', 'shois-chat-button')}</h3>
                    </div>
                    <PlatformBreakdown platforms={summary.platform_clicks} />
                </div>

                <div className="shcb-modern-card">
                    <div className="shcb-modern-card-header">
                        <span>📱</span>
                        <h3>{__('Device Breakdown', 'shois-chat-button')}</h3>
                    </div>
                    <div className="shcb-device-breakdown">
                        <div className="shcb-device-bar">
                            <div className="shcb-device-mobile" style={{ width: mobilePercent + '%' }} />
                        </div>
                        <div className="shcb-device-labels">
                            <span>📱 {__('Mobile', 'shois-chat-button')}: {summary.devices.mobile}</span>
                            <span>🖥 {__('Desktop', 'shois-chat-button')}: {summary.devices.desktop}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
