"use client";

import { useState } from "react";
import { ChevronDown, ChevronRight } from "lucide-react";
import type { ConversionHeatMap } from "@/lib/audit/types";

interface Props {
  conversionHeatMap: ConversionHeatMap | null | undefined;
}

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

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

// ─── Region heatmap grid ──────────────────────────────────────────────────────

const Y_LABELS = ["Header / Nav", "Hero Area", "Upper Content", "Mid Content", "Lower Content", "Footer"];
const X_LABELS = ["left", "center", "right"];

type RegionCell = ConversionHeatMap["perPage"][number]["clickDensityRegions"][number];

function buildGrid(regions: ConversionHeatMap["perPage"][number]["clickDensityRegions"]): (RegionCell | null)[][] {
  const grid: (RegionCell | null)[][] = Y_LABELS.map(() => X_LABELS.map(() => null));
  for (const r of regions) {
    const yIdx = Y_LABELS.findIndex((y) => r.regionLabel.startsWith(y));
    const xIdx = r.regionLabel.includes("(left)") ? 0 : r.regionLabel.includes("(right)") ? 2 : 1;
    if (yIdx >= 0) grid[yIdx][xIdx] = r;
  }
  return grid;
}

function intensityBg(sharePercent: number, hasConversionPath: boolean): string {
  if (sharePercent === 0) return "bg-slate-50";
  if (hasConversionPath) {
    if (sharePercent >= 30) return "bg-emerald-400";
    if (sharePercent >= 15) return "bg-emerald-300";
    if (sharePercent >= 5) return "bg-emerald-200";
    return "bg-emerald-100";
  }
  if (sharePercent >= 30) return "bg-amber-400";
  if (sharePercent >= 15) return "bg-amber-300";
  if (sharePercent >= 5) return "bg-amber-200";
  return "bg-amber-100";
}

function HeatmapGrid({ regions }: { regions: ConversionHeatMap["perPage"][number]["clickDensityRegions"] }) {
  const grid = buildGrid(regions);
  return (
    <div className="rounded-lg overflow-hidden border border-slate-100">
      <div className="grid grid-cols-3 gap-px bg-slate-100">
        {grid.map((row, yIdx) =>
          row.map((cell, xIdx) => (
            <div
              key={`${yIdx}-${xIdx}`}
              title={cell ? `${cell.regionLabel ?? ""}: ${cell.clickCount} clicks (${cell.sharePercent}%)` : "No data"}
              className={`relative h-10 flex items-center justify-center text-[9px] font-medium transition-colors ${
                cell ? intensityBg(cell.sharePercent, cell.hasConversionPath) : "bg-slate-50"
              }`}
            >
              {cell && cell.sharePercent > 0 && (
                <span className={`${cell.sharePercent >= 15 ? "text-white" : "text-slate-600"}`}>
                  {cell.sharePercent}%
                </span>
              )}
              {cell?.hasConversionPath && (
                <span className="absolute top-0.5 right-0.5 w-1.5 h-1.5 rounded-full bg-emerald-600" title="Leads to conversion" />
              )}
            </div>
          ))
        )}
      </div>
      <div className="flex text-[9px] text-slate-400 divide-x divide-slate-100">
        {["Left", "Center", "Right"].map((x) => (
          <div key={x} className="flex-1 text-center py-0.5">{x}</div>
        ))}
      </div>
    </div>
  );
}

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

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

// ─── Page type badge ──────────────────────────────────────────────────────────

const PAGE_TYPE_BADGE: Record<string, string> = {
  homepage: "bg-violet-50 text-violet-700 border-violet-200",
  service:  "bg-blue-50 text-blue-700 border-blue-200",
  product:  "bg-amber-50 text-amber-700 border-amber-200",
  contact:  "bg-emerald-50 text-emerald-700 border-emerald-200",
  other:    "bg-slate-50 text-slate-500 border-slate-200",
};

// ─── Per-page card ────────────────────────────────────────────────────────────

function PageCard({ page }: { page: ConversionHeatMap["perPage"][number] }) {
  const [open, setOpen] = useState(false);
  const typeBadge = PAGE_TYPE_BADGE[page.pageType] ?? PAGE_TYPE_BADGE.other;

  return (
    <div className="rounded-lg border border-slate-200 overflow-hidden">
      {/* Card header — always visible */}
      <button
        onClick={() => setOpen((o) => !o)}
        className="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-slate-50 transition-colors"
      >
        <span className="shrink-0 text-slate-400">{open ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}</span>
        <span className="flex-1 min-w-0">
          <span className="font-mono text-sm text-slate-700 truncate block">{urlPath(page.pageUrl)}</span>
          <span className="text-xs text-slate-400">{page.totalClicks.toLocaleString()} clicks · {page.totalSessions.toLocaleString()} sessions · {page.clicksPerSession} clicks/session</span>
        </span>
        <span className={`shrink-0 text-[10px] font-semibold px-2 py-0.5 rounded-full border capitalize ${typeBadge}`}>
          {page.pageType}
        </span>
      </button>

      {open && (
        <div className="border-t border-slate-100 px-4 pb-4 pt-3 space-y-5">
          {/* Heatmap grid + top elements side-by-side */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {/* Region heatmap */}
            <div>
              <p className="text-xs font-semibold text-slate-500 mb-2 uppercase tracking-wide">Click Density Map</p>
              <HeatmapGrid regions={page.clickDensityRegions} />
              <div className="flex items-center gap-3 mt-2 text-[10px] text-slate-400">
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-emerald-300 inline-block" /> Conversion path</span>
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-amber-300 inline-block" /> High engagement</span>
                <span className="flex items-center gap-1"><span className="w-3 h-3 rounded-sm bg-slate-100 inline-block" /> Low engagement</span>
              </div>
            </div>

            {/* Top clicked elements */}
            <div>
              <p className="text-xs font-semibold text-slate-500 mb-2 uppercase tracking-wide">Top Clicked Elements</p>
              <div className="space-y-1.5">
                {page.topClickedElements.slice(0, 6).map((el, i) => (
                  <div key={i} className="flex items-center gap-2">
                    <span className="text-xs text-slate-400 w-4 shrink-0">{i + 1}</span>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs text-slate-700 truncate">{el.elementLabel}</p>
                    </div>
                    <span className="text-xs font-medium text-slate-600 shrink-0">{el.clickCount.toLocaleString()}</span>
                    {el.conversionContribution > 0 && (
                      <span className="text-[10px] font-medium text-emerald-600 shrink-0">{el.conversionContributionPercent}% conv</span>
                    )}
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Dead zones */}
          {page.deadZones.length > 0 && (
            <div>
              <p className="text-xs font-semibold text-red-500 mb-2 uppercase tracking-wide">Dead Zones</p>
              <div className="space-y-2">
                {page.deadZones.map((z, i) => (
                  <div key={i} className="rounded-lg border border-red-100 bg-red-50 px-3 py-2">
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-xs font-medium text-red-700">{z.regionLabel}</p>
                      <span className="text-[10px] text-red-500">{z.missedClickRatio}:1 view-to-click</span>
                    </div>
                    <p className="text-xs text-red-600 mt-1">{z.recommendation}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Hot zones */}
          {page.hotZones.length > 0 && (
            <div>
              <p className="text-xs font-semibold text-emerald-600 mb-2 uppercase tracking-wide">Hot Zones</p>
              <div className="space-y-2">
                {page.hotZones.map((z, i) => (
                  <div key={i} className="rounded-lg border border-emerald-100 bg-emerald-50 px-3 py-2">
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-xs font-medium text-emerald-700">{z.regionLabel}</p>
                      <span className="text-[10px] text-emerald-600">{z.clickCount.toLocaleString()} clicks</span>
                    </div>
                    <p className="text-xs text-emerald-700 mt-1">{z.recommendation}</p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Recommended CTA placements */}
          {page.recommendedCtaPlacements.length > 0 && (
            <div>
              <p className="text-xs font-semibold text-amber-600 mb-2 uppercase tracking-wide">Recommended CTA Placements</p>
              <div className="space-y-2">
                {page.recommendedCtaPlacements.map((r, i) => (
                  <div key={i} className="rounded-lg border border-amber-100 bg-amber-50 px-3 py-2">
                    <p className="text-xs font-medium text-amber-800">{r.regionLabel}</p>
                    <p className="text-xs text-amber-700 mt-0.5">{r.rationale}</p>
                    <p className="text-[10px] text-amber-600 mt-1 italic">{r.expectedLift}</p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─── Placeholder (no click data) ──────────────────────────────────────────────

function NoClickDataPlaceholder() {
  return (
    <div className="rounded-xl border border-amber-200 bg-amber-50 p-6">
      <p className="text-sm font-semibold text-amber-800 mb-3">Click Event Capture Not Detected</p>
      <ul className="space-y-2 text-sm text-amber-700">
        <li>• Click capture requires Site Tag v2 or later with the heatmap module enabled</li>
        <li>• Enables: click density heatmaps, CTA placement recommendations, dead zone detection</li>
        <li>• Action: confirm Site Tag installation includes click capture configuration</li>
      </ul>
      <p className="text-xs text-amber-600 mt-3">Once click data starts flowing, this section will populate automatically within 24 hours.</p>
    </div>
  );
}

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

export function ConversionHeatMapSection({ conversionHeatMap: chm }: Props) {
  if (!chm) return null;

  const confidence = CONFIDENCE_BADGE[chm.dataConfidence] ?? CONFIDENCE_BADGE.low;

  return (
    <section id="audit-conversion-heat-map" className="scroll-mt-20">
      <div className="rounded-xl border border-slate-200 bg-white shadow-sm overflow-hidden">
        {/* Header */}
        <div className="px-6 py-5 border-b border-slate-100">
          <div className="flex items-start justify-between gap-4">
            <div>
              <h2 className="text-lg font-semibold text-slate-900">Conversion Heat Map</h2>
              <p className="mt-0.5 text-sm text-slate-500">Where visitors actually click vs where CTAs exist — last {chm.windowDays} days</p>
            </div>
            {chm.hasClickData && (
              <span className={`shrink-0 text-xs font-semibold px-2.5 py-1 rounded-full border ${confidence.cls}`}>
                {confidence.label}
              </span>
            )}
          </div>
        </div>

        <div className="p-6 space-y-6">
          {!chm.hasClickData ? (
            <NoClickDataPlaceholder />
          ) : (
            <>
              {/* Per-page cards */}
              {chm.perPage.length > 0 && (
                <div>
                  <h3 className="text-sm font-semibold text-slate-700 mb-3">Page-Level Click Analysis</h3>
                  <div className="space-y-3">
                    {chm.perPage.map((page) => (
                      <PageCard key={page.pageUrl} page={page} />
                    ))}
                  </div>
                </div>
              )}

              {/* Aggregate insights */}
              {chm.aggregateInsights.length > 0 && (
                <div>
                  <h3 className="text-sm font-semibold text-slate-700 mb-3">Cross-Page Patterns</h3>
                  <div className="space-y-3">
                    {chm.aggregateInsights.map((ins, i) => (
                      <div key={i} className="rounded-lg border border-slate-100 bg-slate-50 p-4">
                        <p className="text-sm text-slate-700 leading-relaxed">{ins.insight}</p>
                        {ins.affectedPages.length > 0 && (
                          <p className="text-xs text-slate-400 mt-1.5">
                            Affected: {ins.affectedPages.slice(0, 4).join(", ")}
                            {ins.affectedPages.length > 4 ? ` +${ins.affectedPages.length - 4} more` : ""}
                          </p>
                        )}
                        <p className="text-xs text-indigo-600 mt-1.5 font-medium">{ins.actionRecommendation}</p>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Patent relevance */}
              <p className="text-xs text-slate-400 italic">{chm.patentRelevance}</p>
            </>
          )}
        </div>
      </div>
    </section>
  );
}
