import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import {
  ArrowRight,
  User,
  FolderOpen,
  Share2,
  Globe,
  Image,
  FileText,
  QrCode,
  Star,
  Camera,
  BadgeCheck,
  Check,
  Users,
  Camera as CameraIcon,
  Video,
  Mic,
  Sparkles,
  RefreshCw,
  Link2,
} from "lucide-react";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";

interface PublicProfile {
  user_id: string;
  name: string;
  artistic_name: string;
  category: string;
  city_state: string;
  profile_image_url: string;
  verified_creator?: boolean;
}

export const LandingPage = () => {
  const navigate = useNavigate();
  const [creators, setCreators] = useState<PublicProfile[]>([]);
  const [loadingCreators, setLoadingCreators] = useState(true);

  useEffect(() => {
    const fetchCreators = async () => {
      const { data } = await supabase.rpc('get_public_profiles');
      if (data) {
        const list = (data as PublicProfile[]) ?? [];
        // Deduplicate by artistic_name/name (case-insensitive) keeping verified first
        const sorted = [...list].sort((a, b) => {
          const av = a.verified_creator ? 1 : 0;
          const bv = b.verified_creator ? 1 : 0;
          return bv - av;
        });
        const seen = new Set<string>();
        const unique: PublicProfile[] = [];
        for (const p of sorted) {
          const key = (p.artistic_name || p.name || '').trim().toLowerCase();
          if (!key || seen.has(key)) continue;
          seen.add(key);
          unique.push(p);
        }
        setCreators(unique.slice(0, 6));
      }
      setLoadingCreators(false);
    };
    fetchCreators();
  }, []);

  const getProfileSlug = (p: PublicProfile) => {
    const name = p.artistic_name || p.name || 'creator';
    return name.toLowerCase().replace(/\s+/g, '-');
  };

  return (
    <div className="min-h-screen bg-background">
      {/* ============ HERO ============ */}
      <section id="hero" className="relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-muted/60 via-background to-muted/30" />
        <div className="absolute top-0 right-0 w-[600px] h-[600px] rounded-full bg-primary/[0.03] blur-3xl -translate-y-1/2 translate-x-1/3" />

        <div className="relative container mx-auto max-w-6xl px-4 pt-20 pb-24 md:pt-28 md:pb-32">
          <div className="max-w-3xl mx-auto text-center">
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-primary/5 border border-primary/10 text-sm text-muted-foreground mb-8">
              <Star className="w-3.5 h-3.5 text-primary" />
              Portfólio profissional para modelos e influenciadores
            </div>

            <h1 className="text-4xl md:text-6xl lg:text-7xl font-bold tracking-tight text-foreground leading-[1.1] mb-6">
              Sua identidade profissional
              <br />
              <span className="text-primary">começa aqui.</span>
            </h1>

            <p className="text-lg md:text-xl text-muted-foreground leading-relaxed max-w-2xl mx-auto mb-10">
              Crie um portfólio profissional, organize seus trabalhos, gere um mídia kit automaticamente e compartilhe um único perfil com agências, clientes e oportunidades.
            </p>

            <div className="flex flex-col sm:flex-row items-center justify-center gap-3">
              <Button
                size="lg"
                onClick={() => navigate('/auth')}
                className="rounded-full px-8 h-12 text-base shadow-lg hover:shadow-xl transition-all w-full sm:w-auto"
              >
                Criar meu portfólio
                <ArrowRight className="w-4 h-4 ml-1" />
              </Button>
              <Button
                variant="outline"
                size="lg"
                onClick={() => {
                  const el = document.getElementById('creators');
                  el?.scrollIntoView({ behavior: 'smooth' });
                }}
                className="rounded-full px-8 h-12 text-base w-full sm:w-auto"
              >
                Explorar creators
              </Button>
            </div>
          </div>

          {/* ==== Platform Mockup (Perfil Profissional) ==== */}
          <div className="mt-16 md:mt-20 relative">
            <div className="absolute -inset-4 bg-gradient-to-t from-background via-transparent to-transparent z-10 pointer-events-none" />
            <div className="bg-card rounded-2xl md:rounded-3xl shadow-2xl border border-border/50 overflow-hidden">
              <div className="flex items-center gap-2 px-5 py-3 border-b border-border/40 bg-muted/30">
                <div className="flex gap-1.5">
                  <div className="w-3 h-3 rounded-full bg-border" />
                  <div className="w-3 h-3 rounded-full bg-border" />
                  <div className="w-3 h-3 rounded-full bg-border" />
                </div>
                <div className="flex-1 flex justify-center">
                  <div className="bg-muted rounded-md px-4 py-1 text-xs text-muted-foreground">
                    creatorid.lovable.app/u/seu-perfil
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-0">
                {/* Coluna 1 — Identidade */}
                <div className="p-6 md:p-8 border-b md:border-b-0 md:border-r border-border/30">
                  <div className="flex flex-col items-center text-center">
                    <div className="w-20 h-20 rounded-full bg-gradient-to-br from-primary/20 to-primary/5 flex items-center justify-center mb-4 ring-4 ring-background shadow-md">
                      <User className="w-8 h-8 text-primary" />
                    </div>
                    <p className="font-bold text-lg text-foreground">Nome do Creator</p>
                    <p className="text-sm text-muted-foreground">Modelo & Influencer</p>
                    <p className="text-xs text-muted-foreground mt-1">São Paulo · SP</p>

                    <div className="mt-4 inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-green-500/10 border border-green-500/20 text-[11px] font-medium text-green-700 dark:text-green-400">
                      <span className="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse" />
                      Disponível para trabalhos
                    </div>

                    <div className="w-full mt-5 pt-5 border-t border-border/40 text-left">
                      <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">Medidas</p>
                      <div className="grid grid-cols-2 gap-x-3 gap-y-1 text-xs">
                        <span className="text-muted-foreground">Altura</span><span className="font-medium text-right">Ainda sem dados</span>
                        <span className="text-muted-foreground">Busto</span><span className="font-medium text-right">Ainda sem dados</span>
                        <span className="text-muted-foreground">Cintura</span><span className="font-medium text-right">Ainda sem dados</span>
                        <span className="text-muted-foreground">Sapato</span><span className="font-medium text-right">Ainda sem dados</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Coluna 2 — Portfólio + Redes */}
                <div className="p-6 md:p-8 border-b md:border-b-0 md:border-r border-border/30">
                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-4">Portfólio</p>
                  <div className="grid grid-cols-2 gap-2">
                    {[1,2,3,4].map(i => (
                      <div key={i} className="aspect-square rounded-xl bg-gradient-to-br from-muted to-muted/50 flex items-center justify-center">
                        <Camera className="w-5 h-5 text-muted-foreground/50" />
                      </div>
                    ))}
                  </div>
                  <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mt-5 mb-2">Redes sociais</p>
                  <div className="flex gap-2 flex-wrap">
                    <span className="text-xs bg-muted rounded-full px-3 py-1">Instagram</span>
                    <span className="text-xs bg-muted rounded-full px-3 py-1">TikTok</span>
                    <span className="text-xs bg-muted rounded-full px-3 py-1">YouTube</span>
                  </div>
                </div>

                {/* Coluna 3 — Mídia Kit + QR + Compartilhar */}
                <div className="p-6 md:p-8">
                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-4">Mídia Kit</p>
                  <div className="space-y-3">
                    <div className="bg-muted/50 rounded-xl p-3">
                      <p className="text-xs text-muted-foreground">Categoria</p>
                      <p className="text-sm font-bold text-foreground">Modelo & Influencer</p>
                    </div>
                    <div className="bg-muted/50 rounded-xl p-3">
                      <p className="text-xs text-muted-foreground">Alcance médio</p>
                      <p className="text-sm font-bold text-foreground">Ainda sem dados</p>
                    </div>
                  </div>
                  <div className="mt-5 pt-5 border-t border-border/40 flex items-center gap-3">
                    <div className="w-14 h-14 rounded-lg border border-border/60 flex items-center justify-center bg-muted/40">
                      <QrCode className="w-7 h-7 text-muted-foreground" />
                    </div>
                    <div className="flex-1">
                      <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">QR Code</p>
                      <p className="text-xs mt-0.5 text-muted-foreground">Compartilhe seu perfil</p>
                    </div>
                  </div>
                  <Button size="sm" variant="outline" className="mt-4 rounded-full h-8 text-xs w-full gap-1.5">
                    <Share2 className="w-3 h-3" /> Compartilhar perfil
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ============ COMO FUNCIONA ============ */}
      <section id="how-it-works" className="py-20 md:py-28 px-4 bg-muted/30">
        <div className="container mx-auto max-w-5xl">
          <div className="text-center mb-16">
            <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-3">Como funciona</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground">
              Simples de começar, profissional de verdade.
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8">
            {[
              {
                icon: User,
                step: "01",
                title: "Crie seu perfil",
                desc: "Cadastre suas informações profissionais, fotos, medidas, redes sociais e experiência."
              },
              {
                icon: FolderOpen,
                step: "02",
                title: "Organize seu portfólio",
                desc: "Adicione ensaios, editoriais, campanhas e projetos para apresentar seu trabalho."
              },
              {
                icon: Share2,
                step: "03",
                title: "Compartilhe",
                desc: "Envie um único link profissional para agências, clientes e oportunidades."
              },
            ].map((item) => (
              <div key={item.step} className="group relative bg-card rounded-2xl p-8 border border-border/40 hover:border-primary/20 hover:shadow-lg transition-all duration-300">
                <span className="text-5xl font-bold text-muted/60 absolute top-6 right-6">{item.step}</span>
                <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-5">
                  <item.icon className="w-6 h-6 text-primary" />
                </div>
                <h3 className="text-xl font-bold mb-3">{item.title}</h3>
                <p className="text-muted-foreground leading-relaxed">{item.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ============ RECURSOS ============ */}
      <section className="py-20 md:py-28 px-4">
        <div className="container mx-auto max-w-6xl">
          <div className="text-center mb-16">
            <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-3">Recursos</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground mb-4">
              Ferramentas profissionais em um só lugar.
            </h2>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
            {[
              {
                icon: Globe,
                title: "Perfil Profissional",
                desc: "Sua apresentação profissional em uma página elegante, pronta para agências e clientes."
              },
              {
                icon: Image,
                title: "Portfólio",
                desc: "Reúna ensaios, editoriais e campanhas em uma galeria pensada para valorizar o seu trabalho."
              },
              {
                icon: FileText,
                title: "Mídia Kit",
                desc: "Um mídia kit profissional atualizado automaticamente com base nas suas informações."
              },
              {
                icon: QrCode,
                title: "Compartilhamento",
                desc: "Link único, QR Code e compartilhamento direto para qualquer oportunidade."
              },
            ].map((item) => (
              <div key={item.title} className="flex gap-5 p-6 rounded-2xl border border-border/40 bg-card hover:border-primary/20 hover:shadow-md transition-all duration-300">
                <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0">
                  <item.icon className="w-6 h-6 text-primary" />
                </div>
                <div>
                  <h3 className="font-bold text-base mb-1.5">{item.title}</h3>
                  <p className="text-sm text-muted-foreground leading-relaxed">{item.desc}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ============ PARA QUEM É ============ */}
      <section className="py-20 md:py-28 px-4 bg-muted/30">
        <div className="container mx-auto max-w-6xl">
          <div className="text-center mb-16">
            <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-3">Para quem é</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground mb-4">
              Feito para criadores de imagem.
            </h2>
            <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
              Uma plataforma pensada para quem constrói carreira apresentando o próprio trabalho.
            </p>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {[
              { icon: User, title: "Modelos" },
              { icon: Star, title: "Influenciadores" },
              { icon: Video, title: "Criadores de Conteúdo" },
              { icon: CameraIcon, title: "Fotógrafos" },
              { icon: Users, title: "Atores" },
              { icon: Mic, title: "Apresentadores" },
            ].map((item) => (
              <div key={item.title} className="p-6 rounded-2xl border border-border/40 bg-card hover:border-primary/20 hover:shadow-md transition-all duration-300 text-center">
                <div className="w-11 h-11 mx-auto mb-3 rounded-xl bg-primary/10 flex items-center justify-center">
                  <item.icon className="w-5 h-5 text-primary" />
                </div>
                <h3 className="font-semibold text-sm">{item.title}</h3>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ============ CREATORS EM DESTAQUE ============ */}
      <section id="creators" className="py-20 md:py-28 px-4">
        <div className="container mx-auto max-w-6xl">
          <div className="text-center mb-16">
            <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-3">Creators em Destaque</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground mb-4">
              Conheça quem já está na plataforma.
            </h2>
          </div>

          {loadingCreators ? (
            <div className="text-center text-muted-foreground py-12">Carregando...</div>
          ) : creators.length === 0 ? (
            <div className="text-center py-16">
              <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-4">
                <User className="w-7 h-7 text-primary" />
              </div>
              <p className="text-lg text-muted-foreground">Em breve você conhecerá os creators da plataforma.</p>
              <Button onClick={() => navigate('/auth')} className="mt-6 rounded-full px-6">
                Criar meu portfólio <ArrowRight className="w-4 h-4 ml-1" />
              </Button>
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4 md:gap-6">
              {creators.map((creator) => (
                <div key={creator.user_id} className="group relative rounded-2xl overflow-hidden bg-card border border-border/40 hover:shadow-xl transition-all duration-300">
                  <div className="aspect-[3/4] overflow-hidden bg-muted flex items-center justify-center">
                    {creator.profile_image_url ? (
                      <img
                        src={creator.profile_image_url}
                        alt={creator.artistic_name || creator.name}
                        loading="lazy"
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                      />
                    ) : (
                      <User className="w-12 h-12 text-muted-foreground/40" />
                    )}
                    <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/10 to-transparent" />
                  </div>
                  <div className="absolute bottom-0 left-0 right-0 p-4 md:p-5">
                    <h3 className="font-bold text-white text-base md:text-lg leading-tight flex items-center gap-1.5">
                      <span className="truncate">{creator.artistic_name || creator.name}</span>
                      {creator.verified_creator && (
                        <BadgeCheck className="h-4 w-4 text-blue-400 flex-shrink-0" aria-label="Verificado" />
                      )}
                    </h3>
                    {creator.category && (
                      <p className="text-white/70 text-xs md:text-sm mt-0.5">{creator.category}</p>
                    )}
                    {creator.city_state && (
                      <p className="text-white/60 text-xs mt-1">{creator.city_state}</p>
                    )}
                    <Button
                      variant="secondary"
                      size="sm"
                      className="mt-3 rounded-full text-xs h-8 px-4 opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-white/90 text-foreground hover:bg-white"
                      onClick={() => navigate(`/u/${getProfileSlug(creator)}`)}
                    >
                      Ver perfil
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* ============ DIFERENCIAL ============ */}
      <section className="py-20 md:py-28 px-4 bg-muted/30">
        <div className="container mx-auto max-w-4xl">
          <div className="text-center mb-12">
            <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-3">Diferencial</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground mb-4">
              Seu portfólio completo em um único link.
            </h2>
            <p className="text-muted-foreground text-lg max-w-2xl mx-auto">
              Em vez de compartilhar vários links, organize sua presença profissional em um único perfil com portfólio, mídia kit, redes sociais, contato e informações profissionais.
            </p>
          </div>

          <div className="bg-card rounded-2xl border border-border/40 p-8 md:p-10 shadow-sm">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                "Portfólio",
                "Mídia Kit",
                "Redes sociais",
                "Informações profissionais",
                "Contato",
                "Trabalhos",
                "Disponibilidade",
                "Atualizações automáticas",
              ].map((item) => (
                <div key={item} className="flex items-center gap-3">
                  <div className="w-6 h-6 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Check className="w-3.5 h-3.5 text-primary" />
                  </div>
                  <span className="text-foreground">{item}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* ============ POR QUE USAR ============ */}
      <section className="py-20 md:py-28 px-4">
        <div className="container mx-auto max-w-6xl">
          <div className="text-center mb-16">
            <p className="text-sm font-semibold text-primary uppercase tracking-wider mb-3">Por que Creator ID</p>
            <h2 className="text-3xl md:text-4xl font-bold text-foreground">
              Por que usar o Creator ID?
            </h2>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
            {[
              { icon: User, title: "Perfil Profissional", desc: "Uma apresentação séria e organizada da sua carreira." },
              { icon: FolderOpen, title: "Portfólio organizado", desc: "Seus melhores trabalhos exibidos com clareza e estética." },
              { icon: FileText, title: "Mídia Kit automático", desc: "Um mídia kit atualizado sem retrabalho para cada oportunidade." },
              { icon: QrCode, title: "Compartilhamento por QR Code", desc: "Compartilhe seu perfil em cartões, e-mails e mensagens." },
              { icon: RefreshCw, title: "Atualização rápida", desc: "Edite suas informações e veja tudo refletido em um clique." },
              { icon: Link2, title: "Link único profissional", desc: "Um endereço só para toda a sua presença profissional." },
            ].map((item) => (
              <div key={item.title} className="p-6 rounded-2xl border border-border/40 bg-card hover:border-primary/20 hover:shadow-md transition-all duration-300">
                <div className="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center mb-4">
                  <item.icon className="w-5 h-5 text-primary" />
                </div>
                <h3 className="font-bold text-base mb-1.5">{item.title}</h3>
                <p className="text-sm text-muted-foreground leading-relaxed">{item.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* ============ CTA FINAL ============ */}
      <section className="py-20 md:py-28 px-4">
        <div className="container mx-auto max-w-4xl">
          <div className="relative rounded-3xl bg-primary p-10 md:p-16 text-center overflow-hidden">
            <div className="absolute top-0 right-0 w-64 h-64 rounded-full bg-primary-foreground/5 -translate-y-1/2 translate-x-1/3" />
            <div className="absolute bottom-0 left-0 w-48 h-48 rounded-full bg-primary-foreground/5 translate-y-1/2 -translate-x-1/3" />

            <div className="relative">
              <h2 className="text-3xl md:text-4xl font-bold text-primary-foreground mb-4">
                Sua carreira merece uma apresentação profissional.
              </h2>
              <p className="text-primary-foreground/80 text-lg mb-8 max-w-xl mx-auto">
                Junte-se aos modelos e influenciadores que utilizam o Creator ID para organizar seu portfólio e compartilhar seu trabalho com mais credibilidade.
              </p>
              <Button
                size="lg"
                variant="secondary"
                onClick={() => navigate('/auth')}
                className="rounded-full px-8 h-12 text-base"
              >
                Criar meu portfólio gratuitamente
                <ArrowRight className="w-4 h-4 ml-1" />
              </Button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};
