import { AddressAutocompleteInput } from "@/components/AddressAutocompleteInput";
import AccountSecurityPanel from "@/components/AccountSecurityPanel";
import { AuthenticatedPageSkeleton } from "@/components/AuthenticatedPageSkeleton";
import { useDashboardNavigationGuard } from "@/components/DashboardLayout";
import DataPrivacyValidationDialog from "@/components/DataPrivacyValidationDialog";
import { PortalDashboardHeader, PortalSectionIntro, PortalSurface } from "@/components/portal/PortalSurface";
import { useViewportFlags } from "@/hooks/useMobile";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import type { AddressSuggestion } from "@/lib/addressAutocomplete";
import { trpc } from "@/lib/trpc";
import { getFriendlyActionError } from "@/lib/userFeedback";
import { cn } from "@/lib/utils";
import {
  createEmptyGovernancePerson,
  governanceMemberRoleOptions,
  legalRepresentativeRoleOptions,
  normalizeLegalRepresentativeRole,
  parseAssociationGovernance,
  sanitizeGovernance,
  type AssociationGovernance,
  type GovernancePerson,
  type GovernanceMemberRole,
  type LegalRepresentativeRole,
} from "@shared/associationGovernance";
import { associationThematicOptions, getAssociationThematicDescription, getAssociationThematicLabel, parseAssociationThematics, type AssociationThematic } from "@shared/associationThematics";
import { isValidFacebookUrl, isValidInstagramUrl } from "@shared/socialLinks";
import { buildDataPrivacyConsent } from "@shared/privacyCompliance";
import { Building2, Loader2, Plus, Save, Trash2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link } from "wouter";
import { toast } from "sonner";

export default function Profile() {
  const { isMobile, isTablet } = useViewportFlags();
  const { data: association, isLoading } = trpc.association.getMyProfile.useQuery();
  const utils = trpc.useUtils();
  const [privacyDialogOpen, setPrivacyDialogOpen] = useState(false);
  const [savedSnapshot, setSavedSnapshot] = useState<string | null>(null);
  const { setUnsavedChangesGuard } = useDashboardNavigationGuard();

  const [formData, setFormData] = useState<{
    nomAssociation: string;
    siret: string;
    rna: string;
    thematiques: AssociationThematic[];
    adresse: string;
    codePostal: string;
    ville: string;
    telephone: string;
    emailContact: string;
    siteWeb: string;
    facebookUrl: string;
    instagramUrl: string;
    dateCreation: string;
    objetAssociation: string;
    statutJuridique: 'association_loi_1901' | 'association_reconnue_utilite_publique' | 'fondation' | 'autre';
    gouvernance: {
      representantLegal: GovernancePerson & { fonction: LegalRepresentativeRole };
      membres: Array<GovernancePerson & { fonction: GovernanceMemberRole }>;
    };
  }>({
    nomAssociation: '',
    siret: '',
    rna: '',
    thematiques: [] as AssociationThematic[],
    adresse: '',
    codePostal: '',
    ville: '',
    telephone: '',
    emailContact: '',
    siteWeb: '',
    facebookUrl: '',
    instagramUrl: '',
    dateCreation: '',
    objetAssociation: '',
    statutJuridique: 'association_loi_1901' as 'association_loi_1901' | 'association_reconnue_utilite_publique' | 'fondation' | 'autre',
    gouvernance: {
      representantLegal: createEmptyGovernancePerson('president') as GovernancePerson & { fonction: LegalRepresentativeRole },
      membres: [],
    },
  });

  const buildFallbackGovernance = (nomRepresentant?: string | null, fonctionRepresentant?: string | null) => {
    const cleaned = String(nomRepresentant || "").trim().replace(/\s+/g, " ");
    const parts = cleaned ? cleaned.split(" ") : [];
    const nom = parts.length > 1 ? parts.at(-1) || "" : cleaned;
    const prenom = parts.length > 1 ? parts.slice(0, -1).join(" ") : "";

    return {
      representantLegal: {
        nom,
        prenom,
        email: "",
        telephone: "",
        fonction: normalizeLegalRepresentativeRole(fonctionRepresentant),
      },
      membres: [],
    } satisfies AssociationGovernance;
  };

  useEffect(() => {
    if (association) {
      const parsedGovernance = sanitizeGovernance(
        association.gouvernance
          ? parseAssociationGovernance(association.gouvernance)
          : buildFallbackGovernance(association.nomRepresentant, association.fonctionRepresentant)
      );
      const nextFormData = {
        nomAssociation: association.nomAssociation || '',
        siret: association.siret || '',
        rna: association.rna || '',
        thematiques: parseAssociationThematics(association.thematique),
        adresse: association.adresse || '',
        codePostal: association.codePostal || '',
        ville: association.ville || '',
        telephone: association.telephone || '',
        emailContact: association.emailContact || '',
        siteWeb: association.siteWeb || '',
        facebookUrl: association.facebookUrl || '',
        instagramUrl: association.instagramUrl || '',
        dateCreation: association.dateCreation ? new Date(association.dateCreation).toISOString().split('T')[0] : '',
        objetAssociation: association.objetAssociation || '',
        statutJuridique: association.statutJuridique || 'association_loi_1901',
        gouvernance: {
          representantLegal: (parsedGovernance.representantLegal || createEmptyGovernancePerson("president")) as GovernancePerson & { fonction: LegalRepresentativeRole },
          membres: parsedGovernance.membres as Array<GovernancePerson & { fonction: GovernanceMemberRole }>,
        },
      };
      setFormData(nextFormData);
      setSavedSnapshot(JSON.stringify(nextFormData));
    }
  }, [association]);

  const upsertMutation = trpc.association.upsertProfile.useMutation({
    onSuccess: () => {
      setPrivacyDialogOpen(false);
      toast.success('Profil enregistré avec succès');
      utils.association.getMyProfile.invalidate();
    },
    onError: (error) => {
      toast.error(
        getFriendlyActionError(
          error,
          "Impossible d'enregistrer votre fiche pour le moment. Vérifiez les champs obligatoires puis réessayez.",
          {
            invalidInputMessage:
              "Impossible d'enregistrer la fiche : merci de compléter les informations obligatoires du représentant légal et de l'association.",
          }
        )
      );
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const gouvernance = sanitizeGovernance(formData.gouvernance);
    if (!gouvernance.representantLegal?.nom || !gouvernance.representantLegal?.prenom || !gouvernance.representantLegal?.fonction) {
      toast.error("Le représentant légal principal est obligatoire.");
      return;
    }
    setPrivacyDialogOpen(true);
  };

  const buildProfilePayload = useCallback(() => {
    const gouvernance = sanitizeGovernance(formData.gouvernance);
    const representantLegal = gouvernance.representantLegal;
    if (!representantLegal) {
      toast.error("Le représentant légal principal est obligatoire.");
      return null;
    }
    return {
      ...formData,
      thematiques: formData.thematiques,
      gouvernance: {
        representantLegal: {
          nom: representantLegal.nom,
          prenom: representantLegal.prenom,
          email: representantLegal.email || "",
          telephone: representantLegal.telephone || "",
          fonction: representantLegal.fonction as LegalRepresentativeRole,
        },
        membres: gouvernance.membres.map((member) => ({
          nom: member.nom,
          prenom: member.prenom,
          email: member.email || "",
          telephone: member.telephone || "",
          fonction: member.fonction as GovernanceMemberRole,
        })),
      },
      privacyConsent: buildDataPrivacyConsent("save_profile"),
    };
  }, [formData]);

  const submitProfileWithPrivacyConsent = useCallback(async () => {
    const payload = buildProfilePayload();
    if (!payload) {
      return false;
    }

    await upsertMutation.mutateAsync(payload);
    setSavedSnapshot(JSON.stringify(formData));
    return true;
  }, [buildProfilePayload, formData, upsertMutation]);

  const currentSnapshot = useMemo(() => JSON.stringify(formData), [formData]);
  const hasUnsavedChanges = savedSnapshot !== null && currentSnapshot !== savedSnapshot;

  useEffect(() => {
    if (!hasUnsavedChanges) {
      setUnsavedChangesGuard(null);
      return;
    }

    setUnsavedChangesGuard({
      when: true,
      title: "Modifications non enregistrées",
      message:
        "Vous avez des modifications non enregistrées ou une fiche incomplète. Souhaitez-vous enregistrer vos changements avant de quitter cette page ?",
      onSave: submitProfileWithPrivacyConsent,
    });

    return () => {
      setUnsavedChangesGuard(null);
    };
  }, [hasUnsavedChanges, setUnsavedChangesGuard, submitProfileWithPrivacyConsent]);

  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleRepresentativeChange = (
    field: keyof GovernancePerson,
    value: string
  ) => {
    setFormData((prev) => ({
      ...prev,
      gouvernance: {
        ...prev.gouvernance,
        representantLegal: {
          ...prev.gouvernance.representantLegal,
          [field]: value,
        },
      },
    }));
  };

  const handleGovernanceMemberChange = (index: number, field: keyof GovernancePerson, value: string) => {
    setFormData((prev) => ({
      ...prev,
      gouvernance: {
        ...prev.gouvernance,
        membres: prev.gouvernance.membres.map((member, memberIndex) =>
          memberIndex === index ? { ...member, [field]: value } : member
        ),
      },
    }));
  };

  const addGovernanceMember = () => {
    setFormData((prev) => ({
      ...prev,
      gouvernance: {
        ...prev.gouvernance,
        membres: [...prev.gouvernance.membres, createEmptyGovernancePerson("tresorier") as GovernancePerson & { fonction: GovernanceMemberRole }],
      },
    }));
  };

  const removeGovernanceMember = (index: number) => {
    setFormData((prev) => ({
      ...prev,
      gouvernance: {
        ...prev.gouvernance,
        membres: prev.gouvernance.membres.filter((_, memberIndex) => memberIndex !== index),
      },
    }));
  };

  const handleAddressSelected = (suggestion: AddressSuggestion) => {
    setFormData(prev => ({
      ...prev,
      adresse: suggestion.addressLine,
      codePostal: suggestion.postcode,
      ville: suggestion.city,
    }));
  };

  const facebookUrlIsValid = isValidFacebookUrl(formData.facebookUrl);
  const instagramUrlIsValid = isValidInstagramUrl(formData.instagramUrl);


  if (isLoading) {
    return (
      <div className="portal-immersive-page min-h-screen">
        <PortalDashboardHeader
          title="Mon association"
          description="Chargement de votre fiche association"
        />
        <main className="container py-6 sm:py-8">
          <div className="max-w-4xl">
            <AuthenticatedPageSkeleton
              message="Chargement de votre fiche, de la gouvernance et des paramètres de sécurité..."
              cards={2}
              formRows={6}
            />
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="portal-immersive-page min-h-screen">
      <PortalDashboardHeader
        tourId="profile-header"
        title="Mon association"
        description="Gérez les informations de votre association"
      />

      <main className={cn("container py-5 sm:py-8", isMobile && "pb-28")}>
        <form onSubmit={handleSubmit} className="max-w-4xl space-y-5 sm:space-y-6">
          <PortalSurface
            className={cn(
              "border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5",
              hasUnsavedChanges ? "ring-1 ring-amber-100" : "ring-1 ring-emerald-100"
            )}
            bodyClassName="space-y-4 p-5"
          >
            <PortalSectionIntro
              eyebrow="Suivi"
              title={hasUnsavedChanges ? "Des modifications sont en attente" : "Votre fiche est à jour"}
              description={
                hasUnsavedChanges
                  ? "Pensez à enregistrer vos changements avant de quitter cette page pour éviter toute perte de saisie."
                  : "Les informations enregistrées ici seront réutilisées dans vos demandes et dans l’annuaire."
              }
              aside={
                <span className="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">
                  {hasUnsavedChanges ? "Enregistrement recommandé" : "Dernière version prête"}
                </span>
              }
            />
            <div className="rounded-xl border border-white/80 bg-white/80 px-4 py-3 text-sm text-muted-foreground shadow-sm">
              <p className="font-medium text-foreground">Repère rapide</p>
              <p className="mt-1">
                Cette fiche alimente automatiquement vos demandes, votre présence dans l’annuaire et les informations reprises par l’administration.
              </p>
            </div>
          </PortalSurface>

          {/* Informations générales */}
          <Card className="bg-white/96">
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Building2 className="h-5 w-5 text-primary" />
                Informations générales
              </CardTitle>
              <CardDescription>
                Les informations de base de votre association
              </CardDescription>
            </CardHeader>
              <CardContent className="space-y-4">
              <div className="rounded-2xl border border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5 p-4">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="rounded-full border border-primary/15 bg-white/80 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary">
                    Référentiel association
                  </span>
                  <span className="rounded-full bg-white/80 px-2.5 py-1 text-xs font-medium text-slate-700">
                    Fiche source de vos demandes
                  </span>
                </div>
                <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Association</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">{formData.nomAssociation || "À renseigner"}</p>
                  </div>
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Commune</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">{formData.ville || "À renseigner"}</p>
                  </div>
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Thématiques</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">{formData.thematiques.length || 0}</p>
                  </div>
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Identifiants</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">
                      {formData.siret || formData.rna ? "Présents" : "À compléter"}
                    </p>
                  </div>
                </div>
                <div className="mt-4 rounded-xl border border-dashed border-primary/20 bg-white/70 px-3 py-3 text-sm text-muted-foreground">
                  Ces informations servent de base à l’annuaire, à la cartographie et au pré-remplissage de vos démarches.
                </div>
              </div>
              {association?.sourceDirectoryEntryId ? (
                <div className="rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm text-primary">
                  Ce profil a été prérempli à partir du bordereau des associations des Savanes. Tu peux compléter ou corriger les informations ci-dessous.
                </div>
              ) : null}
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="nomAssociation">Nom de l'association *</Label>
                  <Input
                    id="nomAssociation"
                    value={formData.nomAssociation}
                    onChange={(e) => handleChange('nomAssociation', e.target.value)}
                    placeholder="Association XYZ"
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="statutJuridique">Statut juridique</Label>
                  <Select
                    value={formData.statutJuridique}
                    onValueChange={(value) => handleChange('statutJuridique', value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Sélectionnez un statut" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="association_loi_1901">Association loi 1901</SelectItem>
                      <SelectItem value="association_reconnue_utilite_publique">Association reconnue d'utilité publique</SelectItem>
                      <SelectItem value="fondation">Fondation</SelectItem>
                      <SelectItem value="autre">Autre</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-3">
                <div className="space-y-1">
                  <Label>Thématiques</Label>
                  <p className="text-sm text-muted-foreground">
                    Sélectionne une ou plusieurs thématiques pour classer correctement l’association dans l’annuaire.
                  </p>
                </div>
                <div className="grid gap-3 md:grid-cols-2">
                  {associationThematicOptions.map((option) => {
                    const checked = formData.thematiques.includes(option.value);
                    return (
                      <button
                        key={option.value}
                        type="button"
                        onClick={() =>
                          setFormData((prev) => ({
                            ...prev,
                            thematiques: checked
                              ? prev.thematiques.filter((value) => value !== option.value)
                              : [...prev.thematiques, option.value],
                          }))
                        }
                        className={`rounded-xl border p-3.5 text-left transition-colors ${checked ? "border-primary bg-primary/5" : "hover:bg-muted/40"}`}
                      >
                        <p className="font-medium">{option.label}</p>
                        <p className="mt-2 text-sm text-muted-foreground">{option.description}</p>
                      </button>
                    );
                  })}
                </div>
                {formData.thematiques.length > 0 ? (
                  <div className="flex flex-wrap gap-2">
                    {formData.thematiques.map((value) => (
                      <span key={value} className="rounded-full bg-primary/10 px-3 py-1 text-sm text-primary">
                        {getAssociationThematicLabel(value)}
                      </span>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground">Aucune thématique sélectionnée pour le moment.</p>
                )}
              </div>

              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="siret">Numéro SIRET</Label>
                  <Input
                    id="siret"
                    value={formData.siret}
                    onChange={(e) => handleChange('siret', e.target.value)}
                    placeholder="123 456 789 00012"
                    maxLength={14}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="rna">Numéro RNA</Label>
                  <Input
                    id="rna"
                    value={formData.rna}
                    onChange={(e) => handleChange('rna', e.target.value)}
                    placeholder="W123456789"
                    maxLength={10}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="dateCreation">Date de création</Label>
                <Input
                  id="dateCreation"
                  type="date"
                  value={formData.dateCreation}
                  onChange={(e) => handleChange('dateCreation', e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="objetAssociation">Objet de l'association</Label>
                <Textarea
                  id="objetAssociation"
                  value={formData.objetAssociation}
                  onChange={(e) => handleChange('objetAssociation', e.target.value)}
                  placeholder="Décrivez l'objet et les activités de votre association..."
                  rows={4}
                />
              </div>
            </CardContent>
          </Card>

          {/* Adresse */}
          <Card>
            <CardHeader>
              <CardTitle>Adresse du siège social</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="adresse">Adresse</Label>
                <AddressAutocompleteInput
                  id="adresse"
                  value={formData.adresse}
                  onValueChange={(value) => handleChange('adresse', value)}
                  onSuggestionSelected={handleAddressSelected}
                  placeholder="123 rue de la République"
                />
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="codePostal">Code postal</Label>
                  <Input
                    id="codePostal"
                    value={formData.codePostal}
                    onChange={(e) => handleChange('codePostal', e.target.value)}
                    placeholder="75001"
                    maxLength={5}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ville">Ville</Label>
                  <Input
                    id="ville"
                    value={formData.ville}
                    onChange={(e) => handleChange('ville', e.target.value)}
                    placeholder="Paris"
                  />
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Contact */}
          <Card className="bg-white/96">
            <CardHeader>
              <CardTitle>Coordonnées de contact</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-2xl border border-primary/10 bg-gradient-to-r from-primary/10 via-white to-primary/5 p-4">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="rounded-full border border-primary/15 bg-white/80 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-primary">
                    Contact public
                  </span>
                  <span className="rounded-full bg-white/80 px-2.5 py-1 text-xs font-medium text-slate-700">
                    Annuaire et échanges admin
                  </span>
                </div>
                <div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Téléphone</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">{formData.telephone || "À renseigner"}</p>
                  </div>
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Email</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950 break-all">{formData.emailContact || "À renseigner"}</p>
                  </div>
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Site web</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">{formData.siteWeb ? "Renseigné" : "Optionnel"}</p>
                  </div>
                  <div className="rounded-xl border border-white/80 bg-white/90 px-3 py-3">
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Réseaux</p>
                    <p className="mt-1 text-sm font-semibold text-slate-950">
                      {(formData.facebookUrl ? 1 : 0) + (formData.instagramUrl ? 1 : 0)} lien(s)
                    </p>
                  </div>
                </div>
                <div className="mt-4 rounded-xl border border-dashed border-primary/20 bg-white/70 px-3 py-3 text-sm text-muted-foreground">
                  Ces coordonnées sont celles que l’association et l’administration réutilisent le plus souvent au quotidien.
                </div>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="telephone">Téléphone</Label>
                  <Input
                    id="telephone"
                    type="tel"
                    value={formData.telephone}
                    onChange={(e) => handleChange('telephone', e.target.value)}
                    placeholder="01 23 45 67 89"
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="emailContact">Email de contact</Label>
                  <Input
                    id="emailContact"
                    type="email"
                    value={formData.emailContact}
                    onChange={(e) => handleChange('emailContact', e.target.value)}
                    placeholder="contact@association.fr"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="siteWeb">Site web</Label>
                <Input
                  id="siteWeb"
                  type="url"
                  value={formData.siteWeb}
                  onChange={(e) => handleChange('siteWeb', e.target.value)}
                  placeholder="https://www.association.fr"
                />
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="facebookUrl">Lien Facebook</Label>
                  <Input
                    id="facebookUrl"
                    type="url"
                    value={formData.facebookUrl}
                    onChange={(e) => handleChange('facebookUrl', e.target.value)}
                    placeholder="https://facebook.com/monassociation"
                    aria-invalid={!facebookUrlIsValid}
                  />
                  {!facebookUrlIsValid ? (
                    <p className="text-sm text-destructive">
                      Utilise une URL HTTPS valide vers Facebook.
                    </p>
                  ) : null}
                </div>
                <div className="space-y-2">
                  <Label htmlFor="instagramUrl">Lien Instagram</Label>
                  <Input
                    id="instagramUrl"
                    type="url"
                    value={formData.instagramUrl}
                    onChange={(e) => handleChange('instagramUrl', e.target.value)}
                    placeholder="https://instagram.com/monassociation"
                    aria-invalid={!instagramUrlIsValid}
                  />
                  {!instagramUrlIsValid ? (
                    <p className="text-sm text-destructive">
                      Utilise une URL HTTPS valide vers Instagram.
                    </p>
                  ) : null}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Gouvernance */}
          <Card>
            <CardHeader>
              <CardTitle>Gouvernance</CardTitle>
              <CardDescription>
                Le représentant légal principal est affiché par défaut dans le bordereau. Les autres membres restent visibles dans le détail et l’administration.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="rounded-lg border p-4">
                <div className="mb-4">
                  <p className="font-medium">Représentant légal principal</p>
                  <p className="text-sm text-muted-foreground">
                    Bloc obligatoire. C’est la personne de référence publiée par défaut.
                  </p>
                </div>
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label htmlFor="representantLegal-prenom">Prénom *</Label>
                    <Input
                      id="representantLegal-prenom"
                      value={formData.gouvernance.representantLegal.prenom}
                      onChange={(e) => handleRepresentativeChange("prenom", e.target.value)}
                      placeholder="Jean"
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="representantLegal-nom">Nom *</Label>
                    <Input
                      id="representantLegal-nom"
                      value={formData.gouvernance.representantLegal.nom}
                      onChange={(e) => handleRepresentativeChange("nom", e.target.value)}
                      placeholder="Dupont"
                      required
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="representantLegal-email">Email</Label>
                    <Input
                      id="representantLegal-email"
                      type="email"
                      value={formData.gouvernance.representantLegal.email || ""}
                      onChange={(e) => handleRepresentativeChange("email", e.target.value)}
                      placeholder="presidence@association.fr"
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="representantLegal-telephone">Téléphone</Label>
                    <Input
                      id="representantLegal-telephone"
                      value={formData.gouvernance.representantLegal.telephone || ""}
                      onChange={(e) => handleRepresentativeChange("telephone", e.target.value)}
                      placeholder="0694 00 00 00"
                    />
                  </div>
                  <div className="space-y-2 md:col-span-2">
                    <Label htmlFor="representantLegal-fonction">Fonction *</Label>
                    <Select
                      value={formData.gouvernance.representantLegal.fonction as LegalRepresentativeRole}
                      onValueChange={(value) => handleRepresentativeChange("fonction", value)}
                    >
                      <SelectTrigger id="representantLegal-fonction">
                        <SelectValue placeholder="Sélectionnez une fonction" />
                      </SelectTrigger>
                      <SelectContent>
                        {legalRepresentativeRoleOptions.map((option) => (
                          <SelectItem key={option.value} value={option.value}>
                            {option.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </div>

              <div className="space-y-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div>
                    <p className="font-medium">Autres membres de gouvernance</p>
                    <p className="text-sm text-muted-foreground">
                      Ajoute des dirigeants ou référents complémentaires si l’association est multi-personnes.
                    </p>
                  </div>
                  <Button type="button" variant="outline" size="sm" onClick={addGovernanceMember} className="w-full sm:w-auto">
                    <Plus className="mr-2 h-4 w-4" />
                    Ajouter un membre
                  </Button>
                </div>

                {formData.gouvernance.membres.length > 0 ? (
                  <div className="space-y-4">
                    {formData.gouvernance.membres.map((member, index) => (
                      <div key={`member-${index}`} className="rounded-lg border p-4">
                        <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                          <div>
                            <p className="font-medium">Membre {index + 1}</p>
                            <p className="text-sm text-muted-foreground">
                              Visible dans le détail de la fiche et dans l’administration.
                            </p>
                          </div>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => removeGovernanceMember(index)}
                            className="self-end sm:self-auto"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                        <div className="grid gap-4 md:grid-cols-2">
                          <div className="space-y-2">
                            <Label>Prénom</Label>
                            <Input
                              value={member.prenom}
                              onChange={(e) => handleGovernanceMemberChange(index, "prenom", e.target.value)}
                              placeholder="Marie"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label>Nom</Label>
                            <Input
                              value={member.nom}
                              onChange={(e) => handleGovernanceMemberChange(index, "nom", e.target.value)}
                              placeholder="Martin"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label>Email</Label>
                            <Input
                              type="email"
                              value={member.email || ""}
                              onChange={(e) => handleGovernanceMemberChange(index, "email", e.target.value)}
                              placeholder="contact@association.fr"
                            />
                          </div>
                          <div className="space-y-2">
                            <Label>Téléphone</Label>
                            <Input
                              value={member.telephone || ""}
                              onChange={(e) => handleGovernanceMemberChange(index, "telephone", e.target.value)}
                              placeholder="0694 00 00 00"
                            />
                          </div>
                          <div className="space-y-2 md:col-span-2">
                            <Label>Fonction</Label>
                            <Select
                              value={member.fonction as GovernanceMemberRole}
                              onValueChange={(value) => handleGovernanceMemberChange(index, "fonction", value)}
                            >
                              <SelectTrigger>
                                <SelectValue placeholder="Sélectionnez une fonction" />
                              </SelectTrigger>
                              <SelectContent>
                                {governanceMemberRoleOptions.map((option) => (
                                  <SelectItem key={option.value} value={option.value}>
                                    {option.label}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
                    Aucun autre membre de gouvernance ajouté pour le moment.
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          <AccountSecurityPanel compact={isMobile || isTablet} />

          {/* Submit button */}
          <div
            className={cn(
              "flex flex-col-reverse gap-3 sm:flex-row sm:justify-end",
              isMobile &&
                "fixed inset-x-0 bottom-0 z-30 border-t bg-background/96 px-4 py-3 shadow-[0_-18px_40px_-28px_rgba(15,23,42,0.4)] backdrop-blur supports-[backdrop-filter]:backdrop-blur"
            )}
          >
            <Link href="/dashboard">
              <Button type="button" variant="outline" className={cn("w-full sm:w-auto", isMobile && "min-h-11")}>
                Annuler
              </Button>
            </Link>
            <Button type="submit" disabled={upsertMutation.isPending} data-tour-id="profile-save" className={cn("w-full sm:w-auto", isMobile && "min-h-11")}>
              {upsertMutation.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : (
                <Save className="mr-2 h-4 w-4" />
              )}
              {upsertMutation.isPending ? "Enregistrement en cours..." : "Enregistrer"}
            </Button>
          </div>
        </form>
      </main>

      <DataPrivacyValidationDialog
        open={privacyDialogOpen}
        onOpenChange={setPrivacyDialogOpen}
        context="save_profile"
        confirmLabel="Valider et enregistrer"
        onConfirm={submitProfileWithPrivacyConsent}
      />
    </div>
  );
}
