"use client";

import { Share2, Globe, Tag, TrendingUp, BarChart3 } from "lucide-react";
import { CardShell } from "./_shared";

// ─── Types ──────────────────────────────────────────────────────────────────

interface TrafficData {
  pageViews: number;
  sessions: number;
  byReferrer: Array<{ source: string; views: number }>;
  byUtmSource: Array<{ source: string; views: number }>;
}

interface ConvSummary {
  totalConversions: number;
  byUtmSource: Array<{ source: string; conversions: number }>;
}

export interface AttributionTabProps {
  traffic: TrafficData | null;
  conversions: ConvSummary | null;
  hasTag: boolean;
}

// Ordered palette — top (largest share) gets the boldest color.
const BAR_PALETTE = [
  { bar: "bg-indigo-500", bg: "bg-indigo-50", text: "text-indigo-700" },
  { bar: "bg-blue-500", bg: "bg-blue-50", text: "text-blue-700" },
  { bar: "bg-cyan-500", bg: "bg-cyan-50", text: "text-cyan-700" },
  { bar: "bg-teal-500", bg: "bg-teal-50", text: "text-teal-700" },
  { bar: "bg-emerald-500", bg: "bg-emerald-50", text: "text-emerald-700" },
  { bar: "bg-lime-500", bg: "bg-lime-50", text: "text-lime-700" },
  { bar: "bg-amber-500", bg: "bg-amber-50", text: "text-amber-700" },
  { bar: "bg-orange-500", bg: "bg-orange-50", text: "text-orange-700" },
  { bar: "bg-rose-500", bg: "bg-rose-50", text: "text-rose-700" },
  { bar: "bg-slate-400", bg: "bg-slate-100", text: "text-slate-600" },
];

export function AttributionTab({ traffic, conversions, hasTag }: AttributionTabProps) {
  if (!hasTag || !traffic) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
        <Share2 className="w-10 h-10 text-slate-200 mx-auto mb-3" />
        <h2 className="text-lg font-bold text-slate-900 mb-1">Attribution</h2>
        <p className="text-sm text-slate-500 max-w-sm mx-auto">
          Install the meSEO Site Tag to see where your traffic and conversions come from.
          The tag tracks referrers, UTM parameters, and conversion attribution automatically.
        </p>
      </div>
    );
  }

  const totalViews = traffic.byReferrer.reduce((a, b) => a + b.views, 0) || traffic.pageViews || 1;
  const totalUtmViews = traffic.byUtmSource.reduce((a, b) => a + b.views, 0) || traffic.sessions || 1;
  const totalConv = conversions?.totalConversions ?? 0;

  return (
    <div className="space-y-6">

      {/* Traffic by Referrer */}
      {traffic.byReferrer.length > 0 && (
        <CardShell title="Traffic by Referrer" icon={Globe}>
          <AttributionTable
            rows={traffic.byReferrer.map((r) => ({ label: r.source, value: r.views }))}
            total={totalViews}
            valueLabel="Views"
          />
        </CardShell>
      )}

      {/* Traffic by UTM Source */}
      {traffic.byUtmSource.length > 0 && (
        <CardShell title="Traffic by UTM Source" icon={Tag}>
          <AttributionTable
            rows={traffic.byUtmSource.map((r) => ({ label: r.source, value: r.views }))}
            total={totalUtmViews}
            valueLabel="Sessions"
          />
        </CardShell>
      )}

      {/* Conversions by UTM Source */}
      {conversions && conversions.byUtmSource.length > 0 && (
        <CardShell title="Conversions by UTM Source" icon={TrendingUp}>
          <AttributionTable
            rows={conversions.byUtmSource.map((r) => ({ label: r.source, value: r.conversions }))}
            total={totalConv || 1}
            valueLabel="Conversions"
          />
        </CardShell>
      )}

      {/* Empty state */}
      {traffic.byReferrer.length === 0 && traffic.byUtmSource.length === 0 && (
        <div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
          <BarChart3 className="w-10 h-10 text-slate-200 mx-auto mb-3" />
          <h2 className="text-base font-bold text-slate-900 mb-1">No Attribution Data Yet</h2>
          <p className="text-sm text-slate-500 max-w-sm mx-auto">
            The site tag is installed but no referrer or UTM data has been collected yet.
            Traffic attribution will appear here as visitors arrive.
          </p>
        </div>
      )}
    </div>
  );
}

function AttributionTable({ rows, total, valueLabel }: {
  rows: Array<{ label: string; value: number }>;
  total: number;
  valueLabel: string;
}) {
  // Sort descending so the top contributor always gets the first palette color
  const sorted = [...rows].sort((a, b) => b.value - a.value);
  const maxPct = sorted[0] ? (sorted[0].value / total) * 100 : 0;

  return (
    <table className="w-full text-sm">
      <thead>
        <tr className="text-left text-[11px] font-semibold uppercase tracking-wider text-slate-400 border-b border-slate-100">
          <th className="px-5 py-2.5">Source</th>
          <th className="px-5 py-2.5 text-right">{valueLabel}</th>
          <th className="px-5 py-2.5 text-right">Share</th>
          <th className="px-5 py-2.5 w-[45%]"></th>
        </tr>
      </thead>
      <tbody className="divide-y divide-slate-100">
        {sorted.map((row, i) => {
          const pct = total > 0 ? (row.value / total) * 100 : 0;
          // Normalize bar width to the row with the biggest share so
          // visual proportions stay meaningful within this table.
          const barWidth = maxPct > 0 ? (pct / maxPct) * 100 : 0;
          const p = BAR_PALETTE[Math.min(i, BAR_PALETTE.length - 1)];
          return (
            <tr key={row.label} className="hover:bg-slate-50 transition-colors">
              <td className="px-5 py-3">
                <span className={`inline-flex items-center gap-2`}>
                  <span className={`w-2 h-2 rounded-full ${p.bar}`} />
                  <span className="text-sm font-medium text-slate-800 truncate max-w-[180px]">{row.label}</span>
                </span>
              </td>
              <td className="px-5 py-3 text-right font-bold text-slate-900 tabular-nums">
                {row.value.toLocaleString()}
              </td>
              <td className="px-5 py-3 text-right text-slate-500 tabular-nums">
                {pct.toFixed(1)}%
              </td>
              <td className="px-5 py-3 pr-6">
                <div className="w-full bg-slate-100 rounded-full h-2 overflow-hidden">
                  <div
                    className={`h-full rounded-full ${p.bar} transition-all`}
                    style={{ width: `${Math.max(barWidth, 2)}%` }}
                  />
                </div>
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
