// src/components/keywords/keyword-modal-rank-card.tsx — « Page qui ranke »
// card: position GSC, minis Impressions/Clics/CTR, URL qui ranke, et le
// détail GSC par pays.
"use client";

import { Flag } from "@/components/ui/flag";
import type { Keyword } from "@/lib/keywords/types";

function pageParts(url: string): { host: string; initials: string } {
  try {
    const u = new URL(url);
    const host = u.hostname.replace(/^www\./, "");
    return { host, initials: host.slice(0, 2).toUpperCase() };
  } catch {
    return { host: url, initials: "··" };
  }
}

function Mini({ value, label }: { value: string; label: string }) {
  return (
    <div className="flex flex-1 flex-col gap-0.5 rounded-[9px] border border-border/60 bg-muted/30 px-2.5 py-1.5">
      <b className="font-semibold text-[15px] tabular-nums">{value}</b>
      <span className="font-medium text-[10px] text-muted-foreground/80">
        {label}
      </span>
    </div>
  );
}

export function KeywordModalRankCard({ keyword }: { keyword: Keyword }) {
  const gsc = keyword.gsc;
  const byCountry = Object.entries(keyword.gscByCountry ?? {}).filter(
    ([, t]) => t,
  );

  if (!gsc) {
    return (
      <section className="flex flex-col rounded-2xl border border-border/70 bg-card px-4.5 py-4">
        <h3 className="font-semibold text-[11px] text-muted-foreground/80 uppercase tracking-wider">
          Page qui ranke
        </h3>
        <div className="flex flex-1 items-center justify-center py-6">
          <span className="text-muted-foreground/70 text-xs">
            — Aucune donnée GSC pour ce mot-clé
          </span>
        </div>
      </section>
    );
  }

  const distance = Math.max(0, Math.ceil(gsc.position - 10));
  const page = gsc.page ?? null;
  const parts = page ? pageParts(page) : null;

  return (
    <section className="flex flex-col gap-3 rounded-2xl border border-border/70 bg-card px-4.5 py-4">
      <h3 className="font-semibold text-[11px] text-muted-foreground/80 uppercase tracking-wider">
        Page qui ranke
      </h3>

      <div className="flex items-center gap-3">
        <div
          className="flex size-[46px] flex-none flex-col items-center justify-center rounded-xl border"
          style={{
            background:
              "linear-gradient(180deg, rgba(245,181,68,.16), rgba(245,181,68,.05))",
            borderColor: "rgba(245,181,68,.28)",
          }}
        >
          <b className="font-semibold text-[#f5b544] text-[17px] leading-none">
            {gsc.position.toFixed(1)}
          </b>
          <span className="mt-0.5 font-semibold text-[8px] text-[#f5b544]/70 uppercase tracking-wide">
            Pos.
          </span>
        </div>
        <div className="flex min-w-0 flex-col gap-0.5">
          <b className="font-semibold text-[13px]">Position moyenne</b>
          <span className="text-[11px] text-muted-foreground">
            Google ·{" "}
            {distance > 0 ? `~${distance} places du top 10` : "dans le top 10"}
          </span>
        </div>
      </div>

      <div className="flex gap-2">
        <Mini
          value={gsc.impressions.toLocaleString("fr-FR")}
          label="Impressions"
        />
        <Mini value={gsc.clicks.toLocaleString("fr-FR")} label="Clics" />
        <Mini value={`${(gsc.ctr * 100).toFixed(1)}%`} label="CTR" />
      </div>

      {page && parts ? (
        <div className="flex items-center gap-2.5 rounded-[11px] border border-border/60 bg-muted/30 px-3 py-2.5">
          <div className="grid size-[26px] flex-none place-items-center rounded-[7px] bg-primary font-bold text-[11px] text-primary-foreground">
            {parts.initials}
          </div>
          <div className="flex min-w-0 flex-1 flex-col">
            <b className="truncate font-semibold text-xs">{parts.host}</b>
            <span className="truncate text-[11px] text-muted-foreground">
              {page}
            </span>
          </div>
          <a
            href={page}
            target="_blank"
            rel="noreferrer"
            title="Ouvrir la page"
            className="grid size-[30px] flex-none place-items-center rounded-lg border border-border/60 bg-card text-muted-foreground transition-colors hover:border-border hover:text-foreground"
          >
            <svg
              width="14"
              height="14"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden="true"
            >
              <path d="M7 17L17 7M9 7h8v8" />
            </svg>
            <span className="sr-only">Ouvrir la page qui ranke</span>
          </a>
        </div>
      ) : null}

      {byCountry.length > 0 ? (
        <div className="flex flex-col gap-1.5 border-border/50 border-t pt-2.5">
          <span className="font-semibold text-[10px] text-muted-foreground/70 uppercase tracking-wider">
            GSC par pays
          </span>
          {byCountry.map(([code, t]) =>
            t ? (
              <div
                key={code}
                className="flex items-center gap-3 text-xs tabular-nums"
              >
                <Flag code={code} title={code} />
                <span className="font-medium">
                  pos. {t.position.toFixed(1)}
                </span>
                <span className="text-muted-foreground">{t.clicks} clics</span>
                <span className="text-muted-foreground">
                  {t.impressions} impr.
                </span>
              </div>
            ) : null,
          )}
        </div>
      ) : null}
    </section>
  );
}
