"use client";

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

interface Props {
  organicSearchSummary: NonNullable<SeoSection["organicSearchSummary"]>;
}

function urlPath(url: string): string {
  try {
    const p = new URL(url).pathname.replace(/\/$/, "") || "/";
    return p.length > 45 ? p.slice(0, 43) + "…" : p;
  } catch {
    return url.length > 45 ? url.slice(0, 43) + "…" : url;
  }
}

export function OrganicSearchSection({ organicSearchSummary: gs }: Props) {
  return (
    <div className="rounded-2xl bg-slate-900/60 border border-white/10 overflow-hidden">
      <div className="px-6 py-5 border-b border-white/10">
        <h3 className="text-sm font-semibold text-slate-100">Organic Search Performance</h3>
        <p className="text-xs text-slate-400 mt-0.5">Last 30 days from connected search console integration</p>
      </div>

      {/* Summary tiles */}
      <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-white/10 border-b border-white/10">
        {[
          { label: "Clicks", value: gs.totalClicks30d.toLocaleString() },
          { label: "Impressions", value: gs.totalImpressions30d.toLocaleString() },
          { label: "Avg CTR", value: `${gs.avgCtr.toFixed(1)}%` },
          { label: "Avg position", value: gs.avgPosition.toFixed(1) },
        ].map(({ label, value }) => (
          <div key={label} className="px-5 py-4">
            <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-1">{label}</p>
            <div className="text-2xl font-black tabular-nums text-white leading-none">{value}</div>
          </div>
        ))}
      </div>

      <div className="grid sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-white/10">
        {/* Top queries */}
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">Top queries</p>
          {gs.topQueries.length === 0 ? (
            <p className="text-xs text-slate-500">No query data yet</p>
          ) : (
            <table className="w-full text-xs">
              <thead>
                <tr className="text-slate-500">
                  <th className="text-left font-medium pb-2">Query</th>
                  <th className="text-right font-medium pb-2 pl-2">Clicks</th>
                  <th className="text-right font-medium pb-2 pl-2">Pos.</th>
                </tr>
              </thead>
              <tbody>
                {gs.topQueries.slice(0, 8).map((q, i) => (
                  <tr key={q.query} className={i < Math.min(gs.topQueries.length, 8) - 1 ? "border-b border-white/5" : ""}>
                    <td className="py-1.5 pr-2 text-slate-300 max-w-[160px] truncate" title={q.query}>{q.query}</td>
                    <td className="py-1.5 px-2 text-right tabular-nums text-slate-300">{q.clicks.toLocaleString()}</td>
                    <td className="py-1.5 pl-2 text-right tabular-nums text-slate-400">{q.position.toFixed(1)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* Top pages */}
        <div className="px-5 py-5">
          <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400 mb-3">Top pages</p>
          {gs.topPages.length === 0 ? (
            <p className="text-xs text-slate-500">No page data yet</p>
          ) : (
            <table className="w-full text-xs">
              <thead>
                <tr className="text-slate-500">
                  <th className="text-left font-medium pb-2">Page</th>
                  <th className="text-right font-medium pb-2 pl-2">Clicks</th>
                  <th className="text-right font-medium pb-2 pl-2">Pos.</th>
                </tr>
              </thead>
              <tbody>
                {gs.topPages.slice(0, 8).map((p, i) => (
                  <tr key={p.page} className={i < Math.min(gs.topPages.length, 8) - 1 ? "border-b border-white/5" : ""}>
                    <td className="py-1.5 pr-2 font-mono text-[11px] text-slate-400" title={p.page}>{urlPath(p.page)}</td>
                    <td className="py-1.5 px-2 text-right tabular-nums text-slate-300">{p.clicks.toLocaleString()}</td>
                    <td className="py-1.5 pl-2 text-right tabular-nums text-slate-400">{p.position.toFixed(1)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      </div>
    </div>
  );
}
