import { useEffect, useRef, useState } from "react";
import { Link } from "@tanstack/react-router";
import { ArrowUpRight, ArrowRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import valdomiroPhoto from "@/assets/valdomiro-garrah.jpg.asset.json";
import christianePhoto from "@/assets/christiane-zamboni.jpg.asset.json";

const metrics: { value: number; suffix: string; label: string; prefix?: string; decimals?: number }[] = [
  { value: 102, suffix: " mil", label: "unidades lançadas" },
  { value: 200, suffix: "+", label: "empreendimentos" },
  { value: 20, suffix: " anos", label: "de experiência no mercado imobiliário" },
  { value: 20, suffix: " mil+", label: "profissionais treinados" },
  { value: 6, suffix: " estados", label: "com operações e projetos em 2026" },
];

const leaders = [
  { name: "Valdomiro Garrah", role: "Founder", initials: "VG", photo: new URL(valdomiroPhoto.url, "https://investplus-v2.lovable.app").href, bio: "20 anos no mercado imobiliário. MBA em Gestão Empresarial pela FGV-RJ. Referência em crédito associativo, o financiamento à produção. Integra o Comitê Executivo da Pramorar Brasil, incorporadora do Minha Casa Minha Vida em Fortaleza. Ex-atleta da base da Seleção Brasileira de Vôlei." },
  { name: "Christiane Zamboni", role: "CEO do Grupo", initials: "CZ", photo: new URL(christianePhoto.url, "https://investplus-v2.lovable.app").href, bio: "30 anos em desenvolvimento humano, gestão e estruturação de equipes de alta performance. MBA em Gestão de RH pela FGV. Passagens por FTD, Sodimac Brasil e Grupo Casa Barão. Organiza e institucionaliza a operação do grupo." },
];

function Metrics() {
  const ref = useRef<HTMLDivElement>(null);
  const [progress, setProgress] = useState(1);

  useEffect(() => {
    const element = ref.current;
    if (!element || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    setProgress(0);
    let frame = 0;
    const observer = new IntersectionObserver(([entry]) => {
      if (!entry?.isIntersecting) return;
      observer.disconnect();
      const start = performance.now();
      const animate = (now: number) => {
        const elapsed = Math.min((now - start) / 1100, 1);
        setProgress(1 - Math.pow(1 - elapsed, 3));
        if (elapsed < 1) frame = requestAnimationFrame(animate);
      };
      frame = requestAnimationFrame(animate);
    }, { threshold: 0.25 });
    observer.observe(element);
    return () => { observer.disconnect(); cancelAnimationFrame(frame); };
  }, []);

  return (
    <div ref={ref}>
      <dl className="grid grid-cols-2 gap-x-6 gap-y-6 border-y border-border py-6 md:grid-cols-3">
        {metrics.map(({ value, suffix, label, prefix = "", decimals = 0 }) => (
          <div key={label} className="min-w-0">
            <dt className="mt-1 text-sm text-muted-foreground">{label}</dt>
            <dd className="-order-1 text-3xl font-bold tabular-nums text-foreground" aria-label={`${value}${suffix}`}>
              <span aria-hidden>{prefix}{(value * progress).toFixed(decimals).replace(".", ",")}{suffix}</span>
            </dd>
          </div>
        ))}
      </dl>
      <p className="mt-3 text-xs leading-relaxed text-muted-foreground">Informação declarada pela emissora. Desempenho passado não é garantia de resultados futuros.</p>
    </div>
  );
}

function LeaderPhoto({ leader }: { leader: typeof leaders[number] }) {
  const [failed, setFailed] = useState(false);
  return (
    <div className="flex size-16 shrink-0 items-center justify-center overflow-hidden rounded-full bg-secondary font-semibold text-secondary-foreground">
      {failed ? leader.initials : <img src={leader.photo} alt={leader.name} width={64} height={64} loading="lazy" onError={() => setFailed(true)} className="size-full object-cover" />}
    </div>
  );
}

export function BrasilUrbanoProfile({ partnerPage = false }: { partnerPage?: boolean }) {
  const Title = partnerPage ? "h1" : "h2";
  return (
    <section className="border-y border-border bg-secondary/30 py-12 sm:py-14">
      <div className="mx-auto max-w-6xl space-y-7 px-4 sm:px-6 lg:px-8">
        <div>
          <div className="brand-gradient h-1 w-12 rounded-full" />
          <p className="mt-3 text-xs font-semibold uppercase text-muted-foreground">Brasil Urbano — a incorporadora que capta na N-1</p>
          <Title className="mt-2 max-w-4xl text-2xl font-bold sm:text-3xl">20 anos de experiência no mercado imobiliário.</Title>
          <p className="mt-3 max-w-3xl text-base leading-relaxed text-muted-foreground">A Brasil Urbano é o núcleo operacional de um ecossistema de dez empresas da Garrah & Co, que cobre o ciclo completo do imóvel: terreno, projeto, tecnologia, marketing, crédito e venda.</p>
        </div>
        <Metrics />
        <div>
          <div className="grid gap-4 md:grid-cols-2">
            {leaders.map((leader) => (
              <article key={leader.name} className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-4 rounded-lg border border-border bg-card p-5">
                <LeaderPhoto leader={leader} />
                <div className="min-w-0">
                  <h3 className="text-base font-semibold">{leader.name}</h3>
                  <p className="mt-1 text-xs font-semibold text-muted-foreground">{leader.role}</p>
                  <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{leader.bio}</p>
                </div>
              </article>
            ))}
          </div>
          <div className="mt-4 flex gap-4 rounded-lg border border-border bg-card p-5">
            <p className="text-4xl font-bold">8º</p>
            <p className="text-sm leading-relaxed text-muted-foreground">Top Imobiliário 2018 (O Estado de S. Paulo × EMBRAESP, categoria Vendedora). A Garrah estreou em 8º lugar no ranking de vendas da Região Metropolitana de São Paulo. Hoje, a Garrah & Co é a holding do ecossistema Brasil Urbano. Fonte: O Estado de S. Paulo, 25/06/2019.</p>
          </div>
          <div className="mt-6 flex flex-col items-start gap-4 sm:flex-row sm:items-center sm:justify-between">
            <a href="https://www.brasilurbano.com.br/" target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1.5 text-sm text-foreground underline decoration-border underline-offset-4 transition hover:text-muted-foreground">
              www.brasilurbano.com.br <ArrowUpRight className="size-4 shrink-0" />
            </a>
            {partnerPage && (
              <Button asChild className="h-auto min-h-10 whitespace-normal text-center">
                <Link to="/brasil-urbano">Ver a N-1 <ArrowRight /></Link>
              </Button>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}