import { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
  ArrowLeft, Building2, MapPin, Phone, Mail, Loader2, Users, Home,
  AlertTriangle, Gavel, Save, Pencil, Globe, Shield, Landmark,
  FileText, Plus, Trash2, HelpCircle, Briefcase, BookOpen, Archive, ArchiveRestore, CalendarCheck, ClipboardCheck, FileDown
} from "lucide-react";
import { exportAssociationBinderPdf, exportAssociationFaqsPdf } from "@/lib/associationBinderPdf";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import FeesTab from "@/components/association/FeesTab";
import ViolationTypeManager from "@/components/ViolationTypeManager";
import LogoUpload from "@/components/LogoUpload";
import AnnualMeetingTab from "@/components/association/AnnualMeetingTab";
import PublicPageSettings from "@/components/association/PublicPageSettings";
import CheckLayoutEditor from "@/components/CheckLayoutEditor";
import AmenitiesManager from "@/components/association/AmenitiesManager";
import AssociationDirectoryManager from "@/components/association/AssociationDirectoryManager";
import type { Tables } from "@/integrations/supabase/types";
import { format } from "date-fns";

export default function AssociationDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { toast } = useToast();

  const [association, setAssociation] = useState<Tables<"associations"> | null>(null);
  const [units, setUnits] = useState<Tables<"units">[]>([]);
  const [owners, setOwners] = useState<(Tables<"owners"> & { units?: { unit_number: string } | null })[]>([]);
  const [violations, setViolations] = useState<(Tables<"violations"> & { units?: { unit_number: string } | null })[]>([]);
  const [arcApps, setArcApps] = useState<(Tables<"arc_applications"> & { units?: { unit_number: string } | null })[]>([]);
  const [boardMembers, setBoardMembers] = useState<Tables<"board_members">[]>([]);
  const [bankAccounts, setBankAccounts] = useState<Tables<"bank_accounts">[]>([]);
  const [documents, setDocuments] = useState<Tables<"documents">[]>([]);
  const [faqs, setFaqs] = useState<any[]>([]);
  const [violationTypes, setViolationTypes] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [faqDialog, setFaqDialog] = useState(false);
  const [faqForm, setFaqForm] = useState({ question: "", answer: "" });
  const [savingFaq, setSavingFaq] = useState(false);
  const [vtDialog, setVtDialog] = useState(false);
  const [vtForm, setVtForm] = useState({ category: "", article_section: "", citation_text: "", requested_action: "" });
  const [savingVt, setSavingVt] = useState(false);

  // ── Board member management (writes board_members; can_upload gates board uploads) ──
  const [bmDialog, setBmDialog] = useState(false);
  const [bmEditingId, setBmEditingId] = useState<string | null>(null);
  const [bmForm, setBmForm] = useState({ member_name: "", member_email: "", phone: "", role: "Member", approval_authority: false, can_upload: false });
  const [bmSaving, setBmSaving] = useState(false);
  const [bmDeleteTarget, setBmDeleteTarget] = useState<Tables<"board_members"> | null>(null);

  const openAddBm = () => {
    setBmEditingId(null);
    setBmForm({ member_name: "", member_email: "", phone: "", role: "Member", approval_authority: false, can_upload: false });
    setBmDialog(true);
  };
  const openEditBm = (m: any) => {
    setBmEditingId(m.id);
    setBmForm({
      member_name: m.member_name || "", member_email: m.member_email || "", phone: m.phone || "",
      role: m.role || "Member", approval_authority: !!m.approval_authority, can_upload: !!m.can_upload,
    });
    setBmDialog(true);
  };
  const saveBm = async () => {
    if (!bmForm.member_name.trim()) { toast({ variant: "destructive", title: "Name is required" }); return; }
    setBmSaving(true);
    const payload = {
      association_id: id, member_name: bmForm.member_name.trim(),
      member_email: bmForm.member_email || null, phone: bmForm.phone || null,
      role: bmForm.role || "Member", approval_authority: bmForm.approval_authority, can_upload: bmForm.can_upload,
    };
    const { error } = bmEditingId
      ? await supabase.from("board_members").update(payload as any).eq("id", bmEditingId)
      : await supabase.from("board_members").insert(payload as any);
    if (error) toast({ variant: "destructive", title: "Error", description: error.message });
    else { toast({ title: bmEditingId ? "Board member updated" : "Board member added" }); setBmDialog(false); fetchAll(); }
    setBmSaving(false);
  };
  const deleteBm = async () => {
    if (!bmDeleteTarget) return;
    const { error } = await supabase.from("board_members").delete().eq("id", bmDeleteTarget.id);
    if (error) toast({ variant: "destructive", title: "Error", description: error.message });
    else { toast({ title: "Board member removed" }); fetchAll(); }
    setBmDeleteTarget(null);
  };

  // Custom fields
  const [customFields, setCustomFields] = useState<any[]>([]);
  const [cfDialog, setCfDialog] = useState(false);
  const [cfForm, setCfForm] = useState<{ id?: string; field_label: string; field_value: string }>({ field_label: "", field_value: "" });
  const [savingCf, setSavingCf] = useState(false);

  // Editing state
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState({
    name: "", address: "", city: "", state: "", zip: "", phone: "", email: "",
    management_fee: "", fiscal_year_start: "", zoho_organization_id: "", accounting_system: "buildium",
    attorney_name: "", attorney_firm: "", attorney_email: "", attorney_phone: "",
    cpa_name: "", cpa_firm: "", cpa_email: "", cpa_phone: "",
    insurance_provider: "", insurance_expiration: "", website: "",
    care_of_address: "", mailing_address: "", contact_email: "",
  });
  const [saving, setSaving] = useState(false);
  const [showDeleteAlert, setShowDeleteAlert] = useState(false);
  const [isActionLoading, setIsActionLoading] = useState(false);

  useEffect(() => {
    if (id) fetchAll();
  }, [id]);

  const fetchAll = async () => {
    setLoading(true);
    const [assocRes, unitsRes, ownersRes, violRes, arcRes, boardRes, bankRes, docsRes, faqsRes, vtRes, cfRes] = await Promise.all([
      supabase.from("associations").select("*").eq("id", id!).single(),
      supabase.from("units").select("*").eq("association_id", id!).order("unit_number"),
      supabase.from("owners").select("*, units(unit_number)").eq("status", "active").eq("association_id", id!).order("last_name"),
      supabase.from("violations").select("*, units(unit_number)").eq("association_id", id!).order("created_at", { ascending: false }).limit(20),
      supabase.from("arc_applications").select("*, units(unit_number)").eq("association_id", id!).order("created_at", { ascending: false }).limit(20),
      supabase.from("board_members").select("*").eq("association_id", id!).order("member_name"),
      supabase.from("bank_accounts").select("*").eq("association_id", id!).order("account_name"),
      supabase.from("documents").select("*").eq("association_id", id!).order("created_at", { ascending: false }),
      supabase.from("association_faqs").select("*").eq("association_id", id!).order("sort_order"),
      supabase.from("violation_types").select("*").eq("association_id", id!).order("category"),
      supabase.from("association_custom_fields" as any).select("*").eq("association_id", id!).order("sort_order").order("created_at"),
    ]);

    if (assocRes.data) {
      setAssociation(assocRes.data);
      setEditForm({
        name: assocRes.data.name || "",
        address: assocRes.data.address || "",
        city: assocRes.data.city || "",
        state: assocRes.data.state || "",
        zip: assocRes.data.zip || "",
        phone: assocRes.data.phone || "",
        email: assocRes.data.email || "",
        management_fee: assocRes.data.management_fee?.toString() || "",
        fiscal_year_start: assocRes.data.fiscal_year_start?.toString() || "1",
        zoho_organization_id: assocRes.data.zoho_organization_id || "",
        accounting_system: ((assocRes.data as any).accounting_system as string) || "buildium",
        attorney_name: (assocRes.data as any).attorney_name || "",
        attorney_firm: (assocRes.data as any).attorney_firm || "",
        attorney_email: (assocRes.data as any).attorney_email || "",
        attorney_phone: (assocRes.data as any).attorney_phone || "",
        cpa_name: (assocRes.data as any).cpa_name || "",
        cpa_firm: (assocRes.data as any).cpa_firm || "",
        cpa_email: (assocRes.data as any).cpa_email || "",
        cpa_phone: (assocRes.data as any).cpa_phone || "",
        insurance_provider: (assocRes.data as any).insurance_provider || "",
        insurance_expiration: (assocRes.data as any).insurance_expiration || "",
        website: (assocRes.data as any).website || "",
        care_of_address: (assocRes.data as any).care_of_address || "",
        mailing_address: (assocRes.data as any).mailing_address || "",
        contact_email: (assocRes.data as any).contact_email || "",
      });
    }
    if (unitsRes.data) setUnits(unitsRes.data);
    if (ownersRes.data) setOwners(ownersRes.data);
    if (violRes.data) setViolations(violRes.data);
    if (arcRes.data) setArcApps(arcRes.data);
    if (boardRes.data) setBoardMembers(boardRes.data);
    if (bankRes.data) setBankAccounts(bankRes.data);
    if (docsRes.data) setDocuments(docsRes.data);
    if (faqsRes.data) setFaqs(faqsRes.data);
    if (vtRes.data) setViolationTypes(vtRes.data);
    if (cfRes.data) setCustomFields(cfRes.data as any[]);
    setLoading(false);
  };

  const openCustomFieldDialog = (field?: any) => {
    if (field) {
      setCfForm({ id: field.id, field_label: field.field_label || "", field_value: field.field_value || "" });
    } else {
      setCfForm({ field_label: "", field_value: "" });
    }
    setCfDialog(true);
  };

  const handleSaveCustomField = async () => {
    if (!cfForm.field_label.trim()) return;
    setSavingCf(true);
    const { data: { user } } = await supabase.auth.getUser();
    let error;
    if (cfForm.id) {
      const res = await supabase.from("association_custom_fields" as any)
        .update({ field_label: cfForm.field_label, field_value: cfForm.field_value } as any)
        .eq("id", cfForm.id);
      error = res.error;
    } else {
      const res = await supabase.from("association_custom_fields" as any).insert({
        association_id: id!,
        field_label: cfForm.field_label,
        field_value: cfForm.field_value,
        sort_order: customFields.length,
        created_by: user?.id || null,
      } as any);
      error = res.error;
    }
    setSavingCf(false);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: cfForm.id ? "Custom field updated" : "Custom field added" });
      setCfDialog(false);
      setCfForm({ field_label: "", field_value: "" });
      fetchAll();
    }
  };

  const handleDeleteCustomField = async (fieldId: string) => {
    const { error } = await supabase.from("association_custom_fields" as any).delete().eq("id", fieldId);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Custom field deleted" });
      fetchAll();
    }
  };

  const handleAddFaq = async () => {
    if (!faqForm.question.trim()) return;
    setSavingFaq(true);
    const { error } = await supabase.from("association_faqs").insert({
      association_id: id!,
      question: faqForm.question,
      answer: faqForm.answer,
      sort_order: faqs.length,
    });
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "FAQ added" });
      setFaqDialog(false);
      setFaqForm({ question: "", answer: "" });
      fetchAll();
    }
    setSavingFaq(false);
  };

  const handleDeleteFaq = async (faqId: string) => {
    const { error } = await supabase.from("association_faqs").delete().eq("id", faqId);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      setFaqs(faqs.filter(f => f.id !== faqId));
    }
  };

  const handleSave = async () => {
    setSaving(true);
    const { error } = await supabase.from("associations").update({
      name: editForm.name,
      address: editForm.address,
      city: editForm.city,
      state: editForm.state,
      zip: editForm.zip,
      phone: editForm.phone,
      email: editForm.email,
      management_fee: editForm.management_fee ? Number(editForm.management_fee) : null,
      fiscal_year_start: editForm.fiscal_year_start ? Number(editForm.fiscal_year_start) : 1,
      zoho_organization_id: editForm.zoho_organization_id || null,
      accounting_system: editForm.accounting_system || "buildium",
      attorney_name: editForm.attorney_name || null,
      attorney_firm: editForm.attorney_firm || null,
      attorney_email: editForm.attorney_email || null,
      attorney_phone: editForm.attorney_phone || null,
      cpa_name: editForm.cpa_name || null,
      cpa_firm: editForm.cpa_firm || null,
      cpa_email: editForm.cpa_email || null,
      cpa_phone: editForm.cpa_phone || null,
      insurance_provider: editForm.insurance_provider || null,
      insurance_expiration: editForm.insurance_expiration || null,
      website: editForm.website || null,
      care_of_address: editForm.care_of_address || null,
      mailing_address: editForm.mailing_address || null,
      contact_email: editForm.contact_email || null,
    } as any).eq("id", id!);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Association updated" });
      setIsEditing(false);
      fetchAll();
    }
    setSaving(false);
  };

  const handleArchiveToggle = async () => {
    setIsActionLoading(true);
    const newStatus = (association as any).status === "archived" ? "active" : "archived";
    const { error } = await supabase.from("associations").update({ status: newStatus } as any).eq("id", id!);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: newStatus === "archived" ? "Association archived" : "Association restored" });
      fetchAll();
    }
    setIsActionLoading(false);
  };

  const handleDelete = async () => {
    setIsActionLoading(true);
    const { error } = await supabase.from("associations").delete().eq("id", id!);
    if (error) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } else {
      toast({ title: "Association deleted" });
      navigate("/dashboard/associations");
    }
    setIsActionLoading(false);
    setShowDeleteAlert(false);
  };

  if (loading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!association) {
    return (
      <div className="flex flex-col h-[50vh] items-center justify-center p-8 text-center space-y-4">
        <Building2 className="h-12 w-12 text-muted-foreground/50" />
        <h2 className="text-xl font-semibold">Association Not Found</h2>
        <Button variant="outline" onClick={() => navigate("/dashboard/associations")}>
          <ArrowLeft className="w-4 h-4 mr-2" /> Back to Associations
        </Button>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={() => { localStorage.setItem("assoc_dir_archived", "false"); navigate("/dashboard/associations"); }}>
          <ArrowLeft className="h-5 w-5" />
        </Button>
        <div className="flex-1">
          <h1 className="text-2xl font-bold flex items-center gap-2">
            {association.name}
            {(association as any).status === "archived" && (
              <Badge variant="secondary" className="ml-2">Archived</Badge>
            )}
          </h1>
          <p className="text-sm text-muted-foreground flex items-center gap-1 mt-1">
            <Building2 className="h-3.5 w-3.5" />
            Client Details & Management
          </p>
        </div>
        <div className="flex gap-2 flex-wrap">
          <Button
            variant="outline"
            onClick={() => exportAssociationBinderPdf({ association, boardMembers, bankAccounts, customFields, units, owners })}
            className="gap-2"
          >
            <FileDown className="h-4 w-4" /> Export Binder PDF
          </Button>
          <Button
            variant="outline"
            onClick={() => exportAssociationFaqsPdf({ association, faqs })}
            className="gap-2"
          >
            <HelpCircle className="h-4 w-4" /> Export FAQs PDF
          </Button>
          <Button variant="outline" onClick={() => setIsEditing(true)} className="gap-2">
            <Pencil className="h-4 w-4" /> Edit Details
          </Button>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="icon">
                <AlertTriangle className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={handleArchiveToggle} disabled={isActionLoading}>
                {(association as any).status === "archived" ? (
                  <><ArchiveRestore className="h-4 w-4 mr-2" /> Restore Association</>
                ) : (
                  <><Archive className="h-4 w-4 mr-2" /> Archive Association</>
                )}
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => setShowDeleteAlert(true)} className="text-destructive focus:text-destructive" disabled={isActionLoading}>
                <Trash2 className="h-4 w-4 mr-2" /> Delete Association
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Main Tabs */}
      <Tabs defaultValue="overview">
        <TabsList className="flex-wrap">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="documents">Documents</TabsTrigger>
          <TabsTrigger value="bank-accounts">Bank Accounts</TabsTrigger>
          <TabsTrigger value="violation-types">Violation Types</TabsTrigger>
          <TabsTrigger value="association-info">Association Info</TabsTrigger>
          <TabsTrigger value="directory">Directory</TabsTrigger>
          <TabsTrigger value="amenities">Amenities</TabsTrigger>
          <TabsTrigger value="annual-meeting">Annual Meeting</TabsTrigger>
          <TabsTrigger value="public-page">Public Page</TabsTrigger>
          <TabsTrigger value="fees">Fees</TabsTrigger>
          <TabsTrigger value="check-layout">Check Layout</TabsTrigger>
          <Button
            variant="outline"
            size="sm"
            className="ml-2"
            onClick={() => navigate(`/dashboard/associations/${id}/compliance`)}
          >
            <ClipboardCheck className="h-4 w-4 mr-1" /> Compliance Checklist
          </Button>
        </TabsList>

        {/* ─── Overview Tab ─── */}
        <TabsContent value="overview" className="mt-6 space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Contact Information */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Contact Information</CardTitle>
                <CardDescription>Primary contact details for the association</CardDescription>
              </CardHeader>
              <CardContent className="space-y-5">
                <div className="flex items-start gap-3">
                  <Mail className="h-5 w-5 text-primary mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Email Address</p>
                    <p className="text-sm font-medium">{association.email || "No email provided"}</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Phone className="h-5 w-5 text-primary mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Phone Number</p>
                    <p className="text-sm font-medium">{association.phone || "No phone provided"}</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <MapPin className="h-5 w-5 text-destructive mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Mailing Address</p>
                    <p className="text-sm font-medium">
                      {association.address || "No address provided"}
                      {(association.city || association.state) && (
                        <><br />{association.city}{association.state && `, ${association.state}`} {association.zip}</>
                      )}
                    </p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Globe className="h-5 w-5 text-primary mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Website</p>
                    <p className="text-sm font-medium text-muted-foreground">No website provided</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Internal Details */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Internal Details</CardTitle>
                <CardDescription>Management information</CardDescription>
              </CardHeader>
              <CardContent className="space-y-5">
                <div className="flex items-start gap-3">
                  <Building2 className="h-5 w-5 text-muted-foreground mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Company</p>
                    <p className="text-sm font-medium">{association.name}</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Briefcase className="h-5 w-5 text-muted-foreground mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Management Fee</p>
                    <p className="text-sm font-medium">{association.management_fee ? `$${Number(association.management_fee).toFixed(2)}` : "—"}</p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Users className="h-5 w-5 text-muted-foreground mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Board Members</p>
                    <p className="text-sm font-medium">
                      {boardMembers.length > 0
                        ? boardMembers.map(m => m.member_name).join(", ")
                        : "—"}
                    </p>
                  </div>
                </div>
                <div className="flex items-start gap-3">
                  <Shield className="h-5 w-5 text-muted-foreground mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">Fiscal Year Start</p>
                    <p className="text-sm font-medium">Month {association.fiscal_year_start || 1}</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* Stats Summary */}
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {[
              { label: "Units", value: units.length, icon: Home },
              { label: "Owners", value: owners.length, icon: Users },
              { label: "Open Violations", value: violations.filter(v => v.status === "open" || v.status === "escalated" || v.status === "recommended_for_fining").length, icon: AlertTriangle },
              { label: "ARC Pending", value: arcApps.filter(a => a.status === "submitted").length, icon: Gavel },
            ].map((stat) => (
              <Card key={stat.label}>
                <CardContent className="p-4 flex items-center gap-3">
                  <div className="p-2 rounded-lg bg-primary/10">
                    <stat.icon className="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <p className="text-2xl font-bold">{stat.value}</p>
                    <p className="text-xs text-muted-foreground">{stat.label}</p>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Association Logo */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Association Logo</CardTitle>
              <CardDescription>Upload a logo for this association's PDFs, reports, and documents.</CardDescription>
            </CardHeader>
            <CardContent>
              <LogoUpload
                currentUrl={(association as any).logo_url || null}
                storagePath={`associations/${id}`}
                onUploaded={async (url) => {
                  await supabase.from("associations").update({ logo_url: url } as any).eq("id", id!);
                  fetchAll();
                }}
                label="Association Logo"
              />
            </CardContent>
          </Card>

          {/* Custom Fields */}
          <Card>
            <CardHeader className="flex-row items-center justify-between">
              <div className="flex items-center gap-2">
                <BookOpen className="h-5 w-5 text-primary" />
                <div>
                  <CardTitle>Custom Fields</CardTitle>
                  <CardDescription>Add your own labeled fields to display on this overview.</CardDescription>
                </div>
              </div>
              <Button onClick={() => openCustomFieldDialog()} className="gap-2">
                <Plus className="h-4 w-4" /> Add Field
              </Button>
            </CardHeader>
            <CardContent>
              {customFields.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">No custom fields yet. Add your first field.</p>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {customFields.map((field) => (
                    <div key={field.id} className="border rounded-lg p-4 flex items-start justify-between gap-3">
                      <div className="min-w-0 flex-1">
                        <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">{field.field_label}</p>
                        <p className="text-sm font-medium whitespace-pre-wrap break-words mt-1">{field.field_value || "—"}</p>
                      </div>
                      <div className="flex gap-1">
                        <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openCustomFieldDialog(field)}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => handleDeleteCustomField(field.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Association FAQs */}
          <Card>
            <CardHeader className="flex-row items-center justify-between">
              <div className="flex items-center gap-2">
                <HelpCircle className="h-5 w-5 text-primary" />
                <div>
                  <CardTitle>Association FAQs</CardTitle>
                  <CardDescription>Common questions and information for this association.</CardDescription>
                </div>
              </div>
              <Button onClick={() => setFaqDialog(true)} className="gap-2">
                <Plus className="h-4 w-4" /> Add Question
              </Button>
            </CardHeader>
            <CardContent>
              {faqs.length === 0 ? (
                <p className="text-sm text-muted-foreground text-center py-8">No FAQs yet. Add your first question.</p>
              ) : (
                <div className="space-y-4">
                  {faqs.map((faq) => (
                    <div key={faq.id} className="border rounded-lg p-4 space-y-2">
                      <div className="flex items-start justify-between">
                        <h4 className="font-semibold text-sm">{faq.question}</h4>
                        <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => handleDeleteFaq(faq.id)}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                      {faq.answer && <p className="text-sm text-muted-foreground">{faq.answer}</p>}
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Documents Tab ─── */}
        <TabsContent value="documents" className="mt-6">
          <Card>
            <CardHeader className="flex-row items-center justify-between">
              <div>
                <CardTitle>Documents</CardTitle>
                <CardDescription>Files and documents for this association</CardDescription>
              </div>
            </CardHeader>
            <CardContent>
              {documents.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  <FileText className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>No documents uploaded yet</p>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Title</TableHead>
                      <TableHead>Category</TableHead>
                      <TableHead>File</TableHead>
                      <TableHead>Uploaded</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {documents.map((doc) => (
                      <TableRow key={doc.id}>
                        <TableCell className="font-medium">{doc.title}</TableCell>
                        <TableCell><Badge variant="secondary">{doc.category || "General"}</Badge></TableCell>
                        <TableCell className="text-muted-foreground">{doc.file_name || "—"}</TableCell>
                        <TableCell className="text-muted-foreground">{format(new Date(doc.created_at), "MMM d, yyyy")}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Bank Accounts Tab ─── */}
        <TabsContent value="bank-accounts" className="mt-6">
          <Card>
            <CardHeader className="flex-row items-center justify-between">
              <div>
                <CardTitle className="flex items-center gap-2"><Landmark className="h-5 w-5" /> Bank Accounts</CardTitle>
                <CardDescription>Manage assigned bank accounts for this client</CardDescription>
              </div>
            </CardHeader>
            <CardContent>
              {bankAccounts.length === 0 ? (
                <div className="border-2 border-dashed rounded-lg text-center py-12 text-muted-foreground">
                  <Landmark className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>No bank accounts assigned</p>
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Account Name</TableHead>
                      <TableHead>Bank</TableHead>
                      <TableHead>Type</TableHead>
                      <TableHead>Balance</TableHead>
                      <TableHead>Status</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {bankAccounts.map((acct) => (
                      <TableRow key={acct.id}>
                        <TableCell className="font-medium">{acct.account_name}</TableCell>
                        <TableCell className="text-muted-foreground">{acct.bank_name || "—"}</TableCell>
                        <TableCell><Badge variant="secondary">{acct.account_type || acct.account_category}</Badge></TableCell>
                        <TableCell className="font-medium">{acct.current_balance != null ? `$${Number(acct.current_balance).toLocaleString("en-US", { minimumFractionDigits: 2 })}` : "—"}</TableCell>
                        <TableCell><Badge variant={acct.status === "active" ? "default" : "destructive"}>{acct.status}</Badge></TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Units & Owners Tab ─── */}
        <TabsContent value="units-owners" className="mt-6 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Units ({units.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Unit #</TableHead>
                    <TableHead>Address</TableHead>
                    <TableHead>Bed/Bath</TableHead>
                    <TableHead>Sq Ft</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {units.length === 0 ? (
                    <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">No units</TableCell></TableRow>
                  ) : units.map((u) => (
                    <TableRow key={u.id}>
                      <TableCell className="font-medium">{u.unit_number}</TableCell>
                      <TableCell className="text-muted-foreground">{u.address || "—"}</TableCell>
                      <TableCell>{u.bedrooms ?? "—"} / {u.bathrooms ?? "—"}</TableCell>
                      <TableCell>{u.sqft?.toLocaleString() || "—"}</TableCell>
                      <TableCell><Badge variant={u.status === "active" ? "default" : "destructive"}>{u.status || "active"}</Badge></TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle>Owners ({owners.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead>
                    <TableHead>Unit</TableHead>
                    <TableHead>Email</TableHead>
                    <TableHead>Phone</TableHead>
                    <TableHead>Balance</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {owners.length === 0 ? (
                    <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">No owners</TableCell></TableRow>
                  ) : owners.map((o) => (
                    <TableRow key={o.id}>
                      <TableCell className="font-medium">{o.first_name} {o.last_name}</TableCell>
                      <TableCell>{o.units?.unit_number ?? "—"}</TableCell>
                      <TableCell className="text-muted-foreground">{o.email || "—"}</TableCell>
                      <TableCell className="text-muted-foreground">{o.phone || "—"}</TableCell>
                      <TableCell className={Number(o.balance) > 0 ? "text-destructive font-medium" : ""}>${Number(o.balance).toFixed(2)}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Violations Tab ─── */}
        <TabsContent value="violations" className="mt-6 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Violations ({violations.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Title</TableHead>
                    <TableHead>Unit</TableHead>
                    <TableHead>Priority</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Date</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {violations.length === 0 ? (
                    <TableRow><TableCell colSpan={5} className="text-center py-8 text-muted-foreground">No violations</TableCell></TableRow>
                  ) : violations.map((v) => (
                    <TableRow key={v.id}>
                      <TableCell className="font-medium">{v.title}</TableCell>
                      <TableCell>{v.units?.unit_number ?? "—"}</TableCell>
                      <TableCell>{v.priority}</TableCell>
                      <TableCell><Badge variant={v.status === "open" ? "destructive" : "default"}>{v.status}</Badge></TableCell>
                      <TableCell className="text-muted-foreground">{format(new Date(v.created_at), "MMM d, yyyy")}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── ARC Applications Tab ─── */}
        <TabsContent value="arc" className="mt-6 space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>ARC Applications ({arcApps.length})</CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Title</TableHead>
                    <TableHead>Unit</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Status</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {arcApps.length === 0 ? (
                    <TableRow><TableCell colSpan={4} className="text-center py-8 text-muted-foreground">No applications</TableCell></TableRow>
                  ) : arcApps.map((a) => (
                    <TableRow key={a.id}>
                      <TableCell className="font-medium">{a.title}</TableCell>
                      <TableCell>{a.units?.unit_number ?? "—"}</TableCell>
                      <TableCell className="text-muted-foreground">{a.project_type || "—"}</TableCell>
                      <TableCell><Badge variant={a.status === "denied" ? "destructive" : "default"}>{a.status?.replace("_", " ")}</Badge></TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Violation Types Tab ─── */}
        <TabsContent value="violation-types" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle>Violation Types Configuration</CardTitle>
              <CardDescription>Customize standard violation categories and citations for this client.</CardDescription>
            </CardHeader>
            <CardContent>
              <ViolationTypeManager associationId={id!} />
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Fees Tab ─── */}
        <TabsContent value="fees" className="mt-6">
          <FeesTab associationId={id!} associationName={association.name} />
        </TabsContent>

        {/* ─── Association Info Tab ─── */}
        <TabsContent value="association-info" className="mt-6">
          <Card>
            <CardHeader>
              <CardTitle>Association Configuration</CardTitle>
              <CardDescription>Advanced settings and information for this client.</CardDescription>
            </CardHeader>
            <CardContent className="space-y-8">
              {/* Mailing & Contact Information */}
              <div>
                <h3 className="text-base font-semibold mb-1">Mailing & Contact Information</h3>
                <p className="text-sm text-muted-foreground mb-4">Update the primary contact details for this association. These details are used in generated documents.</p>
                <div className="space-y-4">
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">c/o Address Line</Label>
                    <p className="text-sm font-medium mt-1">{(association as any).care_of_address || "—"}</p>
                    <p className="text-xs text-muted-foreground mt-0.5">Appears above the mailing address in standard letter headers.</p>
                  </div>
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Mailing Address</Label>
                    <p className="text-sm font-medium mt-1 whitespace-pre-line">{(association as any).mailing_address || association.address || "—"}</p>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <Label className="text-xs font-semibold text-muted-foreground uppercase">Phone Number</Label>
                      <p className="text-sm font-medium mt-1">{association.phone || "—"}</p>
                    </div>
                    <div>
                      <Label className="text-xs font-semibold text-muted-foreground uppercase">Primary Email</Label>
                      <p className="text-sm font-medium mt-1">{association.email || "—"}</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* Digital Presence */}
              <div>
                <h3 className="text-base font-semibold mb-1">Digital Presence</h3>
                <p className="text-sm text-muted-foreground mb-4">Stored in Association Info records.</p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Public/Contact Email</Label>
                    <p className="text-sm font-medium mt-1">{(association as any).contact_email || "—"}</p>
                  </div>
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Association Website</Label>
                    <p className="text-sm font-medium mt-1">{(association as any).website || "—"}</p>
                  </div>
                </div>
              </div>

              {/* Attorney & CPA */}
              <div>
                <h3 className="text-base font-semibold mb-1">Professional Contacts</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                  <div className="space-y-3">
                    <h4 className="text-sm font-semibold flex items-center gap-2"><Gavel className="h-4 w-4 text-muted-foreground" /> Attorney</h4>
                    <div><Label className="text-xs text-muted-foreground uppercase">Name</Label><p className="text-sm mt-0.5">{(association as any).attorney_name || "—"}</p></div>
                    <div><Label className="text-xs text-muted-foreground uppercase">Firm</Label><p className="text-sm mt-0.5">{(association as any).attorney_firm || "—"}</p></div>
                    <div><Label className="text-xs text-muted-foreground uppercase">Email</Label><p className="text-sm mt-0.5">{(association as any).attorney_email || "—"}</p></div>
                    <div><Label className="text-xs text-muted-foreground uppercase">Phone</Label><p className="text-sm mt-0.5">{(association as any).attorney_phone || "—"}</p></div>
                  </div>
                  <div className="space-y-3">
                    <h4 className="text-sm font-semibold flex items-center gap-2"><BookOpen className="h-4 w-4 text-muted-foreground" /> CPA / Accountant</h4>
                    <div><Label className="text-xs text-muted-foreground uppercase">Name</Label><p className="text-sm mt-0.5">{(association as any).cpa_name || "—"}</p></div>
                    <div><Label className="text-xs text-muted-foreground uppercase">Firm</Label><p className="text-sm mt-0.5">{(association as any).cpa_firm || "—"}</p></div>
                    <div><Label className="text-xs text-muted-foreground uppercase">Email</Label><p className="text-sm mt-0.5">{(association as any).cpa_email || "—"}</p></div>
                    <div><Label className="text-xs text-muted-foreground uppercase">Phone</Label><p className="text-sm mt-0.5">{(association as any).cpa_phone || "—"}</p></div>
                  </div>
                </div>
              </div>

              {/* Insurance & Financial */}
              <div>
                <h3 className="text-base font-semibold mb-4">Insurance & Financial</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Insurance Provider</Label>
                    <p className="text-sm font-medium mt-1">{(association as any).insurance_provider || "—"}</p>
                  </div>
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Insurance Expiration</Label>
                    <p className="text-sm font-medium mt-1">{(association as any).insurance_expiration || "—"}</p>
                  </div>
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Fiscal Year Start</Label>
                    <p className="text-sm font-medium mt-1">Month {association.fiscal_year_start || 1}</p>
                  </div>
                  <div>
                    <Label className="text-xs font-semibold text-muted-foreground uppercase">Management Fee</Label>
                    <p className="text-sm font-medium mt-1">{association.management_fee ? `$${Number(association.management_fee).toFixed(2)}` : "—"}</p>
                  </div>
                </div>
              </div>


              {/* Board Members */}
              <div>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-base font-semibold">Board Members</h3>
                  <Button size="sm" variant="outline" className="gap-1" onClick={openAddBm}><Plus className="h-4 w-4" /> Add Member</Button>
                </div>
                {boardMembers.length > 0 ? (
                  <div className="space-y-2">
                    {boardMembers.map(m => (
                      <div key={m.id} className="flex items-center justify-between gap-2 text-sm border rounded-md px-3 py-2">
                        <div className="min-w-0">
                          <span className="font-medium">{m.member_name}</span>
                          {m.member_email && <span className="text-muted-foreground text-xs ml-2">{m.member_email}</span>}
                        </div>
                        <div className="flex items-center gap-2 shrink-0">
                          {m.role && <Badge variant="secondary" className="text-xs">{m.role}</Badge>}
                          {(m as any).approval_authority && <Badge className="text-xs bg-emerald-500/10 text-emerald-700 border-emerald-200 hover:bg-emerald-500/10">Approver</Badge>}
                          {(m as any).can_upload && <Badge className="text-xs bg-blue-500/10 text-blue-700 border-blue-200 hover:bg-blue-500/10">Uploads</Badge>}
                          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => openEditBm(m)}><Pencil className="h-3.5 w-3.5" /></Button>
                          <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive hover:text-destructive" onClick={() => setBmDeleteTarget(m)}><Trash2 className="h-3.5 w-3.5" /></Button>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : <p className="text-sm text-muted-foreground">No board members defined.</p>}
              </div>

              {/* Board Member add/edit dialog */}
              <Dialog open={bmDialog} onOpenChange={setBmDialog}>
                <DialogContent>
                  <DialogHeader><DialogTitle>{bmEditingId ? "Edit" : "Add"} Board Member</DialogTitle></DialogHeader>
                  <div className="space-y-4">
                    <div className="space-y-2"><Label>Name *</Label><Input value={bmForm.member_name} onChange={e => setBmForm({ ...bmForm, member_name: e.target.value })} /></div>
                    <div className="space-y-2"><Label>Email</Label><Input type="email" value={bmForm.member_email} onChange={e => setBmForm({ ...bmForm, member_email: e.target.value })} placeholder="Matches the member's portal login" /></div>
                    <div className="space-y-2"><Label>Phone</Label><Input value={bmForm.phone} onChange={e => setBmForm({ ...bmForm, phone: e.target.value })} /></div>
                    <div className="space-y-2">
                      <Label>Role</Label>
                      <Select value={bmForm.role} onValueChange={v => setBmForm({ ...bmForm, role: v })}>
                        <SelectTrigger><SelectValue /></SelectTrigger>
                        <SelectContent>
                          <SelectItem value="President">President</SelectItem>
                          <SelectItem value="Vice President">Vice President</SelectItem>
                          <SelectItem value="Treasurer">Treasurer</SelectItem>
                          <SelectItem value="Secretary">Secretary</SelectItem>
                          <SelectItem value="Member">Member</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="flex items-center gap-3">
                      <Switch checked={bmForm.approval_authority} onCheckedChange={v => setBmForm({ ...bmForm, approval_authority: v })} />
                      <Label>Approval authority</Label>
                    </div>
                    <div className="flex items-center gap-3">
                      <Switch checked={bmForm.can_upload} onCheckedChange={v => setBmForm({ ...bmForm, can_upload: v })} />
                      <Label>Allow document &amp; bid/quote uploads</Label>
                    </div>
                  </div>
                  <DialogFooter>
                    <Button variant="outline" onClick={() => setBmDialog(false)}>Cancel</Button>
                    <Button onClick={saveBm} disabled={bmSaving} className="gap-2">
                      {bmSaving && <Loader2 className="h-4 w-4 animate-spin" />}{bmEditingId ? "Update" : "Add"}
                    </Button>
                  </DialogFooter>
                </DialogContent>
              </Dialog>

              <AlertDialog open={!!bmDeleteTarget} onOpenChange={(o) => { if (!o) setBmDeleteTarget(null); }}>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Remove board member?</AlertDialogTitle>
                    <AlertDialogDescription>
                      Remove {bmDeleteTarget?.member_name} from this association's board. This cannot be undone.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={deleteBm} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">Remove</AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </CardContent>
          </Card>
        </TabsContent>

        {/* ─── Amenities Tab ─── */}
        <TabsContent value="directory" className="mt-6">
          <AssociationDirectoryManager associationId={id!} />
        </TabsContent>

        {/* ─── Amenities Tab ─── */}
        <TabsContent value="amenities" className="mt-6">
          <AmenitiesManager associationId={id!} />
        </TabsContent>

        {/* ─── Annual Meeting Tab ─── */}
        <TabsContent value="annual-meeting" className="mt-6">
          <AnnualMeetingTab associationId={id!} associationName={association?.name || ""} />
        </TabsContent>

        {/* ─── Public Page Tab ─── */}
        <TabsContent value="public-page" className="mt-6">
          <PublicPageSettings associationId={id!} associationName={association?.name || ""} />
        </TabsContent>

        {/* ─── Check Layout Tab ─── */}
        <TabsContent value="check-layout" className="mt-6">
          <CheckLayoutEditor associationId={id!} associationName={association?.name || ""} />
        </TabsContent>
      </Tabs>

      {/* Edit Dialog */}
      <Dialog open={isEditing} onOpenChange={setIsEditing}>
        <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Association Details</DialogTitle>
          </DialogHeader>
          <div className="space-y-6">
            {/* Basic Info */}
            <div>
              <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Basic Information</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2 md:col-span-2"><Label>Name</Label><Input value={editForm.name} onChange={(e) => setEditForm({ ...editForm, name: e.target.value })} /></div>
                <div className="space-y-2"><Label>Email</Label><Input value={editForm.email} onChange={(e) => setEditForm({ ...editForm, email: e.target.value })} type="email" /></div>
                <div className="space-y-2"><Label>Phone</Label><Input value={editForm.phone} onChange={(e) => setEditForm({ ...editForm, phone: e.target.value })} /></div>
                <div className="space-y-2"><Label>Website</Label><Input value={editForm.website} onChange={(e) => setEditForm({ ...editForm, website: e.target.value })} placeholder="https://example.com" /></div>
                <div className="space-y-2"><Label>Contact Email (Public)</Label><Input value={editForm.contact_email} onChange={(e) => setEditForm({ ...editForm, contact_email: e.target.value })} placeholder="contact@example.com" type="email" /></div>
              </div>
            </div>

            {/* Address */}
            <div>
              <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Address & Mailing</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2 md:col-span-2"><Label>Street Address</Label><Input value={editForm.address} onChange={(e) => setEditForm({ ...editForm, address: e.target.value })} /></div>
                <div className="space-y-2"><Label>City</Label><Input value={editForm.city} onChange={(e) => setEditForm({ ...editForm, city: e.target.value })} /></div>
                <div className="space-y-2"><Label>State</Label><Input value={editForm.state} onChange={(e) => setEditForm({ ...editForm, state: e.target.value })} /></div>
                <div className="space-y-2"><Label>ZIP</Label><Input value={editForm.zip} onChange={(e) => setEditForm({ ...editForm, zip: e.target.value })} /></div>
                <div className="space-y-2"><Label>C/O Address (Care Of)</Label><Input value={editForm.care_of_address} onChange={(e) => setEditForm({ ...editForm, care_of_address: e.target.value })} placeholder="e.g. c/o Avria Management" /></div>
                <div className="space-y-2 md:col-span-2"><Label>Mailing Address</Label><Textarea value={editForm.mailing_address} onChange={(e) => setEditForm({ ...editForm, mailing_address: e.target.value })} placeholder="P.O. Box 560099, Rockledge, FL 32956" rows={2} /></div>
              </div>
            </div>

            {/* Attorney */}
            <div>
              <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Attorney</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2"><Label>Attorney Name</Label><Input value={editForm.attorney_name} onChange={(e) => setEditForm({ ...editForm, attorney_name: e.target.value })} /></div>
                <div className="space-y-2"><Label>Firm</Label><Input value={editForm.attorney_firm} onChange={(e) => setEditForm({ ...editForm, attorney_firm: e.target.value })} /></div>
                <div className="space-y-2"><Label>Email</Label><Input value={editForm.attorney_email} onChange={(e) => setEditForm({ ...editForm, attorney_email: e.target.value })} type="email" /></div>
                <div className="space-y-2"><Label>Phone</Label><Input value={editForm.attorney_phone} onChange={(e) => setEditForm({ ...editForm, attorney_phone: e.target.value })} /></div>
              </div>
            </div>

            {/* CPA */}
            <div>
              <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">CPA / Accountant</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2"><Label>CPA Name</Label><Input value={editForm.cpa_name} onChange={(e) => setEditForm({ ...editForm, cpa_name: e.target.value })} /></div>
                <div className="space-y-2"><Label>Firm</Label><Input value={editForm.cpa_firm} onChange={(e) => setEditForm({ ...editForm, cpa_firm: e.target.value })} /></div>
                <div className="space-y-2"><Label>Email</Label><Input value={editForm.cpa_email} onChange={(e) => setEditForm({ ...editForm, cpa_email: e.target.value })} type="email" /></div>
                <div className="space-y-2"><Label>Phone</Label><Input value={editForm.cpa_phone} onChange={(e) => setEditForm({ ...editForm, cpa_phone: e.target.value })} /></div>
              </div>
            </div>

            {/* Insurance & Financial */}
            <div>
              <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Insurance & Financial</h4>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2"><Label>Insurance Provider</Label><Input value={editForm.insurance_provider} onChange={(e) => setEditForm({ ...editForm, insurance_provider: e.target.value })} /></div>
                <div className="space-y-2"><Label>Insurance Expiration</Label><Input value={editForm.insurance_expiration} onChange={(e) => setEditForm({ ...editForm, insurance_expiration: e.target.value })} type="date" /></div>
                <div className="space-y-2"><Label>Management Fee</Label><Input value={editForm.management_fee} onChange={(e) => setEditForm({ ...editForm, management_fee: e.target.value })} type="number" step="0.01" /></div>
                <div className="space-y-2">
                  <Label>Fiscal Year Start</Label>
                  <Select value={editForm.fiscal_year_start} onValueChange={(v) => setEditForm({ ...editForm, fiscal_year_start: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {["1","2","3","4","5","6","7","8","9","10","11","12"].map(m => (
                        <SelectItem key={m} value={m}>Month {m}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* Accounting */}
            <div>
              <h4 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">Accounting</h4>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Accounting System</Label>
                  <Select
                    value={editForm.accounting_system}
                    onValueChange={(v) => setEditForm({ ...editForm, accounting_system: v })}
                  >
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="buildium">Buildium</SelectItem>
                      <SelectItem value="platform">Platform (Accounting) — coming soon</SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">Determines Chart of Accounts and where ledger entries route.</p>
                </div>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsEditing(false)}>Cancel</Button>
            <Button onClick={handleSave} disabled={saving} className="gap-2">
              {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              Save Changes
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* FAQ Dialog */}
      <Dialog open={faqDialog} onOpenChange={setFaqDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add FAQ</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Question</Label>
              <Input value={faqForm.question} onChange={(e) => setFaqForm({ ...faqForm, question: e.target.value })} placeholder="e.g. When are ARC meetings?" />
            </div>
            <div className="space-y-2">
              <Label>Answer / Details</Label>
              <Textarea value={faqForm.answer} onChange={(e) => setFaqForm({ ...faqForm, answer: e.target.value })} placeholder="Enter the answer..." rows={4} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setFaqDialog(false)}>Cancel</Button>
            <Button onClick={handleAddFaq} disabled={savingFaq || !faqForm.question.trim()} className="gap-2">
              {savingFaq ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
              Add Question
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Custom Field Dialog */}
      <Dialog open={cfDialog} onOpenChange={setCfDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{cfForm.id ? "Edit Custom Field" : "Add Custom Field"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Label</Label>
              <Input
                value={cfForm.field_label}
                onChange={(e) => setCfForm({ ...cfForm, field_label: e.target.value })}
                placeholder="e.g. Pool Code, Gate Hours, Property Manager"
              />
            </div>
            <div className="space-y-2">
              <Label>Value</Label>
              <Textarea
                value={cfForm.field_value}
                onChange={(e) => setCfForm({ ...cfForm, field_value: e.target.value })}
                placeholder="Enter the value..."
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCfDialog(false)}>Cancel</Button>
            <Button onClick={handleSaveCustomField} disabled={savingCf || !cfForm.field_label.trim()} className="gap-2">
              {savingCf ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
              {cfForm.id ? "Save" : "Add Field"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <AlertDialog open={showDeleteAlert} onOpenChange={setShowDeleteAlert}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2 text-destructive">
              <Trash2 className="h-5 w-5" /> Delete Association
            </AlertDialogTitle>
            <AlertDialogDescription className="space-y-3">
              <div className="p-3 bg-destructive/10 border border-destructive/20 rounded-md text-sm flex gap-3">
                <AlertTriangle className="h-5 w-5 shrink-0" />
                <p>You are about to permanently delete <strong>{association.name}</strong>. This cannot be undone.</p>
              </div>
              <p className="text-muted-foreground text-sm">
                All linked data (units, owners, violations, documents, etc.) may also be deleted.
                Consider archiving instead if you want to preserve records.
              </p>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isActionLoading}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={(e) => { e.preventDefault(); handleDelete(); }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
              disabled={isActionLoading}
            >
              {isActionLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
              Delete Association
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
