"use client";

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

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

interface Props {
  bilingualAudit: BilingualAudit | null | undefined;
}

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

function urlPath(url: string): string {
  try {
    const path = new URL(url).pathname || "/";
    return path.length > 48 ? path.slice(0, 47) + "…" : path;
  } catch {
    return url.length > 48 ? url.slice(0, 47) + "…" : url;
  }
}

function pct(n: number): string {
  return `${n.toFixed(1)}%`;
}

function langLabel(code: string, displayName: string): string {
  return displayName || code.toUpperCase();
}

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

const confidenceConfig = {
  high: { label: "High confidence", class: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30" },
  moderate: { label: "Moderate confidence", class: "bg-amber-500/20 text-amber-400 border border-amber-500/30" },
  low: { label: "Limited data", class: "bg-slate-500/20 text-slate-400 border border-slate-500/30" },
};

// ─── Shared card shell ────────────────────────────────────────────────────────

function CardShell({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
  return (
    <div className="border-t border-white/10">
      <div className="px-6 py-5">
        <div className="mb-4">
          <h4 className="text-xs font-semibold text-slate-100 uppercase tracking-widest">{title}</h4>
          <p className="text-xs text-slate-400 mt-0.5">{subtitle}</p>
        </div>
        {children}
      </div>
    </div>
  );
}

// ─── Sub-section A: Language Coverage ────────────────────────────────────────

function LanguageCoverageCard({ ba }: { ba: BilingualAudit }) {
  const nonPrimary = ba.detectedLanguages.filter((l) => l.code !== ba.primaryLanguage);
  return (
    <CardShell title="Language Coverage" subtitle="Page distribution across detected languages">
      <div className="space-y-3">
        {ba.languageCoverage.perLanguage.map((lang) => {
          const meta = ba.detectedLanguages.find((d) => d.code === lang.code);
          const name = meta ? langLabel(meta.code, meta.displayName) : lang.code.toUpperCase();
          const isPrimary = lang.code === ba.primaryLanguage;
          return (
            <div key={lang.code}>
              <div className="flex items-center justify-between mb-1">
                <span className="text-xs text-slate-300">
                  {name}
                  {isPrimary && <span className="ml-2 text-[10px] text-slate-500 uppercase tracking-wider">primary</span>}
                </span>
                <span className="text-xs tabular-nums text-slate-400">
                  {lang.pageCount.toLocaleString()} pages · {pct(lang.sharePercent)}
                </span>
              </div>
              <div className="h-1.5 bg-slate-800 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full ${isPrimary ? "bg-indigo-500" : "bg-violet-400"}`}
                  style={{ width: `${Math.min(100, lang.sharePercent)}%` }}
                />
              </div>
            </div>
          );
        })}
      </div>
      {nonPrimary.length > 0 && (
        <p className="mt-4 text-xs text-slate-500">
          {nonPrimary.map((l) => langLabel(l.code, l.displayName)).join(" and ")}{" "}
          {nonPrimary.length === 1 ? "page" : "pages"} detected alongside the primary{" "}
          {langLabel(ba.primaryLanguage, ba.detectedLanguages.find((d) => d.code === ba.primaryLanguage)?.displayName ?? ba.primaryLanguage)}{" "}
          content.
        </p>
      )}
    </CardShell>
  );
}

// ─── Sub-section B: Content Parity ───────────────────────────────────────────

function ContentParityCard({ ba }: { ba: BilingualAudit }) {
  const { contentParity } = ba;
  if (contentParity.perNonPrimaryLanguage.length === 0) return null;
  return (
    <CardShell title="Content Parity" subtitle="Equivalent page coverage vs. primary language">
      <div className="space-y-6">
        {contentParity.perNonPrimaryLanguage.map((lang) => {
          const meta = ba.detectedLanguages.find((d) => d.code === lang.code);
          const name = meta ? langLabel(meta.code, meta.displayName) : lang.code.toUpperCase();
          const parityColor =
            lang.parityPercent >= 80
              ? "text-emerald-400"
              : lang.parityPercent >= 50
                ? "text-amber-400"
                : "text-red-400";
          return (
            <div key={lang.code}>
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-medium text-slate-200">{name}</span>
                <span className={`text-xs font-semibold tabular-nums ${parityColor}`}>
                  {pct(lang.parityPercent)} parity
                </span>
              </div>
              <div className="h-1.5 bg-slate-800 rounded-full overflow-hidden mb-2">
                <div
                  className={`h-full rounded-full ${lang.parityPercent >= 80 ? "bg-emerald-500" : lang.parityPercent >= 50 ? "bg-amber-500" : "bg-red-500"}`}
                  style={{ width: `${Math.min(100, lang.parityPercent)}%` }}
                />
              </div>
              <div className="flex gap-4 text-[10px] text-slate-400 mb-2">
                <span>{lang.pagesWithEquivalent} equivalent</span>
                <span className={lang.pagesMissingEquivalent > 0 ? "text-red-400" : ""}>
                  {lang.pagesMissingEquivalent} missing
                </span>
              </div>
              {lang.topMissingPages.length > 0 && (
                <div className="mt-2">
                  <p className="text-[10px] text-slate-500 mb-1.5 uppercase tracking-wider">Top missing pages</p>
                  <ul className="space-y-1">
                    {lang.topMissingPages.slice(0, 5).map((p, i) => (
                      <li key={i} className="text-[11px] text-slate-400 font-mono">
                        {urlPath(p.primaryUrl)}
                        <span className="text-slate-600"> → </span>
                        <span className="text-slate-500">{urlPath(p.expectedNonPrimaryUrl)}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </CardShell>
  );
}

// ─── Sub-section C: Hreflang Implementation ──────────────────────────────────

function HreflangCard({ ba }: { ba: BilingualAudit }) {
  const { hreflangImplementation: h } = ba;
  const statusColor =
    h.status === "complete" ? "text-emerald-400" : h.status === "partial" ? "text-amber-400" : "text-red-400";
  const statusLabel =
    h.status === "complete" ? "Complete" : h.status === "partial" ? "Partial coverage" : "Not detected";
  return (
    <CardShell title="Hreflang Implementation" subtitle="Language signal correctness for search engines">
      <div className="flex items-center gap-6 mb-4">
        <div>
          <p className={`text-lg font-bold tabular-nums ${statusColor}`}>{statusLabel}</p>
          <p className="text-[11px] text-slate-400 mt-0.5">{pct(h.coveragePercent)} page coverage</p>
        </div>
        <div className="text-xs text-slate-400 space-y-0.5">
          <p>{h.pagesWithHreflang} pages with hreflang</p>
          <p>~{h.pagesShouldHaveHreflang} pages needed</p>
          {h.bidirectionalCheckPassed != null && (
            <p>
              Bidirectional check:{" "}
              <span className={h.bidirectionalCheckPassed ? "text-emerald-400" : "text-red-400"}>
                {h.bidirectionalCheckPassed ? "passed" : "failed"}
              </span>
            </p>
          )}
        </div>
      </div>
      {h.commonBugs.length > 0 && (
        <div className="space-y-2">
          <p className="text-[10px] text-slate-500 uppercase tracking-wider">Issues detected</p>
          {h.commonBugs.map((bug, i) => (
            <div key={i} className="rounded-lg bg-slate-800/60 border border-white/5 px-4 py-3">
              <p className="text-xs font-medium text-slate-200">{bug.description}</p>
              {bug.affectedUrls.length > 0 && (
                <p className="text-[10px] text-slate-500 mt-1 font-mono">
                  e.g. {urlPath(bug.affectedUrls[0])}
                  {bug.affectedUrls.length > 1 && ` +${bug.affectedUrls.length - 1} more`}
                </p>
              )}
            </div>
          ))}
        </div>
      )}
    </CardShell>
  );
}

// ─── Sub-section D: Conversion Pathway ───────────────────────────────────────

function ConversionPathwayCard({ ba }: { ba: BilingualAudit }) {
  const cp = ba.conversionPathway;
  if (!cp || cp.perLanguage.length === 0) return null;
  return (
    <CardShell title="Conversion by Language" subtitle="Session and conversion performance per language segment (30 days)">
      <div className="overflow-x-auto">
        <table className="w-full text-xs text-left">
          <thead>
            <tr className="text-[10px] text-slate-500 uppercase tracking-wider border-b border-white/5">
              <th className="pb-2 pr-4">Language</th>
              <th className="pb-2 pr-4 text-right">Sessions</th>
              <th className="pb-2 pr-4 text-right">Conversions</th>
              <th className="pb-2 pr-4 text-right">Rate</th>
              <th className="pb-2 text-right">Top Channel</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {cp.perLanguage.map((lang) => {
              const meta = ba.detectedLanguages.find((d) => d.code === lang.code);
              const name = meta ? langLabel(meta.code, meta.displayName) : lang.code.toUpperCase();
              const topChannel = Object.entries({
                Phone: lang.channelMix.phone,
                Form: lang.channelMix.form,
                Booking: lang.channelMix.paperwork,
                Chat: lang.channelMix.chat,
              })
                .sort((a, b) => b[1] - a[1])
                .find(([, v]) => v > 0);
              return (
                <tr key={lang.code} className="text-slate-300">
                  <td className="py-2 pr-4 font-medium">{name}</td>
                  <td className="py-2 pr-4 text-right tabular-nums">{lang.sessions.toLocaleString()}</td>
                  <td className="py-2 pr-4 text-right tabular-nums">{lang.conversions.toLocaleString()}</td>
                  <td className="py-2 pr-4 text-right tabular-nums">
                    <span
                      className={
                        lang.conversionRate >= 3
                          ? "text-emerald-400"
                          : lang.conversionRate >= 1
                            ? "text-amber-400"
                            : "text-slate-400"
                      }
                    >
                      {pct(lang.conversionRate)}
                    </span>
                  </td>
                  <td className="py-2 text-right tabular-nums text-slate-400">
                    {topChannel ? `${topChannel[0]} ${pct(topChannel[1])}` : "—"}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      {cp.aiAttributed.length > 0 && (
        <div className="mt-4 pt-4 border-t border-white/5">
          <p className="text-[10px] text-slate-500 uppercase tracking-wider mb-2">AI-referred visitors by language</p>
          <div className="space-y-1">
            {cp.aiAttributed.map((lang) => {
              const meta = ba.detectedLanguages.find((d) => d.code === lang.code);
              const name = meta ? langLabel(meta.code, meta.displayName) : lang.code.toUpperCase();
              return (
                <div key={lang.code} className="flex justify-between text-xs text-slate-400">
                  <span>{name}</span>
                  <span className="tabular-nums">
                    {lang.aiVisits.toLocaleString()} visits · {pct(lang.aiConversionRate)} conv rate
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </CardShell>
  );
}

// ─── Sub-section E: AI Citation by Language ───────────────────────────────────

function AiCitationCard({ ba }: { ba: BilingualAudit }) {
  const ac = ba.aiCitationByLanguage;
  if (!ac || ac.perLanguage.length === 0) return null;
  return (
    <CardShell title="AI Citation by Language" subtitle="AI engine traffic distribution across language segments">
      <div className="space-y-5">
        {ac.perLanguage.map((lang) => {
          const meta = ba.detectedLanguages.find((d) => d.code === lang.code);
          const name = meta ? langLabel(meta.code, meta.displayName) : lang.code.toUpperCase();
          return (
            <div key={lang.code}>
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-medium text-slate-200">{name}</span>
                <span className="text-xs tabular-nums text-slate-400">
                  {lang.aiVisits.toLocaleString()} visits · {pct(lang.sharePercent)} of AI traffic
                </span>
              </div>
              {lang.topCitedPages.length > 0 && (
                <ul className="space-y-0.5 mb-2">
                  {lang.topCitedPages.slice(0, 3).map((p, i) => (
                    <li key={i} className="flex justify-between text-[11px] text-slate-400 font-mono">
                      <span>{urlPath(p.url)}</span>
                      <span className="tabular-nums">{p.aiVisits.toLocaleString()}</span>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          );
        })}
      </div>
    </CardShell>
  );
}

// ─── Sub-section F: Content Quality ──────────────────────────────────────────

function ContentQualityCard({ ba }: { ba: BilingualAudit }) {
  const { contentQuality } = ba;
  if (contentQuality.perNonPrimaryLanguage.length === 0) return null;
  return (
    <CardShell title="Content Depth & CTAs" subtitle="Word count depth and call-to-action coverage vs. primary language">
      <div className="space-y-5">
        {contentQuality.perNonPrimaryLanguage.map((lang) => {
          const meta = ba.detectedLanguages.find((d) => d.code === lang.code);
          const name = meta ? langLabel(meta.code, meta.displayName) : lang.code.toUpperCase();
          const depthColor =
            lang.depthRatio >= 0.9 ? "text-emerald-400" : lang.depthRatio >= 0.6 ? "text-amber-400" : "text-red-400";
          const ctaColor =
            lang.bilingualCtaStatus === "present"
              ? "text-emerald-400 bg-emerald-500/10 border-emerald-500/20"
              : lang.bilingualCtaStatus === "partial"
                ? "text-amber-400 bg-amber-500/10 border-amber-500/20"
                : "text-red-400 bg-red-500/10 border-red-500/20";
          const ctaLabel =
            lang.bilingualCtaStatus === "present"
              ? "CTAs present"
              : lang.bilingualCtaStatus === "partial"
                ? "Partial CTAs"
                : "CTAs absent";
          return (
            <div key={lang.code}>
              <div className="flex items-center justify-between mb-2">
                <span className="text-xs font-medium text-slate-200">{name}</span>
                <span className={`text-[10px] font-semibold border rounded-full px-2.5 py-0.5 ${ctaColor}`}>
                  {ctaLabel}
                </span>
              </div>
              <div className="flex gap-6 text-xs text-slate-400 mb-2">
                <div>
                  <span className="text-[10px] text-slate-500 uppercase tracking-wider block">Avg words</span>
                  <span className={`font-semibold tabular-nums ${depthColor}`}>{lang.avgWordCount.toLocaleString()}</span>
                  <span className="text-slate-500"> vs {lang.primaryLanguageAvgWordCount.toLocaleString()}</span>
                </div>
                <div>
                  <span className="text-[10px] text-slate-500 uppercase tracking-wider block">Depth ratio</span>
                  <span className={`font-semibold tabular-nums ${depthColor}`}>{lang.depthRatio.toFixed(2)}×</span>
                </div>
                {lang.hasLanguageSpecificSchema && (
                  <div>
                    <span className="text-[10px] text-slate-500 uppercase tracking-wider block">Schema</span>
                    <span className="text-emerald-400 font-semibold">Detected</span>
                  </div>
                )}
              </div>
              {lang.bilingualCtaRecommendation && (
                <p className="text-[11px] text-slate-400 leading-relaxed">
                  {lang.bilingualCtaRecommendation}
                </p>
              )}
            </div>
          );
        })}
      </div>
    </CardShell>
  );
}

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

export function BilingualContentSection({ bilingualAudit }: Props) {
  if (!bilingualAudit) return null;

  const ba = bilingualAudit;
  const conf = confidenceConfig[ba.dataConfidence];
  const nonPrimary = ba.detectedLanguages.filter((l) => l.code !== ba.primaryLanguage);
  const primaryMeta = ba.detectedLanguages.find((d) => d.code === ba.primaryLanguage);
  const primaryName = primaryMeta
    ? langLabel(primaryMeta.code, primaryMeta.displayName)
    : ba.primaryLanguage.toUpperCase();

  return (
    <section id="bilingual-content" className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden">
      {/* Section header */}
      <div className="px-6 py-5 border-b border-white/10 flex items-start justify-between gap-4">
        <div>
          <h3 className="text-sm font-semibold text-slate-100">Multi-Language Presence</h3>
          <p className="text-xs text-slate-400 mt-0.5">
            {primaryName} primary ·{" "}
            {nonPrimary.map((l) => langLabel(l.code, l.displayName)).join(", ")}{" "}
            {nonPrimary.length === 1 ? "audience" : "audiences"} detected
          </p>
        </div>
        <span className={`shrink-0 text-[10px] font-semibold uppercase tracking-widest px-2.5 py-1 rounded-full ${conf.class}`}>
          {conf.label}
        </span>
      </div>

      <LanguageCoverageCard ba={ba} />
      <ContentParityCard ba={ba} />
      <HreflangCard ba={ba} />
      <ConversionPathwayCard ba={ba} />
      <AiCitationCard ba={ba} />
      <ContentQualityCard ba={ba} />
    </section>
  );
}
