'use client';
import {useEffect,useMemo,useState} from 'react';
import Link from 'next/link';
import {ArrowLeft,BarChart3,RefreshCw} from 'lucide-react';
import {WorkspaceShell} from '@/components/workspace-shell';
import {Button} from '@/components/ui/button';

type Totals=Record<'page_view'|'link_click'|'checkout_start'|'checkout_created'|'checkout_paid'|'larp_created',number>;
type Day={date:string}&Totals;
type Report={days:number;totals:Totals;byDay:Day[];destinations:{destination:string;clicks:number}[];affiliate:{clicks:number;startedCheckouts:number;paidConversions:number};usersTotal:number;lastEvents:{id:string;kind:string;at:string;path?:string;destination?:string}[]};
const boxes:[keyof Totals,string][]=[['page_view','Page views'],['link_click','Site link clicks'],['checkout_start','Checkout attempts'],['checkout_created','Stripe checkout opened'],['checkout_paid','Verified paid checkouts'],['larp_created','LARPs created']];
export function InsightsBoard(){
 const[days,setDays]=useState(30),[report,setReport]=useState<Report|null>(null),[error,setError]=useState(''),[loading,setLoading]=useState(true);
 useEffect(()=>{let alive=true;setLoading(true);void fetch(`/api/studio/insights?days=${days}`,{cache:'no-store'}).then(async r=>{const x=await r.json();if(!r.ok)throw Error(x.error||'Unable to read insights');if(alive){setReport(x);setError('')}}).catch(e=>{if(alive)setError((e as Error).message)}).finally(()=>{if(alive)setLoading(false)});return()=>{alive=false}},[days]);
 const chart=useMemo(()=>report?.byDay||[],[report]);const max=Math.max(1,...chart.map(d=>d.page_view+d.link_click));
 return <WorkspaceShell title="Owner Studio · Insights" description="Website activity and the checkout funnel, counted from this deployment." actions={<Button variant="outline" asChild><Link href="/developer"><ArrowLeft size={16}/> Owner Studio</Link></Button>}>
 <div className="max-w-7xl mx-auto space-y-5 min-w-0"><div className="glass-panel p-4 flex items-center justify-between gap-4 flex-wrap"><div className="flex items-center gap-2 text-sm font-semibold"><BarChart3 size={18}/> Performance overview</div><div className="flex gap-2">{[7,30,90].map(n=><Button size="sm" key={n} variant={days===n?'gradient':'outline'} onClick={()=>setDays(n)}>{n} days</Button>)}</div></div>
 {error?<section className="glass-panel p-6 text-red-500">{error}</section>:!report?<section className="glass-panel p-6">{loading?'Loading insights…':'No data yet.'}</section>:<>
 <div className="grid grid-cols-2 md:grid-cols-3 gap-3">{boxes.map(([key,label])=><section key={key} className="glass-panel p-4 md:p-5 min-w-0"><div className="text-xs text-muted-foreground">{label}</div><div className="text-2xl md:text-3xl font-black tabular-nums mt-2">{report.totals[key].toLocaleString()}</div></section>)}</div>
 <section className="glass-panel p-5 space-y-4"><h2 className="font-bold">Visits and link clicks over time</h2><div className="flex items-end gap-[2px] h-36 w-full" role="img" aria-label="Daily visits and link-click bars">{chart.map(d=><div key={d.date} className="group relative flex-1 min-w-0 flex h-full items-end gap-px" title={`${d.date}: ${d.page_view} visits, ${d.link_click} clicks`}><div className="bg-violet-500/80 rounded-t-sm flex-1" style={{height:`${Math.max(2,d.page_view/max*100)}%`}}/><div className="bg-sky-400/90 rounded-t-sm flex-1" style={{height:`${Math.max(2,d.link_click/max*100)}%`}}/></div>)}</div><p className="text-xs text-muted-foreground">Purple = page views · Blue = internal link clicks. Counts may include repeat visits and automated traffic.</p></section>
 <div className="grid lg:grid-cols-2 gap-4"><section className="glass-panel p-5"><h2 className="font-bold">Checkout funnel</h2><div className="space-y-3 mt-4">{[['Started on site',report.totals.checkout_start],['Stripe checkout created',report.totals.checkout_created],['Paid, confirmed by Stripe',report.totals.checkout_paid]].map(([label,value])=><div key={label}><div className="flex justify-between text-sm gap-3"><span>{label}</span><b>{value}</b></div><div className="h-2 bg-muted rounded-full overflow-hidden mt-1"><div className="h-full bg-primary rounded-full" style={{width:`${Math.min(100,Number(value)/Math.max(report.totals.checkout_start,1)*100)}%`}}/></div></div>)}</div><p className="text-xs text-muted-foreground mt-4">Events are recorded separately; these are not unique-customer conversion rates. Stripe webhooks must be configured to verify payments.</p></section>
 <section className="glass-panel p-5"><h2 className="font-bold">Referral activity</h2><div className="grid grid-cols-3 gap-2 mt-5">{[['Affiliate clicks',report.affiliate.clicks],['Referred checkouts',report.affiliate.startedCheckouts],['Referred payments',report.affiliate.paidConversions]].map(([label,n])=><div className="bg-muted/40 rounded-xl p-3" key={label}><div className="text-xl font-bold tabular-nums">{n}</div><div className="text-xs text-muted-foreground mt-1">{label}</div></div>)}</div><p className="text-xs text-muted-foreground mt-4">{report.usersTotal} total registered accounts. Affiliate metrics use the existing referral event log.</p></section></div>
 <section className="glass-panel p-5"><h2 className="font-bold mb-3">Most-clicked internal destinations</h2>{report.destinations.length?<div className="space-y-2">{report.destinations.map(d=><div className="flex justify-between gap-4 text-sm border-b border-border py-2" key={d.destination}><span className="break-all">{d.destination}</span><b className="tabular-nums">{d.clicks}</b></div>)}</div>:<p className="text-sm text-muted-foreground">Links will appear here after visitors click them.</p>}</section>
 <p className="text-xs text-muted-foreground">Tracking starts after this update is deployed. Historic page visits and checkout attempts cannot be reconstructed. This file-based event log is intended for modest traffic; use a database and analytics service for production-scale accuracy.</p></>}
 </div></WorkspaceShell>
}
