"use client";

import type { RevenueAttribution } from "@/lib/audit/types";

// ─── Props ────────────────────────────────────────────────────────────────────

interface Props {
  revenueAttribution: RevenueAttribution | null | undefined;
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function fmtUsd(n: number): string {
  if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `$${(n / 1_000).toFixed(1)}K`;
  return `$${n.toLocaleString("en-US", { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
}

function fmtPct(n: number, sign = false): string {
  const prefix = sign && n > 0 ? "+" : "";
  return `${prefix}${n.toFixed(1)}%`;
}

function urlPath(url: string): string {
  let path = url;
  try { path = new URL(url).pathname || "/"; } catch { /* keep original */ }
  return path.length > 50 ? path.slice(0, 49) + "…" : path;
}

// ─── Confidence badge ─────────────────────────────────────────────────────────

const confidenceBadge: Record<string, { label: string; cls: string }> = {
  high:         { label: "High confidence",    cls: "bg-emerald-100 text-emerald-700 border border-emerald-200" },
  moderate:     { label: "Moderate confidence", cls: "bg-amber-100 text-amber-700 border border-amber-200" },
  low:          { label: "Limited data",        cls: "bg-slate-100 text-slate-500 border border-slate-200" },
  insufficient: { label: "Insufficient data",   cls: "bg-slate-100 text-slate-500 border border-slate-200" },
};

// ─── Delta indicator ──────────────────────────────────────────────────────────

function DeltaBadge({ delta, pct }: { delta: number; pct: number }) {
  if (delta === 0) return null;
  const up = delta > 0;
  return (
    <span className={`text-[10px] font-medium px-1.5 py-0.5 rounded-full ${up ? "bg-emerald-100 text-emerald-700" : "bg-red-100 text-red-600"}`}>
      {fmtPct(pct, true)}
    </span>
  );
}

// ─── Channel row ──────────────────────────────────────────────────────────────

function ChannelRow({
  row,
  isAi,
  isLast,
}: {
  row: RevenueAttribution["revenueByChannel"][number];
  isAi: boolean;
  isLast: boolean;
}) {
  return (
    <div className={`flex items-center justify-between gap-4 px-4 py-3 ${!isLast ? "border-b border-slate-100" : ""} ${isAi ? "bg-indigo-50/60" : ""}`}>
      <div className="flex items-center gap-2 min-w-0">
        {isAi && (
          <span className="inline-flex items-center gap-1 text-[10px] font-semibold text-indigo-600 bg-indigo-100 px-1.5 py-0.5 rounded-full shrink-0">
            AI
          </span>
        )}
        <span className="text-sm font-medium text-slate-800">{row.channelName}</span>
      </div>
      <div className="flex items-center gap-4 shrink-0 text-right">
        <div className="hidden sm:block">
          <p className="text-xs text-slate-400">Conversions</p>
          <p className="text-sm font-medium text-slate-700">{row.conversions}</p>
        </div>
        <div>
          <p className="text-xs text-slate-400">Avg / conversion</p>
          <p className="text-sm font-medium text-slate-700">{fmtUsd(row.avgRevenuePerConversion)}</p>
        </div>
        <div>
          <p className="text-xs text-slate-400">Share</p>
          <p className="text-sm font-medium text-slate-700">{fmtPct(row.sharePercent)}</p>
        </div>
        <div className="text-right">
          <p className="text-xs text-slate-400">Revenue</p>
          <div className="flex items-center gap-1.5 justify-end">
            <p className="text-sm font-bold text-slate-900">{fmtUsd(row.revenue)}</p>
            {row.deltaVsPrior30d && (
              <DeltaBadge delta={row.deltaVsPrior30d.revenueDelta} pct={row.deltaVsPrior30d.revenueDeltaPercent} />
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// Revenue tracking finding removed: most brands do not configure revenue events; absence is not a meaningful audit signal

// ─── Full Revenue Attribution view ────────────────────────────────────────────

function FullRevenueView({ ra }: { ra: RevenueAttribution }) {
  const badge = confidenceBadge[ra.dataConfidence] ?? confidenceBadge.low;
  const agg = ra.aggregateMetrics;

  return (
    <div id="audit-revenue-attribution" className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
      {/* Header */}
      <div className="px-6 pt-6 pb-4 border-b border-slate-100">
        <div className="flex items-start justify-between gap-4 flex-wrap">
          <div>
            <h2 className="text-lg font-bold text-slate-900">Revenue Attribution</h2>
            <p className="text-sm text-slate-500 mt-0.5">Where your revenue actually comes from, measured by the meSEO Site Tag</p>
          </div>
          <span className={`text-[11px] font-semibold px-2.5 py-1 rounded-full ${badge.cls}`}>
            {badge.label}
          </span>
        </div>
      </div>

      {/* Aggregate metrics strip */}
      <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-slate-100 border-b border-slate-100">
        {[
          { label: "Revenue Tracked", value: fmtUsd(agg.totalRevenueTracked) },
          { label: "Conversions w/ Revenue", value: agg.totalConversionsWithRevenue.toLocaleString() },
          { label: "Avg Revenue / Conversion", value: fmtUsd(agg.avgRevenuePerConversion) },
          {
            label: "Conversion Coverage",
            value: fmtPct(agg.revenueTrackingCoveragePercent),
            sub: agg.revenueTrackingCoveragePercent < 100 ? `${agg.conversionsMissingRevenue} conversions without revenue` : undefined,
          },
        ].map(({ label, value, sub }) => (
          <div key={label} className="px-4 py-4 text-center">
            <p className="text-xs text-slate-400 mb-1">{label}</p>
            <p className="text-xl font-bold text-slate-900">{value}</p>
            {sub && <p className="text-[10px] text-slate-400 mt-0.5">{sub}</p>}
          </div>
        ))}
      </div>

      <div className="divide-y divide-slate-100">
        {/* Revenue by Channel */}
        <div className="px-6 py-5">
          <h3 className="text-sm font-semibold text-slate-800 mb-3">Revenue by Channel</h3>
          <div className="rounded-xl border border-slate-200 overflow-hidden">
            {ra.revenueByChannel.map((row, i) => (
              <ChannelRow
                key={row.channelName}
                row={row}
                isAi={row.channelName === "AI"}
                isLast={i === ra.revenueByChannel.length - 1}
              />
            ))}
          </div>
          <p className="text-[10px] text-slate-400 mt-2">Period-over-period deltas vs prior {ra.windowDays}-day window where data available.</p>
        </div>

        {/* Revenue by AI Engine */}
        {ra.revenueByAiEngine.length > 0 && (
          <div className="px-6 py-5">
            <h3 className="text-sm font-semibold text-slate-800 mb-3">Revenue by AI Engine</h3>
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
              {ra.revenueByAiEngine.map((engine) => (
                <div key={engine.engineName} className="rounded-xl border border-slate-200 p-4 bg-indigo-50/30">
                  <p className="text-sm font-semibold text-slate-900 mb-2">{engine.engineName}</p>
                  <p className="text-2xl font-bold text-indigo-700 mb-1">{fmtUsd(engine.revenue)}</p>
                  <div className="space-y-1">
                    <div className="flex justify-between text-xs text-slate-500">
                      <span>Share of AI revenue</span>
                      <span className="font-medium text-slate-700">{fmtPct(engine.shareOfAiRevenuePercent)}</span>
                    </div>
                    <div className="flex justify-between text-xs text-slate-500">
                      <span>Share of total revenue</span>
                      <span className="font-medium text-slate-700">{fmtPct(engine.shareOfTotalRevenuePercent)}</span>
                    </div>
                    <div className="flex justify-between text-xs text-slate-500">
                      <span>Conversions</span>
                      <span className="font-medium text-slate-700">{engine.conversions}</span>
                    </div>
                    <div className="flex justify-between text-xs text-slate-500">
                      <span>Avg / conversion</span>
                      <span className="font-medium text-slate-700">{fmtUsd(engine.avgRevenuePerConversion)}</span>
                    </div>
                    {engine.highestRevenueLandingPage && (
                      <div className="pt-1 text-[10px] text-slate-400 border-t border-slate-100 mt-1">
                        Top page: {urlPath(engine.highestRevenueLandingPage)}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Top Revenue Pages */}
        {ra.topRevenuePages.length > 0 && (
          <div className="px-6 py-5">
            <h3 className="text-sm font-semibold text-slate-800 mb-3">Top Revenue Pages</h3>
            <div className="rounded-xl border border-slate-200 overflow-hidden">
              <div className="grid grid-cols-12 px-4 py-2.5 bg-slate-50 border-b border-slate-200 text-[10px] font-semibold text-slate-400 uppercase tracking-wider">
                <div className="col-span-4">Page</div>
                <div className="col-span-2 text-right">Revenue</div>
                <div className="col-span-2 text-right">Share</div>
                <div className="col-span-2 text-right hidden sm:block">Conv.</div>
                <div className="col-span-2 text-right">Avg / conv</div>
              </div>
              {ra.topRevenuePages.map((page, i) => (
                <div
                  key={page.pageUrl}
                  className={`grid grid-cols-12 px-4 py-2.5 text-sm ${i % 2 === 0 ? "" : "bg-slate-50/60"} ${i < ra.topRevenuePages.length - 1 ? "border-b border-slate-100" : ""}`}
                >
                  <div className="col-span-4 text-slate-700 font-mono text-xs truncate" title={page.pageUrl}>
                    {urlPath(page.pageUrl)}
                  </div>
                  <div className="col-span-2 text-right font-bold text-slate-900">{fmtUsd(page.revenue)}</div>
                  <div className="col-span-2 text-right text-slate-500">{fmtPct(page.sharePercent)}</div>
                  <div className="col-span-2 text-right text-slate-500 hidden sm:block">{page.conversions}</div>
                  <div className="col-span-2 text-right text-slate-500">{fmtUsd(page.avgRevenuePerConversion)}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Insights */}
        {ra.insights.length > 0 && (
          <div className="px-6 py-5">
            <h3 className="text-sm font-semibold text-slate-800 mb-3">Revenue Insights</h3>
            <div className="space-y-3">
              {ra.insights.map((ins, i) => (
                <div key={i} className="rounded-xl bg-slate-50 border border-slate-100 p-4">
                  <p className="text-sm text-slate-800 font-medium mb-1">{ins.insight}</p>
                  <p className="text-xs text-slate-500 mb-1">{ins.supportingMetric}</p>
                  <p className="text-xs text-indigo-600">{ins.businessImplication}</p>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Patent relevance */}
        <div className="px-6 py-4">
          <p className="text-xs text-slate-400 italic">{ra.patentRelevance}</p>
        </div>

        {/* Future capabilities */}
        <div className="px-6 py-4 bg-slate-50">
          <p className="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Coming Soon</p>
          <div className="space-y-1.5 text-xs text-slate-400">
            <p>{ra.futureCapabilities.cacNote}</p>
            <p>{ra.futureCapabilities.ltvNote}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Main export ──────────────────────────────────────────────────────────────

export function RevenueAttributionSection({ revenueAttribution }: Props) {
  if (revenueAttribution == null) return null;
  return <FullRevenueView ra={revenueAttribution} />;
}
