// components/PdfInsights.jsx
import React, { useEffect, useState } from 'react';
import { Eye, Users, Clock, BookOpenCheck, Crown, ArrowUpRight } from 'lucide-react';
import { fetchAnalytics } from '../api/pdfs';
import { isPro } from '../utils/shortcode';
import { formatDuration } from './AnalyticsPage';
import PageAttention from './PageAttention';

/** Analytics tab of the PDF details panel (Pro). */
const PdfInsights = ({ pdfId, onOpenAnalytics }) => {
    const pro = isPro();
    const [totals, setTotals] = useState(null);

    useEffect(() => {
        if (!pro) return;
        fetchAnalytics(30, pdfId).then((res) => setTotals(res.data.totals)).catch(() => setTotals(false));
    }, [pro, pdfId]);

    if (!pro) {
        return (
            <div className="rounded-xl border border-amber-200 bg-gradient-to-br from-amber-50 to-white p-5 text-sm text-amber-900">
                <p className="flex items-center gap-1.5 font-semibold"><Crown className="size-4" /> Reading analytics is part of PDF Rack Pro</p>
                <p className="mt-1 text-amber-800/80">See views, reading time, how far people read and which pages hold their attention.</p>
                {window.pdfRack?.upgradeUrl && (
                    <a href={window.pdfRack.upgradeUrl} className="mt-2 inline-block font-semibold text-amber-700 underline underline-offset-2">Upgrade now →</a>
                )}
            </div>
        );
    }

    const tiles = totals ? [
        [Eye, 'Views', totals.views],
        [Users, 'Visitors', totals.visitors],
        [Clock, 'Avg. time', formatDuration(totals.avgDuration)],
        [BookOpenCheck, 'Read-through', `${Math.round(totals.completion * 100)}%`],
    ] : [];

    return (
        <div className="space-y-5">
            <div className="flex items-center justify-between">
                <p className="text-sm font-medium text-slate-700">Last 30 days</p>
                <a href="#analytics" onClick={() => onOpenAnalytics?.()} className="inline-flex items-center gap-1 text-xs font-semibold text-indigo-600 hover:text-indigo-800">
                    All analytics <ArrowUpRight className="size-3.5" />
                </a>
            </div>
            {totals === null ? (
                <div className="h-20 rounded-xl bg-slate-50 animate-pulse" />
            ) : totals === false ? (
                <p className="text-sm text-red-600">Could not load analytics.</p>
            ) : (
                <div className="grid grid-cols-2 gap-3">
                    {tiles.map(([Icon, label, value]) => (
                        <div key={label} className="flex items-center gap-3 rounded-xl border border-slate-200 px-3 py-2.5">
                            <span className="rounded-lg bg-indigo-50 p-1.5 text-indigo-600"><Icon className="size-4" /></span>
                            <span>
                                <span className="block text-base font-bold leading-5 text-slate-900 tabular-nums">{value}</span>
                                <span className="block text-xs text-slate-500">{label}</span>
                            </span>
                        </div>
                    ))}
                </div>
            )}
            <div className="rounded-xl border border-slate-200 p-4">
                <p className="text-sm font-medium text-slate-800">Page attention</p>
                <p className="mb-3 text-xs text-slate-500">Where readers spend their time, and where they stop reading.</p>
                <PageAttention pdfId={pdfId} days={30} />
            </div>
        </div>
    );
};

export default PdfInsights;
