"use client";

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

interface Props {
  multiTouchAiPath: MultiTouchAiPath | null | undefined;
}

const STEP_TYPE_LABELS: Record<string, string> = {
  ai_engine: "AI",
  page: "Page",
  conversion: "Conv.",
};

const STEP_TYPE_COLORS: Record<string, string> = {
  ai_engine: "bg-violet-100 text-violet-800 border-violet-200",
  page: "bg-slate-100 text-slate-700 border-slate-200",
  conversion: "bg-emerald-100 text-emerald-800 border-emerald-200",
};

function Bar({ percent, color }: { percent: number; color: string }) {
  return (
    <div className="h-2 w-full rounded-full bg-slate-100 overflow-hidden">
      <div className={`h-full rounded-full ${color}`} style={{ width: `${Math.min(100, percent)}%` }} />
    </div>
  );
}

export function MultiTouchAiPathSection({ multiTouchAiPath }: Props) {
  if (!multiTouchAiPath) return null;

  const { topConversionPaths, pathComplexityDistribution, topEntryChannels, topConversionTriggers, crossDeviceJourneys } = multiTouchAiPath;
  const dist = pathComplexityDistribution;

  return (
    <section id="audit-multi-touch-paths" className="space-y-8">
      <div>
        <h2 className="text-2xl font-bold text-slate-900 mb-1">Multi-Touch AI Path Analysis</h2>
        <p className="text-slate-500 text-sm">First-party visitor journey reconstruction from AI engine referral through conversion.</p>
      </div>

      {/* Cross-Device Detection callout */}
      {crossDeviceJourneys.detected > 0 && (
        <div className="rounded-xl border border-violet-200 bg-violet-50 px-5 py-4 flex items-start gap-3">
          <span className="mt-0.5 text-violet-500 text-lg">⬡</span>
          <div>
            <p className="font-semibold text-violet-900 text-sm">Cross-Device Journeys Detected</p>
            <p className="text-violet-700 text-sm mt-0.5">
              {crossDeviceJourneys.detected} journeys ({crossDeviceJourneys.percentOfConversions}% of AI conversions) span multiple devices.
              Avg. {crossDeviceJourneys.avgDaysSpanned} days. Typical pattern: {crossDeviceJourneys.typicalPattern}
            </p>
          </div>
        </div>
      )}

      {/* Path Complexity Distribution */}
      <div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
        <h3 className="font-semibold text-slate-900 mb-4">Path Complexity Distribution</h3>
        <div className="space-y-4">
          <div>
            <div className="flex justify-between text-sm mb-1">
              <span className="text-slate-600">Single-touch</span>
              <span className="font-medium text-slate-900">{dist.singleTouch.count} <span className="text-slate-400 font-normal">({dist.singleTouch.percent}%)</span></span>
            </div>
            <Bar percent={dist.singleTouch.percent} color="bg-emerald-400" />
          </div>
          <div>
            <div className="flex justify-between text-sm mb-1">
              <span className="text-slate-600">Two-touch</span>
              <span className="font-medium text-slate-900">{dist.twoTouch.count} <span className="text-slate-400 font-normal">({dist.twoTouch.percent}%)</span></span>
            </div>
            <Bar percent={dist.twoTouch.percent} color="bg-blue-400" />
          </div>
          <div>
            <div className="flex justify-between text-sm mb-1">
              <span className="text-slate-600">Multi-touch (3+)</span>
              <span className="font-medium text-slate-900">{dist.multiTouch.count} <span className="text-slate-400 font-normal">({dist.multiTouch.percent}%)</span></span>
            </div>
            <Bar percent={dist.multiTouch.percent} color="bg-violet-400" />
          </div>
        </div>
        {dist.singleTouch.avgConversionRate > 0 && (
          <p className="mt-3 text-xs text-slate-400">Overall AI conversion rate: {dist.singleTouch.avgConversionRate}%</p>
        )}
      </div>

      {/* Top Conversion Paths */}
      {topConversionPaths.length > 0 && (
        <div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
          <h3 className="font-semibold text-slate-900 mb-4">Top Conversion Paths</h3>
          <div className="space-y-4">
            {topConversionPaths.map((path, i) => (
              <div key={i} className="border border-slate-100 rounded-lg p-4">
                <div className="flex items-start justify-between gap-4 mb-3">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-1.5">
                      {path.pathSteps.map((step, j) => (
                        <span key={j} className="flex items-center gap-1">
                          {j > 0 && <span className="text-slate-300 text-xs">→</span>}
                          <span className={`inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium border ${STEP_TYPE_COLORS[step.stepType] ?? "bg-slate-100 text-slate-700 border-slate-200"}`}>
                            <span className="mr-1 opacity-60">{STEP_TYPE_LABELS[step.stepType]}</span>
                            {step.identifier.length > 24 ? step.identifier.slice(0, 24) + "…" : step.identifier}
                          </span>
                        </span>
                      ))}
                    </div>
                  </div>
                  <div className="flex flex-col items-end shrink-0">
                    <span className="text-slate-900 font-semibold text-sm">{path.conversionCount}</span>
                    <span className="text-slate-400 text-xs">conversions</span>
                  </div>
                </div>
                <div className="flex gap-4 text-xs text-slate-500">
                  {path.avgTimeToConversion > 0 && (
                    <span>Avg. {path.avgTimeToConversion < 60 ? `${path.avgTimeToConversion}s` : `${Math.round(path.avgTimeToConversion / 60)}m`} to convert</span>
                  )}
                  <span>{path.sessionsInvolved} sessions</span>
                  {path.crossDevice && <span className="text-violet-600 font-medium">Cross-device</span>}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Top Entry Channels + Top Conversion Triggers side-by-side */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Entry Channels */}
        {topEntryChannels.length > 0 && (
          <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 className="font-semibold text-slate-900 mb-3 text-sm">Top AI Entry Channels</h3>
            <div className="space-y-2.5">
              {topEntryChannels.map((ch, i) => (
                <div key={i} className="flex items-center justify-between gap-2">
                  <span className="text-slate-700 text-sm truncate">{ch.channel}</span>
                  <div className="flex items-center gap-3 shrink-0 text-xs text-slate-500">
                    <span title="First-touch conversions" className="text-slate-900 font-medium">{ch.conversionsAsFirstTouch}</span>
                    <span>/</span>
                    <span title="Last-touch conversions">{ch.conversionsAsLastTouch}</span>
                  </div>
                </div>
              ))}
            </div>
            <p className="mt-3 text-xs text-slate-400">First-touch / last-touch conversions per channel</p>
          </div>
        )}

        {/* Conversion Triggers */}
        {topConversionTriggers.length > 0 && (
          <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
            <h3 className="font-semibold text-slate-900 mb-3 text-sm">Top Conversion Triggers</h3>
            <div className="space-y-2.5">
              {topConversionTriggers.map((trig, i) => (
                <div key={i} className="flex items-start gap-2">
                  <span className="text-slate-400 text-xs mt-0.5 shrink-0">{i + 1}.</span>
                  <div className="flex-1 min-w-0">
                    <p className="text-xs text-slate-700 truncate" title={trig.pageUrl}>
                      {(() => { try { return new URL(trig.pageUrl).pathname || "/"; } catch { return trig.pageUrl.slice(0, 40); } })()}
                    </p>
                    <div className="flex items-center gap-2 text-xs text-slate-400 mt-0.5">
                      <span>{trig.conversionCount} conversions</span>
                      {trig.avgPriorPageviews > 0 && <span>· {trig.avgPriorPageviews} avg prior pages</span>}
                      {trig.topReferringEngines.length > 0 && <span>· via {trig.topReferringEngines[0]}</span>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
