"use client";

import { useEffect, useMemo } from "react";
import { useAppStore, type FeatureFlags } from "@/app/lib/store";
import { useSettings } from "@/app/lib/settings";
import {
  submitFeedback,
  submitOrganizationRequest,
  submitProjectRequest,
  fetchRows,
} from "@/app/lib/api";
import { z } from "zod";
import { PageShell } from "./ui/page-shell";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { FeatureFlagsTab } from "./workspace/FeatureFlagsTab";
import { WorkspaceDialogs } from "./workspace/WorkspaceDialogs";
import { useWorkspacePageStore } from "./workspace/useWorkspacePageStore";
import {
  Building2,
  Globe,
  MapPin,
  Save,
  Upload,
  Sliders,
  LayoutGrid,
  Rows3,
  FileText,
  AlignJustify,
  BarChart3,
  BookOpen,
  Activity,
  Sparkles,
  MessageSquare,
  FolderPlus,
  ArrowDownUp,
  EyeOff,
} from "lucide-react";
import { toast } from "sonner";

const feedbackSchema = z.object({
  message: z.string().trim().min(1, "Feedback message is required"),
  title: z.string().trim().optional(),
  email: z.string().trim().email("Invalid email address").optional().or(z.literal("")),
  category: z.enum(["issue", "idea"]),
});

const organizationSchema = z.object({
  organization_name: z.string().trim().min(1, "Organization name is required").max(100, "Name too long"),
  organization_type: z.string().optional(),
  plan: z.string().optional(),
  requested_by: z.string().trim().email("Invalid email").optional().or(z.literal("")),
  notes: z.string().max(2000, "Notes too long").optional(),
});

const projectSchema = z.object({
  project_name: z.string().trim().min(1, "Project name is required").max(100, "Name too long")
    .refine((v) => /^[a-z0-9_-]+$/i.test(v), "Only letters, numbers, underscore, and hyphen allowed"),
  organization_name: z.string().trim().optional(),
  region: z.string().optional(),
  requested_by: z.string().trim().email("Invalid email").optional().or(z.literal("")),
});

const FISCAL_MONTHS = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December",
];

type FlagConfig = {
  key: keyof FeatureFlags;
  label: string;
  description: string;
  icon: React.ElementType;
};

const FLAG_CONFIGS: FlagConfig[] = [
  {
    key: "enableModules",
    label: "Modules",
    description: "Client/extension module registry",
    icon: LayoutGrid,
  },
  {
    key: "enableWorkspaceSettings",
    label: "Workspace settings",
    description: "Name, logo, region config",
    icon: Building2,
  },
  {
    key: "enableAuthConfig",
    label: "Auth configuration",
    description: "Visual table-to-auth field mapping",
    icon: Sliders,
  },
  {
    key: "enableClientStatistics",
    label: "Client statistics",
    description: "Per-client query analytics dashboard",
    icon: BarChart3,
  },
  {
    key: "enableSdkDocs",
    label: "SDK docs",
    description: "Inline Athena SDK reference",
    icon: BookOpen,
  },
  {
    key: "enableClusterHealth",
    label: "Cluster health",
    description: "Mirror latency and health checker",
    icon: Activity,
  },
  {
    key: "compactDatagrid",
    label: "Compact datagrid",
    description: "Reduce row height for denser tables",
    icon: Rows3,
  },
  {
    key: "showRowNumbers",
    label: "Row numbers",
    description: "Show row index in datagrid",
    icon: Rows3,
  },
  {
    key: "showColumnIcons",
    label: "Column icons",
    description: "Show type icon next to column name",
    icon: AlignJustify,
  },
  {
    key: "showDocumentIcons",
    label: "Document icons",
    description: "Show file icon for text-looking cells",
    icon: FileText,
  },
  {
    key: "sortColumnsByDdl",
    label: "DDL column order",
    description:
      "Sort columns by their DDL definition order (id, created_at, …)",
    icon: ArrowDownUp,
  },
  {
    key: "hideNullColumns",
    label: "Hide all-null columns",
    description: "Collapse columns where every visible row is NULL",
    icon: EyeOff,
  },
];

export default function WorkspacePage() {
  const { workspace, setWorkspace, flags, setFlag, selectedClient } =
    useAppStore();
  const { baseUrl, apiKey, pgDumpPath, pgRestorePath } = useSettings();

  const requestContext = useMemo(
    () => ({
      baseUrl,
      apiKey,
      pgDumpPath,
      pgRestorePath,
    }),
    [baseUrl, apiKey, pgDumpPath, pgRestorePath],
  );

  const {
    name,
    slug,
    region,
    fiscalMonth,
    logoInitials,
    logoColor,
    deleteOpen,
    deleteConfirm,
    feedbackOpen,
    feedbackCategory,
    feedbackTitle,
    feedbackMessage,
    feedbackEmail,
    feedbackSubmitting,
    orgName,
    orgType,
    orgPlan,
    orgRequestedBy,
    orgNotes,
    orgSubmitting,
    projectOrganization,
    projectName,
    projectRegion,
    projectRequester,
    projectPassword,
    projectEnableDataApi,
    projectEnableAutoRls,
    projectSubmitting,
    setState,
    initializeFromWorkspace,
    setNameAndSlug,
    clearFeedbackForm,
    clearOrganizationForm,
    clearProjectForm,
  } = useWorkspacePageStore();

  useEffect(() => {
    initializeFromWorkspace(workspace);
  }, [
    workspace,
    workspace.name,
    workspace.slug,
    workspace.region,
    workspace.fiscalYearStart,
    workspace.logoInitials,
    workspace.logoColor,
    initializeFromWorkspace,
  ]);

  const hasChanges =
    name !== workspace.name ||
    slug !== workspace.slug ||
    region !== workspace.region ||
    fiscalMonth !== workspace.fiscalYearStart ||
    logoInitials !== workspace.logoInitials ||
    logoColor !== workspace.logoColor;

  const handleSave = () => {
    setWorkspace({
      name,
      slug,
      region,
      fiscalYearStart: fiscalMonth,
      logoInitials,
      logoColor,
    });
    toast.success("Workspace settings saved");
  };

  const handleSubmitFeedback = async () => {
    const parsed = feedbackSchema.safeParse({
      message: feedbackMessage,
      title: feedbackTitle || undefined,
      email: feedbackEmail || undefined,
      category: feedbackCategory,
    });
    if (!parsed.success) {
      toast.error(parsed.error.issues[0]?.message ?? "Invalid feedback");
      return;
    }

    setState({ feedbackSubmitting: true });
    try {
      await submitFeedback(requestContext, {
        category: parsed.data.category,
        title: parsed.data.title,
        message: parsed.data.message,
        email: parsed.data.email || undefined,
        organization_name: workspace.name,
        page: "/workspace",
        metadata: {
          source: "workspace-feedback-modal",
          active_client: selectedClient ?? undefined,
        },
      });
      toast.success("Feedback sent");
      clearFeedbackForm();
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Failed to submit feedback",
      );
    } finally {
      setState({ feedbackSubmitting: false });
    }
  };

  const handleSubmitOrganization = async () => {
    const parsed = organizationSchema.safeParse({
      organization_name: orgName,
      organization_type: orgType,
      plan: orgPlan,
      requested_by: orgRequestedBy || undefined,
      notes: orgNotes || undefined,
    });
    if (!parsed.success) {
      toast.error(parsed.error.issues[0]?.message ?? "Invalid organization data");
      return;
    }

    setState({ orgSubmitting: true });
    try {
      const existing = await fetchRows(
        requestContext,
        "organization_requests",
        ["organization_name"],
        undefined,
        undefined,
        true,
      ).catch(() => []);
      if (existing.some((r) => String(r.organization_name).toLowerCase() === parsed.data.organization_name.toLowerCase())) {
        toast.error(`An organization named '${parsed.data.organization_name}' already exists`);
        setState({ orgSubmitting: false });
        return;
      }

      await submitOrganizationRequest(requestContext, {
        organization_name: parsed.data.organization_name,
        organization_type: parsed.data.organization_type,
        plan: parsed.data.plan,
        requested_by: parsed.data.requested_by || undefined,
        notes: parsed.data.notes || undefined,
        metadata: {
          source: "workspace-organization-form",
        },
      });
      toast.success("Organization request saved");
      setState({ projectOrganization: parsed.data.organization_name });
      clearOrganizationForm();
    } catch (err) {
      toast.error(
        err instanceof Error
          ? err.message
          : "Failed to save organization request",
      );
    } finally {
      setState({ orgSubmitting: false });
    }
  };

  const handleSubmitProject = async () => {
    const parsed = projectSchema.safeParse({
      project_name: projectName,
      organization_name: projectOrganization || undefined,
      region: projectRegion,
      requested_by: projectRequester || undefined,
    });
    if (!parsed.success) {
      toast.error(parsed.error.issues[0]?.message ?? "Invalid project data");
      return;
    }

    setState({ projectSubmitting: true });
    try {
      const existing = await fetchRows(
        requestContext,
        "project_requests",
        ["project_name"],
        undefined,
        undefined,
        true,
      ).catch(() => []);
      if (existing.some((r) => String(r.project_name).toLowerCase() === parsed.data.project_name.toLowerCase())) {
        toast.error(`A project named '${parsed.data.project_name}' already exists`);
        setState({ projectSubmitting: false });
        return;
      }

      await submitProjectRequest(requestContext, {
        organization_name: parsed.data.organization_name,
        project_name: parsed.data.project_name,
        region: parsed.data.region,
        requested_by: parsed.data.requested_by || undefined,
        enable_data_api: projectEnableDataApi,
        enable_automatic_rls: projectEnableAutoRls,
        metadata: {
          source: "workspace-project-form",
          password_provided: Boolean(projectPassword.trim()),
        },
      });
      toast.success("Project request saved");
      clearProjectForm();
    } catch (err) {
      toast.error(
        err instanceof Error ? err.message : "Failed to save project request",
      );
    } finally {
      setState({ projectSubmitting: false });
    }
  };

  return (
    <div className="flex flex-1 flex-col min-h-0 overflow-auto">
      <PageShell>
        <div className="flex items-center justify-between mb-8">
          <h1 className="text-xl font-semibold tracking-tight">Workspace</h1>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setState({ feedbackOpen: true })}
              className="animate-soft-pulse"
            >
              <MessageSquare className="h-3.5 w-3.5" /> Feedback
            </Button>
            {hasChanges && (
              <Button onClick={handleSave} size="sm">
                <Save className="h-3.5 w-3.5" /> Save changes
              </Button>
            )}
          </div>
        </div>

        <Tabs defaultValue="general" className="space-y-0">
          <TabsList className="mb-6 h-9">
            <TabsTrigger value="general">General</TabsTrigger>
            <TabsTrigger value="flags">Feature flags</TabsTrigger>
          </TabsList>

          {/* ── General tab ─────────────────────────────────────────── */}
          <TabsContent value="general" className="space-y-6 mt-0">
            <section className="rounded-xl border border-border bg-card overflow-hidden shadow-sm animate-pop-in">
              <div className="border-b border-border px-6 py-4">
                <div className="flex items-center gap-2">
                  <Sparkles className="h-4 w-4 text-primary" />
                  <h2 className="text-sm font-semibold tracking-tight">
                    Workspace intake
                  </h2>
                </div>
                <p className="text-xs text-muted-foreground/85 mt-1">
                  Submit feedback, organization requests, and project requests
                  directly from the frontend.
                </p>
              </div>
              <div className="grid gap-3 px-6 py-5 md:grid-cols-3">
                <button
                  onClick={() => {
                    setState({ feedbackCategory: "issue", feedbackOpen: true });
                  }}
                  className="group rounded-lg border border-border bg-background/60 p-4 text-left transition-all duration-300 hover:-translate-y-0.5 hover:border-primary/60 hover:shadow-md"
                >
                  <p className="text-sm font-semibold text-foreground">
                    Report an issue
                  </p>
                  <p className="mt-1 text-xs text-muted-foreground/85">
                    Capture blockers and project bugs.
                  </p>
                </button>
                <button
                  onClick={() => {
                    setState({ feedbackCategory: "idea", feedbackOpen: true });
                  }}
                  className="group rounded-lg border border-border bg-background/60 p-4 text-left transition-all duration-300 hover:-translate-y-0.5 hover:border-primary/60 hover:shadow-md"
                >
                  <p className="text-sm font-semibold text-foreground">
                    Share an idea
                  </p>
                  <p className="mt-1 text-xs text-muted-foreground/85">
                    Propose improvements for Athena UX.
                  </p>
                </button>
                <div className="rounded-lg border border-border bg-background/60 p-4">
                  <p className="text-sm font-semibold text-foreground">
                    Active client
                  </p>
                  <p className="mt-1 text-xs text-muted-foreground/85">
                    {selectedClient ?? "No client selected"}
                  </p>
                </div>
              </div>
            </section>

            <section className="rounded-xl border border-border bg-card overflow-hidden shadow-sm animate-pop-in">
              <div className="border-b border-border px-6 py-4">
                <h2 className="text-sm font-semibold tracking-tight">
                  Create a new organization
                </h2>
                <p className="text-xs text-muted-foreground/85 mt-1">
                  Organizations group projects and billing settings.
                </p>
              </div>
              <div className="divide-y divide-border">
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">Name</label>
                  <Input
                    value={orgName}
                    onChange={(e) => setState({ orgName: e.target.value })}
                    placeholder="Organization name"
                    className="max-w-lg"
                  />
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">Type</label>
                  <select
                    value={orgType}
                    onChange={(e) => setState({ orgType: e.target.value })}
                    className="h-9 rounded-md border border-border bg-background px-3 text-sm text-foreground max-w-lg"
                  >
                    <option>Personal</option>
                    <option>Startup</option>
                    <option>Business</option>
                    <option>Enterprise</option>
                  </select>
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">Plan</label>
                  <select
                    value={orgPlan}
                    onChange={(e) => setState({ orgPlan: e.target.value })}
                    className="h-9 rounded-md border border-border bg-background px-3 text-sm text-foreground max-w-lg"
                  >
                    <option>Free - $0/month</option>
                    <option>Pro - $29/month</option>
                    <option>Scale - $149/month</option>
                  </select>
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">
                    Requested by
                  </label>
                  <Input
                    value={orgRequestedBy}
                    onChange={(e) =>
                      setState({ orgRequestedBy: e.target.value })
                    }
                    placeholder="name@company.com"
                    className="max-w-lg"
                  />
                </div>
                <div className="grid grid-cols-[180px_1fr] gap-4 px-6 py-4">
                  <label className="pt-2 text-sm text-foreground/85">
                    Notes
                  </label>
                  <textarea
                    value={orgNotes}
                    onChange={(e) => setState({ orgNotes: e.target.value })}
                    placeholder="What best describes your organization?"
                    className="min-h-20 max-w-lg rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground outline-none transition-colors focus:border-primary"
                  />
                </div>
              </div>
              <div className="flex justify-end gap-2 border-t border-border px-6 py-4">
                <Button variant="outline" onClick={clearOrganizationForm}>
                  Cancel
                </Button>
                <Button
                  onClick={handleSubmitOrganization}
                  disabled={orgSubmitting}
                >
                  <Building2 className="h-3.5 w-3.5" />
                  {orgSubmitting ? "Saving..." : "Create organization"}
                </Button>
              </div>
            </section>

            <section className="rounded-xl border border-border bg-card overflow-hidden shadow-sm animate-pop-in">
              <div className="border-b border-border px-6 py-4">
                <h2 className="text-sm font-semibold tracking-tight">
                  Create a new project
                </h2>
                <p className="text-xs text-muted-foreground/85 mt-1">
                  Spin up a project request with region and security
                  preferences.
                </p>
              </div>
              <div className="divide-y divide-border">
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">
                    Organization
                  </label>
                  <Input
                    value={projectOrganization}
                    onChange={(e) =>
                      setState({ projectOrganization: e.target.value })
                    }
                    placeholder="Organization"
                    className="max-w-lg"
                  />
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">
                    Project name
                  </label>
                  <Input
                    value={projectName}
                    onChange={(e) => setState({ projectName: e.target.value })}
                    placeholder="Project name"
                    className="max-w-lg"
                  />
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">
                    Database password
                  </label>
                  <Input
                    value={projectPassword}
                    onChange={(e) =>
                      setState({ projectPassword: e.target.value })
                    }
                    type="password"
                    placeholder="Type in a strong password"
                    className="max-w-lg"
                  />
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">Region</label>
                  <select
                    value={projectRegion}
                    onChange={(e) =>
                      setState({ projectRegion: e.target.value })
                    }
                    className="h-9 rounded-md border border-border bg-background px-3 text-sm text-foreground max-w-lg"
                  >
                    <option>Europe</option>
                    <option>US East</option>
                    <option>US West</option>
                    <option>Asia Pacific</option>
                  </select>
                </div>
                <div className="grid grid-cols-[180px_1fr] gap-4 px-6 py-4">
                  <label className="pt-1 text-sm text-foreground/85">
                    Security
                  </label>
                  <div className="space-y-3">
                    <label className="flex items-center gap-2 text-sm text-foreground">
                      <input
                        type="checkbox"
                        checked={projectEnableDataApi}
                        onChange={(e) =>
                          setState({ projectEnableDataApi: e.target.checked })
                        }
                      />
                      Enable Data API
                    </label>
                    <label className="flex items-center gap-2 text-sm text-foreground">
                      <input
                        type="checkbox"
                        checked={projectEnableAutoRls}
                        onChange={(e) =>
                          setState({ projectEnableAutoRls: e.target.checked })
                        }
                      />
                      Enable automatic RLS
                    </label>
                  </div>
                </div>
                <div className="grid grid-cols-[180px_1fr] items-center gap-4 px-6 py-4">
                  <label className="text-sm text-foreground/85">
                    Requested by
                  </label>
                  <Input
                    value={projectRequester}
                    onChange={(e) =>
                      setState({ projectRequester: e.target.value })
                    }
                    placeholder="name@company.com"
                    className="max-w-lg"
                  />
                </div>
              </div>
              <div className="flex justify-end gap-2 border-t border-border px-6 py-4">
                <Button variant="outline" onClick={clearProjectForm}>
                  Cancel
                </Button>
                <Button
                  onClick={handleSubmitProject}
                  disabled={projectSubmitting}
                >
                  <FolderPlus className="h-3.5 w-3.5" />
                  {projectSubmitting ? "Saving..." : "Create new project"}
                </Button>
              </div>
            </section>

            {/* Logo */}
            <section className="rounded-lg border border-border bg-card overflow-hidden">
              <div className="border-b border-border px-6 py-4">
                <h2 className="text-sm font-semibold">Logo</h2>
                <p className="text-xs text-muted-foreground mt-0.5">
                  Recommended size is 256×256px.
                </p>
              </div>
              <div className="px-6 py-5">
                <div className="flex items-center gap-6">
                  {/* Logo preview */}
                  <div
                    className="flex h-14 w-14 shrink-0 items-center justify-center rounded-xl text-white font-bold text-lg select-none shadow-sm"
                    style={{ backgroundColor: logoColor }}
                  >
                    {logoInitials.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="space-y-2 flex-1">
                    <div className="flex items-center gap-2">
                      <div className="space-y-1 flex-1 max-w-30">
                        <label className="text-xs text-muted-foreground">
                          Initials
                        </label>
                        <Input
                          value={logoInitials}
                          onChange={(e) =>
                            setState({
                              logoInitials: e.target.value.slice(0, 2),
                            })
                          }
                          className="h-7 text-xs font-mono uppercase"
                          maxLength={2}
                        />
                      </div>
                      <div className="space-y-1">
                        <label className="text-xs text-muted-foreground">
                          Color
                        </label>
                        <div className="flex items-center gap-2">
                          <input
                            type="color"
                            value={logoColor}
                            onChange={(e) =>
                              setState({ logoColor: e.target.value })
                            }
                            className="h-7 w-10 rounded cursor-pointer border border-border"
                          />
                          <span className="text-xs font-mono text-muted-foreground">
                            {logoColor}
                          </span>
                        </div>
                      </div>
                    </div>
                    <Button
                      variant="outline"
                      size="sm"
                      className="h-7 text-xs"
                      disabled
                    >
                      <Upload className="h-3 w-3" /> Upload image
                    </Button>
                  </div>
                </div>
              </div>
            </section>

            {/* Name & URL */}
            <section className="rounded-lg border border-border bg-card overflow-hidden">
              <div className="border-b border-border px-6 py-4">
                <h2 className="text-sm font-semibold">Identity</h2>
              </div>
              <div className="px-6 py-5 space-y-4">
                <div className="grid grid-cols-[160px_1fr] items-center gap-4">
                  <label className="text-sm text-muted-foreground flex items-center gap-2">
                    <Building2 className="h-3.5 w-3.5" /> Name
                  </label>
                  <Input
                    value={name}
                    onChange={(e) => setNameAndSlug(e.target.value)}
                    className="text-sm max-w-xs"
                    placeholder="My Workspace"
                  />
                </div>
                <div className="grid grid-cols-[160px_1fr] items-center gap-4">
                  <label className="text-sm text-muted-foreground flex items-center gap-2">
                    <Globe className="h-3.5 w-3.5" /> URL
                  </label>
                  <div className="flex items-center gap-1 max-w-xs">
                    <span className="text-xs text-muted-foreground bg-muted rounded-l-md border border-r-0 border-border px-2.5 h-9 flex items-center">
                      athena-db.com/
                    </span>
                    <Input
                      value={slug}
                      onChange={(e) => setState({ slug: e.target.value })}
                      className="text-sm rounded-l-none font-mono"
                      placeholder="my-workspace"
                    />
                  </div>
                </div>
              </div>
            </section>

            {/* Time & Region */}
            <section className="rounded-lg border border-border bg-card overflow-hidden">
              <div className="border-b border-border px-6 py-4">
                <h2 className="text-sm font-semibold">Time &amp; region</h2>
              </div>
              <div className="divide-y divide-border">
                <div className="grid grid-cols-[1fr_auto] items-center gap-6 px-6 py-4">
                  <div>
                    <p className="text-sm font-medium">
                      First month of the fiscal year
                    </p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Used when grouping data quarterly, half-yearly, and
                      yearly.
                    </p>
                  </div>
                  <select
                    value={fiscalMonth}
                    onChange={(e) => setState({ fiscalMonth: e.target.value })}
                    className="h-8 rounded-md border border-border bg-background px-2.5 text-sm text-foreground appearance-none pr-6 cursor-pointer"
                  >
                    {FISCAL_MONTHS.map((m) => (
                      <option key={m} value={m}>
                        {m}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="grid grid-cols-[1fr_auto] items-center gap-6 px-6 py-4">
                  <div>
                    <p className="text-sm font-medium flex items-center gap-1.5">
                      <MapPin className="h-3.5 w-3.5 text-muted-foreground" />{" "}
                      Region
                    </p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Set when a workspace is created and cannot be changed.
                    </p>
                  </div>
                  <span className="text-sm text-muted-foreground">
                    {region}
                  </span>
                </div>
              </div>
            </section>

            {/* Danger zone */}
            <section className="rounded-lg border border-destructive/40 bg-card overflow-hidden">
              <div className="border-b border-destructive/30 px-6 py-4">
                <h2 className="text-sm font-semibold text-destructive">
                  Danger zone
                </h2>
              </div>
              <div className="px-6 py-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium">Delete workspace</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      Permanently delete this workspace and all its data. This
                      cannot be undone.
                    </p>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    className="shrink-0 border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
                    onClick={() => setState({ deleteOpen: true })}
                  >
                    Delete…
                  </Button>
                </div>
              </div>
            </section>

            {hasChanges && (
              <div className="flex justify-end">
                <Button onClick={handleSave}>
                  <Save className="h-3.5 w-3.5" /> Save changes
                </Button>
              </div>
            )}
          </TabsContent>

          {/* ── Feature flags tab ──────────────────────────────────── */}
          <TabsContent value="flags" className="mt-0">
            <FeatureFlagsTab
              configs={FLAG_CONFIGS}
              flags={flags}
              setFlag={setFlag}
            />
          </TabsContent>
        </Tabs>
      </PageShell>

      <WorkspaceDialogs
        deleteOpen={deleteOpen}
        setDeleteOpen={(value) => setState({ deleteOpen: value })}
        deleteConfirm={deleteConfirm}
        setDeleteConfirm={(value) => setState({ deleteConfirm: value })}
        workspaceName={workspace.name}
        onDeleteConfirm={() => {
          toast.error("Workspace deletion is disabled in demo mode");
          setState({ deleteOpen: false, deleteConfirm: "" });
        }}
        feedbackOpen={feedbackOpen}
        setFeedbackOpen={(value) => setState({ feedbackOpen: value })}
        feedbackCategory={feedbackCategory}
        setFeedbackCategory={(value) => setState({ feedbackCategory: value })}
        feedbackTitle={feedbackTitle}
        setFeedbackTitle={(value) => setState({ feedbackTitle: value })}
        feedbackEmail={feedbackEmail}
        setFeedbackEmail={(value) => setState({ feedbackEmail: value })}
        feedbackMessage={feedbackMessage}
        setFeedbackMessage={(value) => setState({ feedbackMessage: value })}
        feedbackSubmitting={feedbackSubmitting}
        onSubmitFeedback={handleSubmitFeedback}
      />
    </div>
  );
}
