'use client'

import { funnelRates } from '@/lib/domain/broker-leads'
import type { LeadsAnalytics } from '@/lib/data/broker-leads'
import { CARD } from './shared'
import { useLeadKind } from './kind-context'

const pct = (n: number, d: number) => (d > 0 ? `${((n / d) * 100).toFixed(1)}%` : '—')

/** The funnel: leads → emailed → delivered → opened → clicked → signed up → relation confirmed; by campaign, template version, state and brokerage. */
export function AnalyticsTab({ analytics: a }: { analytics: LeadsAnalytics }) {
  const cfg = useLeadKind()
  const converted = cfg.convertedLabel
  const f = a.funnel
  const r = funnelRates({ enrolled: f.leads, sent: f.emailed, delivered: f.delivered, opened: f.opened, clicked: f.clicked, signed_up: f.signed_up, converted: f.converted, bounced: f.bounced, unsubscribed: f.unsubscribed })
  const steps: Array<[string, number, string]> = [['Leads', f.leads, ''], ['Emailed', f.emailed, pct(f.emailed, f.leads)], ['Delivered', f.delivered, `${r.delivered_pct}% of emailed`], ['Opened', f.opened, `${r.open_pct}% of delivered`], ['Clicked', f.clicked, `${r.click_pct}% of delivered`], ['Signed up', f.signed_up, `${r.signup_pct}% of emailed`], [converted, f.converted, `${r.conversion_pct}% of emailed`]]
  const max = Math.max(1, f.leads)
  return (
    <div className="space-y-4">
      <div className={CARD}>
        <p className="text-xs font-bold uppercase tracking-wide text-neutral-400">Funnel · all leads</p>
        <div className="mt-3 space-y-1.5">
          {steps.map(([k, v, s]) => (
            <div key={k} className="flex items-center gap-3 text-xs"><span className="w-32 font-semibold">{k}</span><div className="h-4 flex-1 rounded bg-neutral-100"><div className="h-4 rounded bg-[#0f1b2d]" style={{ width: `${Math.max(0.5, (v / max) * 100)}%` }} /></div><span className="w-16 text-right font-bold">{v}</span><span className="w-32 text-neutral-500">{s}</span></div>
          ))}
        </div>
        <p className="mt-3 text-xs text-neutral-500">Bounced {f.bounced} ({r.bounce_pct}% of emailed) · unsubscribed {f.unsubscribed}. Keep the bounce rate under 2% and complaints under 0.1% to protect the sending domain.</p>
      </div>
      <div className="grid gap-4 lg:grid-cols-2">
        <Table title="By campaign" head={['Campaign', 'Status', 'Sent', 'Delivered', 'Opened', 'Clicked', 'Signed up', converted, 'Bounced', 'Unsub']} rows={a.byCampaign.map((c) => [c.name, c.status, c.sent, `${c.delivered} (${pct(c.delivered, c.sent)})`, `${c.opened} (${pct(c.opened, c.delivered)})`, `${c.clicked} (${pct(c.clicked, c.delivered)})`, `${c.signed_up} (${pct(c.signed_up, c.sent)})`, `${c.converted} (${pct(c.converted, c.sent)})`, c.bounced, c.unsubscribed])} />
        <Table title="By template version (last 30 days)" head={['Template', 'Version', 'Sent', 'Delivered', 'Opened', 'Clicked']} rows={a.byTemplate.map((t) => [t.template_key, t.version ?? 0, t.sent, `${t.delivered} (${pct(t.delivered, t.sent)})`, `${t.opened} (${pct(t.opened, t.delivered)})`, `${t.clicked} (${pct(t.clicked, t.delivered)})`])} />
        <Table title="By state" head={['State', 'Leads', 'Emailed', 'Signed up', converted]} rows={a.byState.slice(0, 30).map((s) => [s.state, s.leads, s.emailed, s.signed_up, `${s.converted} (${pct(s.converted, s.leads)})`])} />
        <Table title={cfg.kind === 'carrier' ? 'Top companies' : 'Top brokerages'} head={[cfg.kind === 'carrier' ? 'Company' : 'Brokerage', 'Leads', 'Emailed', 'Signed up', converted]} rows={a.byBrokerage.slice(0, 30).map((b) => [b.name, b.leads, b.emailed, b.signed_up, `${b.converted} (${pct(b.converted, b.leads)})`])} />
      </div>
      <Table title="Last 30 days, by day" head={['Day', 'Sent', 'Delivered', 'Opened', 'Clicked', 'Signed up']} rows={a.last30.map((d) => [d.day, d.sent, d.delivered, d.opened, d.clicked, d.signed_up])} />
    </div>
  )
}

function Table({ title, head, rows }: { title: string; head: string[]; rows: Array<Array<string | number>> }) {
  return (
    <div className="overflow-x-auto rounded-2xl border bg-white">
      <p className="px-4 pt-4 text-xs font-bold uppercase tracking-wide text-neutral-400">{title}</p>
      <table className="mt-2 w-full text-left text-xs">
        <thead className="text-[10px] uppercase tracking-wide text-neutral-400"><tr>{head.map((h) => <th key={h} className="px-4 py-1.5">{h}</th>)}</tr></thead>
        <tbody className="divide-y">
          {rows.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j} className={`px-4 py-1.5 ${j === 0 ? 'font-semibold' : ''}`}>{c}</td>)}</tr>)}
          {rows.length === 0 && <tr><td colSpan={head.length} className="px-4 py-4 text-neutral-500">Nothing yet.</td></tr>}
        </tbody>
      </table>
    </div>
  )
}
