"use client";

/**
 * Visitor Geography card — shown on Industry Intel briefings.
 * ────────────────────────────────────────────────────────────
 * Surfaces the `sources.visitorCountries` + `sources.serviceLocations`
 * payload the server stuffs into IndustryBriefing.sources at write
 * time (see src/lib/services/industry-intel.ts).
 *
 * Rendering rules:
 *   • Hidden entirely on national-scope briefings (no geo context
 *     to render — the national prompt doesn't lean on visitor
 *     geography at all).
 *   • Empty-state CTA when geoTrackingEnabled === false: nudges
 *     the user to install / re-enable the Site Tag so country
 *     capture starts populating.
 *   • Two columns when both data sets are present: visitor
 *     countries on the left, service locations on the right.
 *
 * Country-only granularity reflects what TrackedSession.country
 * actually stores. City-level would require a Prisma migration +
 * IP→city resolver in /api/collect — out of scope for this card.
 */

import { Globe2, MapPin, AlertCircle, ShieldCheck } from "lucide-react";
import Link from "next/link";

interface VisitorCountry {
  country: string;
  sessions: number;
}

interface ServiceLocation {
  label: string;
  city: string | null;
  state: string | null;
  source: "gbp" | "brand_profile" | "site_tag";
}

interface SourcesPayload {
  visitorCountries?: VisitorCountry[];
  serviceLocations?: ServiceLocation[];
  geoTrackingEnabled?: boolean;
  siteTag?: boolean;
  scope?: string;
}

const SOURCE_BADGES: Record<ServiceLocation["source"], { label: string; color: string }> = {
  gbp:           { label: "GBP-verified",  color: "bg-green-50 text-green-700 border-green-200" },
  brand_profile: { label: "Brand profile", color: "bg-slate-100 text-slate-600 border-slate-200" },
  site_tag:      { label: "Site Tag",      color: "bg-blue-50 text-blue-700 border-blue-200" },
};

/** Coerce ISO-3166 alpha-2 → flag emoji. Falls back to a generic
 *  globe glyph when the input doesn't look like a 2-letter code. */
function flagEmoji(code: string): string {
  if (!code || code.length !== 2) return "🌐";
  const upper = code.toUpperCase();
  // Each regional indicator symbol is U+1F1E6 + (letter index).
  const base = 0x1F1E6;
  const a = upper.charCodeAt(0) - 65;
  const b = upper.charCodeAt(1) - 65;
  if (a < 0 || a > 25 || b < 0 || b > 25) return "🌐";
  return String.fromCodePoint(base + a) + String.fromCodePoint(base + b);
}

export default function VisitorGeography({ sources, scope }: { sources: unknown; scope: "local" | "national" }) {
  // National scope doesn't carry geo context — bail before rendering
  // an empty card that would just confuse the reader.
  if (scope !== "local") return null;

  // Defensive narrowing: `sources` is unknown on the briefing type
  // (free-form Json column) and may legitimately be null on legacy
  // rows generated before commit 3f38cda.
  const s = (sources && typeof sources === "object" ? sources : {}) as SourcesPayload;
  const countries = Array.isArray(s.visitorCountries) ? s.visitorCountries : [];
  const locations = Array.isArray(s.serviceLocations) ? s.serviceLocations : [];
  const totalSessions = countries.reduce((sum, c) => sum + (c.sessions ?? 0), 0);

  // Empty-empty: hide entirely. A briefing that's missing both data
  // sets is almost certainly a pre-3f38cda row; rather than show a
  // confusing "Set up tracking" CTA on what's actually a legacy
  // record, just don't render.
  if (countries.length === 0 && locations.length === 0) return null;

  return (
    <section className="bg-white rounded-xl border border-slate-200 overflow-hidden">
      <header className="px-5 py-4 border-b border-slate-100 flex items-center justify-between flex-wrap gap-2">
        <div className="flex items-center gap-2">
          <Globe2 className="w-4 h-4 text-blue-600" />
          <h2 className="text-sm font-bold text-slate-800">Where Your Visitors Come From</h2>
        </div>
        {totalSessions > 0 && (
          <p className="text-[11px] text-slate-400 tabular-nums">
            {totalSessions.toLocaleString()} session{totalSessions === 1 ? "" : "s"} · last 30 days
          </p>
        )}
      </header>

      <div className="grid grid-cols-1 md:grid-cols-2 divide-y md:divide-y-0 md:divide-x divide-slate-100">
        {/* Visitor countries (Site Tag, country-level only) */}
        <div className="p-5">
          <div className="flex items-center gap-2 mb-3">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Visitor Countries</p>
            <span className="text-[10px] text-slate-400">Site Tag</span>
          </div>
          {countries.length > 0 ? (
            <ul className="space-y-2">
              {countries.slice(0, 5).map((c) => {
                // Width % of the bar — relative to the busiest
                // country, not absolute so a brand with 90% US
                // traffic still shows useful comparative bars for
                // the smaller markets.
                const pct = countries[0].sessions > 0
                  ? Math.round((c.sessions / countries[0].sessions) * 100)
                  : 0;
                return (
                  <li key={c.country} className="flex items-center gap-3">
                    <span className="text-base shrink-0" aria-hidden>{flagEmoji(c.country)}</span>
                    <span className="text-xs font-semibold text-slate-800 w-10 shrink-0 uppercase">{c.country}</span>
                    <div className="flex-1 h-1.5 bg-slate-100 rounded-full overflow-hidden">
                      <div className="h-full bg-blue-500" style={{ width: `${pct}%` }} />
                    </div>
                    <span className="text-xs font-semibold text-slate-700 tabular-nums shrink-0 min-w-[3rem] text-right">
                      {c.sessions.toLocaleString()}
                    </span>
                  </li>
                );
              })}
            </ul>
          ) : s.geoTrackingEnabled === false && s.siteTag === false ? (
            // Site Tag not installed at all — primary CTA is install.
            <div className="flex items-start gap-2 text-xs text-slate-500">
              <AlertCircle className="w-3.5 h-3.5 text-amber-500 mt-0.5 shrink-0" />
              <p>
                Install the{" "}
                <Link href="/site-tag" className="font-semibold text-brand-600 hover:underline">meSEO Site Tag</Link>{" "}
                to start capturing visitor geography. Country-level data appears here within a few hours of the first session.
              </p>
            </div>
          ) : (
            // Site Tag installed but no country data — likely
            // anonymised or capture disabled. Different copy.
            <div className="flex items-start gap-2 text-xs text-slate-500">
              <AlertCircle className="w-3.5 h-3.5 text-amber-500 mt-0.5 shrink-0" />
              <p>
                Site Tag is installed but no visitor country has been resolved yet. Geo capture may be off, or all current sessions are from anonymised networks. Recheck after the next traffic spike.
              </p>
            </div>
          )}
        </div>

        {/* Service locations (GBP + brand profile) */}
        <div className="p-5">
          <div className="flex items-center gap-2 mb-3">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Where You Serve</p>
            <span className="text-[10px] text-slate-400">GBP + Brand Profile</span>
          </div>
          {locations.length > 0 ? (
            <ul className="space-y-2">
              {locations.slice(0, 8).map((l, i) => {
                const badge = SOURCE_BADGES[l.source] ?? SOURCE_BADGES.brand_profile;
                return (
                  <li key={`${l.label}-${i}`} className="flex items-center gap-2">
                    {l.source === "gbp" ? (
                      <span title="Verified by Google Business Profile" className="shrink-0 inline-flex">
                        <ShieldCheck className="w-3.5 h-3.5 text-green-600" />
                      </span>
                    ) : (
                      <MapPin className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                    )}
                    <span className="text-xs font-semibold text-slate-800 flex-1 truncate" title={l.label}>{l.label}</span>
                    <span className={`text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded border ${badge.color}`}>
                      {badge.label}
                    </span>
                  </li>
                );
              })}
              {locations.length > 8 && (
                <li className="text-[10px] text-slate-400 italic pt-1">…and {locations.length - 8} more</li>
              )}
            </ul>
          ) : (
            <div className="flex items-start gap-2 text-xs text-slate-500">
              <AlertCircle className="w-3.5 h-3.5 text-amber-500 mt-0.5 shrink-0" />
              <p>
                No service locations on file. Connect{" "}
                <Link href="/integrations" className="font-semibold text-brand-600 hover:underline">Google Business Profile</Link>{" "}
                or add cities to the brand profile so local intel can target the right markets.
              </p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
