"use client";

import { useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";

type Lead = {
  id: string;
  name: string;
  role: string;
  roleOverride?: string;
  company: string;
  companyFromPrompt?: boolean;
  sourceTitle?: string;
  subtitle?: string;
  titleText?: string;
  metaText?: string;
  snippetText?: string;
  displayedLink?: string;
  linkedinUrl: string;
  sourceUrl: string;
  snippet: string;
  relevanceScore: number;
  emailConfidence: number;
  emailGuess?: string;
  emailOverride?: string;
  websiteOverride?: string;
  companyWebsite?: string;
  companyDomain?: string;
  companyEmails?: string[];
  createdAt?: string;
  resultType?: "profile" | "job" | "other";
  serp?: Record<string, unknown>;
};

function guessEmail(name: string, company: string, domainOverride?: string) {
  const slug = company
    .toLowerCase()
    .replace(/(ltd|limited|plc|group|holdings|inc|llc|co|company|uk)/g, "")
    .replace(/[^a-z0-9]+/g, "")
    .trim();
  const domain = domainOverride || (slug ? `${slug}.com` : "company.com");
  const parts = name
    .toLowerCase()
    .replace(/[^a-z\s-]/g, "")
    .split(/\s+/)
    .filter(Boolean);
  if (!parts.length) return `hello@${domain}`;
  const first = parts[0];
  const last = parts.length > 1 ? parts[parts.length - 1] : "";
  if (last) return `${first}.${last}@${domain}`;
  return `${first}@${domain}`;
}

function buildEmailCandidates(name: string, domain: string) {
  const parts = name
    .toLowerCase()
    .replace(/[^a-z\s-]/g, "")
    .split(/\s+/)
    .filter(Boolean);
  const first = parts[0] ?? "";
  const last = parts.length > 1 ? parts[parts.length - 1] : "";
  const initial = first ? first[0] : "";
  const nicknameMap: Record<string, string> = {
    matthew: "matt",
    michael: "mike",
    robert: "rob",
    william: "will",
    christopher: "chris",
    andrew: "andy",
    daniel: "dan",
    nicholas: "nick",
    jonathan: "jon",
  };
  const nickname = nicknameMap[first] ?? "";
  const ordered: string[] = [];
  const pushUnique = (value: string) => {
    if (!value || ordered.includes(value)) return;
    ordered.push(value);
  };
  if (first && last) {
    pushUnique(`${first}.${last}@${domain}`);
    pushUnique(`${first}${last}@${domain}`);
    pushUnique(`${first}_${last}@${domain}`);
    pushUnique(`${initial}${last}@${domain}`);
    pushUnique(`${first}@${domain}`);
    if (nickname) {
      pushUnique(`${nickname}@${domain}`);
      pushUnique(`${nickname}.${last}@${domain}`);
      pushUnique(`${nickname}${last}@${domain}`);
    }
    pushUnique(`${initial}@${domain}`);
  } else if (first) {
    pushUnique(`${first}@${domain}`);
    if (nickname) pushUnique(`${nickname}@${domain}`);
  }
  pushUnique(`info@${domain}`);
  pushUnique(`hello@${domain}`);
  return ordered;
}

export default function LeadDetail() {
  const params = useParams<{ id: string }>();
  const leadId = params?.id;
  const [lead, setLead] = useState<Lead | null>(null);
  const [summary, setSummary] = useState("");
  const [loading, setLoading] = useState(true);
  const [companyWebsite, setCompanyWebsite] = useState<string>("");
  const [companyDomain, setCompanyDomain] = useState<string>("");
  const [companyEmails, setCompanyEmails] = useState<string[]>([]);
  const [verificationStatus, setVerificationStatus] = useState<
    Record<string, { status: string; subStatus?: string; message?: string }>
  >({});
  const [copiedEmail, setCopiedEmail] = useState<string>("");
  const [websiteInput, setWebsiteInput] = useState("");
  const [emailInput, setEmailInput] = useState("");
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isVerifying, setIsVerifying] = useState(false);
  const [isPreview, setIsPreview] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isEditingRole, setIsEditingRole] = useState(false);
  const [roleDraft, setRoleDraft] = useState("");
  const [showInvalidEmails, setShowInvalidEmails] = useState(false);

  const inferRoleFromEvidence = (text: string) => {
    if (!text) return "";
    const match = text.match(/\b([A-Z][A-Za-z/&-]{2,40})\s+at\s+[A-Z]/);
    if (match?.[1]) return match[1].trim();
    return "";
  };

  const normalizeWebsite = (value: string) => {
    const trimmed = value.trim();
    if (!trimmed) return "";
    if (/^https?:\/\//i.test(trimmed)) return trimmed;
    return `https://${trimmed}`;
  };

  const extractDomain = (value: string) => {
    if (!value) return "";
    try {
      const parsed = new URL(normalizeWebsite(value));
      return parsed.hostname.replace(/^www\./, "");
    } catch {
      return "";
    }
  };

  const verification = useMemo(() => {
    if (!lead) {
      return { roleVerified: false, companyVerified: false };
    }
    const normalize = (value: string) =>
      value.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
    const evidence = `${lead.titleText ?? lead.sourceTitle ?? ""} ${lead.metaText ?? ""} ${lead.snippetText ?? lead.snippet ?? ""}`;
    const evidenceNormalized = normalize(evidence);
    const roleValue = lead.roleOverride || lead.role;
    const roleVerified =
      Boolean(roleValue) && evidenceNormalized.includes(normalize(roleValue));
    const companyVerified =
      Boolean(lead.company) &&
      evidenceNormalized.includes(normalize(lead.company));
    return { roleVerified, companyVerified };
  }, [lead]);

  useEffect(() => {
    if (!leadId) return;
    const loadLead = async () => {
      let previewLead: Lead | null = null;
      if (typeof window !== "undefined") {
        const previewRaw = window.sessionStorage.getItem("leadfinder:previewLead");
        if (previewRaw) {
          try {
            previewLead = JSON.parse(previewRaw) as Lead;
          } catch {
            previewLead = null;
          }
        }
      }
      const res = await fetch("/api/leads");
      const data = await res.json();
      const found = (data.leads as Lead[]).find(
        (item) => item.id === leadId
      );
      if (found) {
        setLead(found);
        setIsPreview(false);
        setRoleDraft(found.roleOverride || found.role || "");
      } else if (previewLead) {
        setLead(previewLead);
        setIsPreview(true);
        setRoleDraft(previewLead.roleOverride || previewLead.role || "");
      } else {
        setLead(null);
      }
      setLoading(false);
      const activeLead = found ?? lead;
      if (activeLead) {
        if (activeLead.company) {
          const websiteQuery = new URLSearchParams({
            company: activeLead.company,
          });
          if (activeLead.websiteOverride) {
            websiteQuery.set("website", activeLead.websiteOverride);
            setWebsiteInput(activeLead.websiteOverride);
          }
          const websiteRes = await fetch(
            `/api/company-website?${websiteQuery.toString()}`
          );
          if (websiteRes.ok) {
            const websiteData = await websiteRes.json();
            setCompanyWebsite(websiteData.website ?? "");
            setCompanyDomain(websiteData.domain ?? "");
            setCompanyEmails(Array.isArray(websiteData.emails) ? websiteData.emails : []);
          }
        }
        if (activeLead.companyWebsite) {
          setCompanyWebsite(activeLead.companyWebsite);
        }
        if (activeLead.companyDomain) {
          setCompanyDomain(activeLead.companyDomain);
        }
        if (activeLead.companyEmails?.length) {
          setCompanyEmails(activeLead.companyEmails);
        }
        if (activeLead.emailOverride) {
          setEmailInput(activeLead.emailOverride);
        }
        const summaryRes = await fetch("/api/summary", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ lead: activeLead }),
        });
        const summaryData = await summaryRes.json();
        if (!summaryRes.ok) {
          setSummary(summaryData.summary ?? "AI summary unavailable.");
        } else {
          setSummary(summaryData.summary ?? "");
        }
      }
    };
    loadLead();
  }, [leadId]);

  const inferredRole = useMemo(() => {
    if (!lead) return "";
    const evidence = `${lead.snippetText ?? ""} ${lead.metaText ?? ""} ${lead.titleText ?? ""}`;
    return inferRoleFromEvidence(evidence);
  }, [lead]);

  const roleSuggestions = useMemo(() => {
    if (!lead) return [];
    const options = [lead.role, inferredRole].filter(Boolean) as string[];
    return Array.from(new Set(options));
  }, [lead, inferredRole]);

  const displayRole = lead?.roleOverride || lead?.role || "";

  const saveCurrentLead = async () => {
    if (!lead || isSaving) return;
    setIsSaving(true);
    try {
      const res = await fetch("/api/leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ lead }),
      });
      if (!res.ok) return;
      const data = await res.json();
      const savedLead = (data.leads as Lead[]).find(
        (item) =>
          item.linkedinUrl === lead.linkedinUrl ||
          item.sourceUrl === lead.sourceUrl
      );
      if (savedLead?.id) {
        window.location.href = `/lead/${savedLead.id}`;
      }
    } finally {
      setIsSaving(false);
    }
  };

  const emailGuess = useMemo(() => {
    if (!lead) return "";
    if (companyEmails.length) {
      return companyEmails[0];
    }
    return lead.emailGuess || guessEmail(lead.name, lead.company, companyDomain);
  }, [lead, companyDomain, companyEmails]);

  const emailOptions = useMemo(() => {
    if (!lead) return [];
    const domain =
      companyDomain ||
      extractDomain(companyWebsite) ||
      extractDomain(websiteInput) ||
      (lead.company
        ? `${lead.company.toLowerCase().replace(/[^a-z0-9]+/g, "")}.com`
        : "");
    if (!domain) return [];
    const candidates = buildEmailCandidates(lead.name, domain);
    const merged = Array.from(
      new Set([
        ...(lead.emailOverride ? [lead.emailOverride] : []),
        ...companyEmails,
        ...candidates,
      ])
    );
    return merged.slice(0, 6);
  }, [lead, companyDomain, companyEmails]);

  const filteredEmailOptions = useMemo(() => {
    return emailOptions.filter((email) => {
      const status = verificationStatus[email]?.status;
      if (showInvalidEmails) return true;
      return status !== "invalid";
    });
  }, [emailOptions, verificationStatus, showInvalidEmails]);

  const verificationIssue = useMemo(() => {
    const issues = Object.values(verificationStatus).filter(
      (item) => item.status === "error"
    );
    if (!issues.length) return "";
    return issues[0]?.message || "Email verification unavailable.";
  }, [verificationStatus]);

  const emailOptionsKey = useMemo(() => emailOptions.join("|"), [emailOptions]);
  useEffect(() => {
    setVerificationStatus((prev) =>
      Object.keys(prev).length ? {} : prev
    );
  }, [emailOptionsKey]);

  const runEmailVerification = async () => {
    if (!emailOptions.length || isVerifying) return;
    setIsVerifying(true);
    const results: Record<string, { status: string; subStatus?: string; message?: string }> = {};
    await Promise.all(
      emailOptions.map(async (email) => {
        try {
          const res = await fetch(
            `/api/email-verify?email=${encodeURIComponent(email)}`
          );
          const data = await res.json();
          if (!res.ok) {
            results[email] = {
              status: "error",
              message: data?.message ?? "Verification failed.",
            };
            return;
          }
          results[email] = {
            status: data?.status ?? "unknown",
            subStatus: data?.subStatus ?? "",
            message: data?.message ?? "",
          };
        } catch {
          results[email] = {
            status: "error",
            message: "Verification failed.",
          };
        }
      })
    );
    setVerificationStatus(results);
    setIsVerifying(false);
  };

  const verificationSummary = useMemo(() => {
    const entries = Object.entries(verificationStatus);
    const valid = entries.find(([, value]) => value.status === "valid");
    const catchAll = entries.find(([, value]) => value.status === "catch-all");
    return {
      hasRun: entries.length > 0,
      validEmail: valid?.[0] ?? "",
      catchAllEmail: catchAll?.[0] ?? "",
    };
  }, [verificationStatus]);

  const emailConfidenceDisplay = useMemo(() => {
    if (!lead) {
      return { value: 0, label: "Unverified" };
    }
    if (verificationSummary.validEmail) {
      return { value: 100, label: "Verified" };
    }
    if (verificationSummary.catchAllEmail) {
      return {
        value: Math.min(60, Math.max(lead.emailConfidence ?? 0, 45)),
        label: "Catch-all",
      };
    }
    const hasRisky = Object.values(verificationStatus).some(
      (item) => item.status === "risky"
    );
    if (hasRisky) {
      return {
        value: Math.max(lead.emailConfidence ?? 0, 55),
        label: "Risky",
      };
    }
    return {
      value: lead.emailConfidence ?? 0,
      label: verificationSummary.hasRun ? "Estimated" : "Unverified",
    };
  }, [lead, verificationSummary, verificationStatus]);

  const refreshLead = async (targetLead: Lead | null = lead) => {
    if (!targetLead) return;
    setIsRefreshing(true);
    try {
      const normalizedWebsite = normalizeWebsite(
        websiteInput || targetLead.websiteOverride || ""
      );
      if (targetLead.company) {
        const websiteQuery = new URLSearchParams({
          company: targetLead.company,
        });
        if (normalizedWebsite) {
          websiteQuery.set("website", normalizedWebsite);
        }
        const websiteRes = await fetch(
          `/api/company-website?${websiteQuery.toString()}`
        );
        if (websiteRes.ok) {
          const websiteData = await websiteRes.json();
          setCompanyWebsite(websiteData.website ?? "");
          setCompanyDomain(websiteData.domain ?? "");
          setCompanyEmails(Array.isArray(websiteData.emails) ? websiteData.emails : []);
          if (!websiteInput && websiteData.website) {
            setWebsiteInput(websiteData.website);
          }
          if (!isPreview && targetLead.id) {
            await fetch("/api/leads", {
              method: "PATCH",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                id: targetLead.id,
                updates: {
                  companyWebsite: websiteData.website ?? undefined,
                  companyDomain: websiteData.domain ?? undefined,
                  companyEmails: Array.isArray(websiteData.emails)
                    ? websiteData.emails
                    : undefined,
                  websiteOverride: normalizedWebsite || undefined,
                },
              }),
            });
          }
        }
      } else if (normalizedWebsite) {
        setCompanyWebsite(normalizedWebsite);
        setCompanyDomain(extractDomain(normalizedWebsite));
      }

      const summaryRes = await fetch("/api/summary", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ lead: targetLead }),
      });
      const summaryData = await summaryRes.json();
      if (!summaryRes.ok) {
        setSummary(summaryData.summary ?? "AI summary unavailable.");
      } else {
        setSummary(summaryData.summary ?? "");
      }
    } finally {
      setIsRefreshing(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-[var(--background)] px-6 py-16 text-[var(--foreground)] md:px-12 lg:px-16">
        <p className="text-sm text-[var(--muted)]">Loading lead...</p>
      </div>
    );
  }

  if (!lead) {
    return (
      <div className="min-h-screen bg-[var(--background)] px-6 py-16 text-[var(--foreground)] md:px-12 lg:px-16">
        <p className="text-sm text-[var(--muted)]">Lead not found.</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[var(--background)] text-[var(--foreground)]">
      <header className="border-b-4 border-black bg-black px-6 py-4 md:px-12 lg:px-16">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-xs uppercase tracking-[0.25em] text-white/70">
              Leadfinder
            </p>
            <h1 className="font-[var(--font-display)] text-2xl font-semibold tracking-tight text-white md:text-3xl">
              Lead profile
            </h1>
          </div>
          <div className="flex items-center gap-4">
            <nav className="flex items-center gap-3 text-xs font-semibold uppercase tracking-wide text-white/70">
              <a href="/" className="text-white hover:text-white/80">
                Search
              </a>
              <span className="text-white/40">|</span>
              <a href="/searches" className="text-white hover:text-white/80">
                Saved searches
              </a>
              <span className="text-white/40">|</span>
              <a href="/leads" className="text-white hover:text-white/80">
                All leads
              </a>
            </nav>
            <button
              type="button"
              onClick={saveCurrentLead}
              disabled={!isPreview || isSaving}
              className="rounded-full border border-white/40 px-4 py-2 text-xs font-semibold uppercase tracking-wide text-white transition hover:border-white hover:bg-white hover:text-black disabled:opacity-60"
            >
              {isPreview ? (isSaving ? "Saving..." : "Save lead") : "Saved"}
            </button>
          </div>
        </div>
      </header>

      <main className="px-6 py-12 md:px-12 lg:px-16">
        <div className="grid gap-10 lg:grid-cols-[1.2fr_0.8fr]">
          <section className="rounded-3xl border border-black/10 bg-white p-8 shadow-[0_30px_80px_rgba(0,0,0,0.12)]">
            <h2 className="font-[var(--font-display)] text-3xl font-semibold">
              {lead.name || "Unknown lead"}
            </h2>
            <div className="mt-2 text-sm text-[var(--muted)]">
              <div className="flex flex-wrap items-center gap-2">
                <span>
                  {displayRole
                    ? displayRole
                    : roleSuggestions.length
                      ? `Suggested: ${roleSuggestions[0]}`
                      : "Role not listed"}
                </span>
                {roleSuggestions.length > 0 && !displayRole && (
                  <button
                    type="button"
                    onClick={async () => {
                      if (!lead) return;
                      const suggested = roleSuggestions[0];
                      if (!suggested) return;
                      const res = await fetch("/api/leads", {
                        method: "PATCH",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                          id: lead.id,
                          updates: { roleOverride: suggested },
                        }),
                      });
                      if (res.ok) {
                        const data = await res.json();
                        if (data?.lead) {
                          setLead(data.lead);
                          setRoleDraft(data.lead.roleOverride || data.lead.role || "");
                        }
                      }
                    }}
                    className="rounded-full border border-black/20 px-3 py-1 text-xs font-semibold text-black hover:border-black"
                  >
                    Confirm
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => setIsEditingRole((value) => !value)}
                  className="rounded-full border border-black/20 px-3 py-1 text-xs font-semibold text-black hover:border-black"
                >
                  {isEditingRole ? "Cancel" : "Edit"}
                </button>
              </div>
              {lead.company ? <span>• {lead.company}</span> : null}
              {isEditingRole && (
                <div className="mt-3 flex flex-wrap items-center gap-2">
                  <input
                    value={roleDraft}
                    onChange={(event) => setRoleDraft(event.target.value)}
                    placeholder="Enter role"
                    className="min-w-[220px] flex-1 rounded-full border border-black/20 bg-white px-3 py-2 text-xs outline-none focus:border-black"
                  />
                  <button
                    type="button"
                    onClick={async () => {
                      if (!lead) return;
                      const res = await fetch("/api/leads", {
                        method: "PATCH",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                          id: lead.id,
                          updates: { roleOverride: roleDraft || undefined },
                        }),
                      });
                      if (res.ok) {
                        const data = await res.json();
                        if (data?.lead) {
                          setLead(data.lead);
                          setRoleDraft(data.lead.roleOverride || data.lead.role || "");
                        }
                        setIsEditingRole(false);
                      }
                    }}
                    className="rounded-full border border-black/20 bg-black px-3 py-2 text-xs font-semibold text-white hover:bg-black/80"
                  >
                    Save
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setRoleDraft(displayRole || "");
                      setIsEditingRole(false);
                    }}
                    className="rounded-full border border-black/20 px-3 py-2 text-xs font-semibold text-black hover:border-black"
                  >
                    Cancel
                  </button>
                </div>
              )}
              {roleSuggestions.length > 1 && (
                <div className="mt-3 flex flex-wrap items-center gap-2">
                  <span className="text-xs uppercase tracking-wide text-black/40">
                    Suggestions
                  </span>
                  {roleSuggestions.map((item) => (
                    <button
                      key={item}
                      type="button"
                      onClick={() => setRoleDraft(item)}
                      className="rounded-full border border-black/20 px-3 py-1 text-xs font-semibold text-black hover:border-black"
                    >
                      {item}
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className="mt-6 grid gap-4 md:grid-cols-2">
              <div className="rounded-2xl bg-black px-5 py-4 text-white">
                <p className="text-xs uppercase tracking-wide text-white/60">
                  LinkedIn match
                </p>
                <p className="mt-2 text-3xl font-semibold">
                  {lead.relevanceScore}%
                </p>
              </div>
              <div className="rounded-2xl border border-black/10 bg-white px-5 py-4">
                <p className="text-xs uppercase tracking-wide text-black/60">
                  Email confidence
                </p>
                <p className="mt-2 text-3xl font-semibold text-black">
                  {emailConfidenceDisplay.value}%
                </p>
                <p className="mt-1 text-xs uppercase tracking-wide text-black/50">
                  {emailConfidenceDisplay.label}
                </p>
              </div>
            </div>

            <div className="mt-6 rounded-2xl border border-black/10 bg-[var(--surface-strong)] px-5 py-4">
              <p className="text-xs uppercase tracking-wide text-black/60">
                Suggested emails
              </p>
              <div className="mt-3 flex flex-wrap items-center gap-2">
                <input
                  value={websiteInput}
                  onChange={(event) => setWebsiteInput(event.target.value)}
                  placeholder="Optional: paste company website"
                  className="flex-1 rounded-full border border-black/20 bg-white px-3 py-2 text-xs outline-none focus:border-black"
                />
                <input
                  value={emailInput}
                  onChange={(event) => setEmailInput(event.target.value)}
                  placeholder="Optional: known email"
                  className="flex-1 rounded-full border border-black/20 bg-white px-3 py-2 text-xs outline-none focus:border-black"
                />
                <button
                  type="button"
                  onClick={async () => {
                    if (!lead) return;
                    const normalizedWebsite = normalizeWebsite(websiteInput);
                    const res = await fetch("/api/leads", {
                      method: "PATCH",
                      headers: { "Content-Type": "application/json" },
                      body: JSON.stringify({
                        id: lead.id,
                        updates: {
                          websiteOverride: normalizedWebsite || undefined,
                          emailOverride: emailInput || undefined,
                        },
                      }),
                    });
                    let updatedLead: Lead | null = lead;
                    if (res.ok) {
                      const data = await res.json();
                      const updated = data?.lead as Lead | undefined;
                      if (updated) {
                        updatedLead = updated;
                        setLead(updated);
                        if (updated.websiteOverride) {
                          setWebsiteInput(updated.websiteOverride);
                        }
                        if (updated.emailOverride) {
                          setEmailInput(updated.emailOverride);
                        }
                      }
                    }
                    await refreshLead(updatedLead);
                  }}
                  className="rounded-full border border-black/20 bg-black px-4 py-2 text-xs font-semibold text-white hover:bg-black/80"
                >
                  Save website
                </button>
                <button
                  type="button"
                  onClick={refreshLead}
                  className="rounded-full border border-black/20 bg-white px-4 py-2 text-xs font-semibold text-black hover:border-black"
                  disabled={isRefreshing}
                >
                  {isRefreshing ? "Refreshing..." : "Refresh lead"}
                </button>
                <button
                  type="button"
                  onClick={runEmailVerification}
                  className="rounded-full border border-black/20 bg-white px-4 py-2 text-xs font-semibold text-black hover:border-black"
                  disabled={isVerifying}
                >
                  {isVerifying ? "Verifying..." : "Verify emails"}
                </button>
              </div>
              <div className="mt-3 grid gap-2">
                {filteredEmailOptions.map((email) => {
                  const status = verificationStatus[email]?.status ?? "unverified";
                  const label =
                    lead?.emailOverride === email
                      ? "Provided"
                      : status === "valid"
                      ? "Verified"
                      : status === "invalid"
                        ? "Invalid"
                        : status === "catch-all"
                          ? "Catch-all domain (cannot confirm)"
                          : status === "risky"
                            ? "Risky"
                          : status === "unverified"
                            ? "Unverified"
                            : "Unknown";
                  return (
                    <button
                      key={email}
                      type="button"
                      onClick={async () => {
                        await navigator.clipboard.writeText(email);
                        setCopiedEmail(email);
                        window.setTimeout(() => {
                          setCopiedEmail((current) =>
                            current === email ? "" : current
                          );
                        }, 1400);
                      }}
                      className="flex items-center justify-between rounded-xl border border-black/10 bg-white px-3 py-2 text-left text-sm font-semibold text-black transition hover:border-black"
                    >
                      <span>{email}</span>
                      <span className="text-[10px] uppercase tracking-wide text-black/50">
                        {copiedEmail === email
                          ? "Copied!"
                          : label}
                      </span>
                    </button>
                  );
                })}
              {!filteredEmailOptions.length && (
                <p className="text-sm text-[var(--muted)]">
                  No email suggestions available.
                </p>
              )}
            </div>
            <p className="mt-2 text-xs text-[var(--muted)]">
              Click an email to copy. Run verification to confirm deliverability (Bouncer).
            </p>
            {Object.values(verificationStatus).some(
              (item) => item.status === "invalid"
            ) && (
              <button
                type="button"
                onClick={() => setShowInvalidEmails((value) => !value)}
                className="mt-2 text-xs font-semibold text-black underline-offset-4 hover:underline"
              >
                {showInvalidEmails ? "Hide invalid emails" : "Show invalid emails"}
              </button>
            )}
            {verificationIssue && (
              <p className="mt-2 text-xs text-rose-600">
                {verificationIssue}
              </p>
            )}
          </div>

            {companyWebsite && (
              <div className="mt-4 text-sm text-[var(--muted)]">
                Company website:{" "}
                <a
                  href={companyWebsite}
                  target="_blank"
                  rel="noreferrer"
                  className="text-black underline-offset-4 hover:underline"
                >
                  {companyWebsite}
                </a>
              </div>
            )}

            <div className="mt-6">
              <p className="text-xs uppercase tracking-wide text-black/60">
                AI summary
              </p>
              <p className="mt-3 text-sm text-[var(--muted)]">
                {summary || "Generating summary..."}
              </p>
              <p className="mt-2 text-xs text-[var(--muted)]">
                Summary is generated from the LinkedIn snippet/title shown below.
              </p>
            </div>

            <div className="mt-6 text-sm text-[var(--muted)]">
              {lead.snippet}
            </div>

            <div className="mt-6 flex flex-wrap gap-3 text-xs">
              {lead.linkedinUrl && (
                <a
                  href={lead.linkedinUrl}
                  target="_blank"
                  rel="noreferrer"
                  className="rounded-full border border-black/20 px-4 py-1.5 text-black transition hover:border-black"
                >
                  View LinkedIn
                </a>
              )}
            </div>
          </section>

          <aside className="space-y-6">
            <div className="rounded-3xl border border-black/10 bg-white p-6">
              <h3 className="font-[var(--font-display)] text-xl font-semibold">
                Lead overview
              </h3>
              <div className="mt-4 space-y-3 text-sm text-[var(--muted)]">
                <div>
                  <p className="text-xs uppercase tracking-wide text-black/60">
                    Company
                  </p>
                  <p className="text-base text-black">
                    {verification.companyVerified ? lead.company : "Not confirmed"}
                  </p>
                </div>
                <div>
                  <p className="text-xs uppercase tracking-wide text-black/60">
                    Role
                  </p>
                  <p className="text-base text-black">
                    {lead.roleOverride
                      ? lead.roleOverride
                      : roleSuggestions.length
                        ? `Suggested: ${roleSuggestions[0]}`
                        : "Not confirmed"}
                  </p>
                </div>
                <div>
                  <p className="text-xs uppercase tracking-wide text-black/60">
                    Added
                  </p>
                  <p className="text-base text-black">
                    {lead.createdAt
                      ? new Date(lead.createdAt).toLocaleString()
                      : "Recently"}
                  </p>
                </div>
              </div>
            </div>

            <div className="rounded-3xl border border-black/10 bg-black p-6 text-white">
              <h3 className="font-[var(--font-display)] text-xl font-semibold">
                Next actions
              </h3>
              <p className="mt-2 text-sm text-white/70">
                Use the estimated email to start outreach, then confirm
                deliverability before sending a full campaign.
              </p>
            </div>
          </aside>
        </div>
      </main>
    </div>
  );
}
