"use client";
import Link from "next/link";
import { useState, useEffect } from "react";
import { useMasterDataStore } from "../../store/masterDataStore";
import { useUserStore } from "../../store/userStore";
import { DEFAULT_PREFERENCES } from "@/app/lib/defaultPreferences";
import { Suspense } from "react";

import {
  User,
  Mail,
  Building2,
  Database,
  List,
  Pill,
  Heart,
  Clock,
  FileText,
  Stethoscope,
  Microscope,
  Printer,
  Info,
  MessageCircle,
  LogOut,
  Trash2,
  Pencil,
  ChevronRight,
  Plus,
  History as HistoryIcon,
  Settings as SettingsIcon,
  Lock,
  Menu,
  FileCheck2,
} from "lucide-react";
import EditProfileModal from "@/components/modals/ui/EditProfileModal";
import PaperSizeWizardModal from "@/components/modals/ui/PaperSizeWizardModal";
import SavedPrintInfoModal from "@/components/modals/ui/SavedPrintInfoModal";
import SelectTemplateModal from "@/components/modals/ui/SelectTemplateModal";
import { UserPreferences } from "@/app/types/preferences";
import ConfirmDeleteModal from "@/components/modals/ui/ConfirmDeleteModal";
import { useTemplateStore } from "@/app/store/templateStore";
import Sidebar from "@/components/modals/ui/Sidebar";
import SavedSymptomsPage from "./symptoms/page";
import SidePanel from "@/app/landing/components/SidePanel";
import CategoryOrderPage from "./category-order/page";
import SavedMedicinesPage from "./medicines/page";
import DoseFrequenciesPage from "./dose-frequencies/page";
import InstructionsPage from "./instructions/page";
import SavedDiagnosesPage from "./diagnoses/page";
import SavedInvestigationsPage from "./investigations/page";
import FeedbackPage from "./feedback/page";
import MyPracticesPage from "./my-practices/page";
import HospitalDetailsPage from "./hospital-details/page";
import AddHospitalPage from "./add-hospital/page";
import { useSearchParams } from "next/navigation";
import SubscriptionPlansPage from "./subscription/page";
import { useRouter } from "next/navigation";

// ── Icons ──────────────────────────────────────────────────────────────────────
const Icon = {
  User: () => <User size={20} />,
  Mail: () => <Mail size={20} />,
  Hospital: () => <Building2 size={20} />,
  Database: () => <Database size={20} />,
  List: () => <List size={20} />,
  Pill: () => <Pill size={20} />,
  Heart: () => <Heart size={20} />,
  Clock: () => <Clock size={20} />,
  FileText: () => <FileText size={20} />,
  Stethoscope: () => <Stethoscope size={20} />,
  Microscope: () => <Microscope size={20} />,
  Printer: () => <Printer size={20} />,
  Info: () => <Info size={20} />,
  MessageCircle: () => <MessageCircle size={20} />,
  LogOut: () => <LogOut size={20} />,
  Trash: () => <Trash2 size={20} />,
  Edit: () => <Pencil size={16} />,
  ChevronRight: () => <ChevronRight size={18} />,
  Plus: () => <Plus size={20} />,
  History: () => <HistoryIcon size={20} />,
  Settings: () => <SettingsIcon size={20} />,
  Lock: () => <Lock size={13} />,
  Menu: () => <Menu size={24} />,
  FileCheck: () => <FileCheck2 size={20} />,
};

const ABOUT_ITEMS = [
  {
    icon: <Icon.MessageCircle />,
    title: "Provide feedback & suggestions",
    sub: "Share your thoughts with us",
    key: "feedback",
  },
];

// ── Reusable UI pieces ─────────────────────────────────────────────────────────
function IconBox({
  children,
  colorClass = "text-[#d4537e]",
  bgClass = "bg-[#fceef3]",
}: {
  children: React.ReactNode;
  colorClass?: string;
  bgClass?: string;
}) {
  return (
    <div
      className={`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${bgClass} ${colorClass}`}
    >
      {children}
    </div>
  );
}

function Card({ children }: { children: React.ReactNode }) {
  return (
    <div className="bg-white border border-[#e5e7eb] rounded-2xl p-7 mb-6">
      {children}
    </div>
  );
}

function CardHeader({
  icon,
  label,
  onEdit,
}: {
  icon: React.ReactNode;
  label: string;
  onEdit?: boolean | (() => void);
}) {
  return (
    <div className="flex items-center justify-between mb-5">
      <div className="flex items-center gap-2">
        <span className="text-[#d4537e]">{icon}</span>
        <span className="text-xs font-bold uppercase tracking-widest text-[#4b5563]">
          {label}
        </span>
      </div>
      {onEdit && typeof onEdit === "function" && (
        <button
          onClick={onEdit}
          className="text-[11px] font-bold text-[#d4537e] bg-[#fceef3] border-none rounded-lg px-3 py-1.5 cursor-pointer hover:bg-[#f8d9e4] transition-colors"
        >
          Edit
        </button>
      )}
    </div>
  );
}

function RowItem({
  icon,
  label,
  value,
  iconBgClass,
  iconColorClass,
  right,
  danger = false,
}: {
  icon: React.ReactNode;
  label?: string;
  value?: string;
  iconBgClass?: string;
  iconColorClass?: string;
  right?: React.ReactNode;
  danger?: boolean;
}) {
  return (
    <div className="flex items-center gap-4 py-4 px-3 -mx-3 border-b border-[#f3f4f6] last:border-b-0 rounded-lg cursor-pointer hover:bg-[#f7f7f8]">
      <IconBox
        bgClass={iconBgClass ?? "bg-[#f7f7f8]"}
        colorClass={iconColorClass ?? "text-[#d4537e]"}
      >
        {icon}
      </IconBox>
      <div className="flex-1 min-w-0">
        {label && (
          <p className="text-xs uppercase tracking-wider text-[#9ca3af] mb-1">
            {label}
          </p>
        )}
        {value && (
          <p
            className={`text-base font-medium ${danger ? "text-[#ef4444]" : "text-[#111111]"}`}
          >
            {value}
          </p>
        )}
      </div>
      {right ?? (
        <span className="text-[#9ca3af]">
          <Icon.ChevronRight />
        </span>
      )}
    </div>
  );
}

function ListRow({
  icon,
  title,
  sub,
  right,
  danger = false,
  iconBgClass,
  iconColorClass,
  href,
  onClick,
}: {
  icon: React.ReactNode;
  title: string;
  sub?: string;
  right?: React.ReactNode;
  danger?: boolean;
  iconBgClass?: string;
  iconColorClass?: string;
  href?: string;
  onClick?: () => void;
}) {
  const content = (
    <>
      <IconBox
        bgClass={iconBgClass ?? "bg-[#fceef3]"}
        colorClass={iconColorClass ?? "text-[#d4537e]"}
      >
        {icon}
      </IconBox>
      <div className="flex-1 min-w-0">
        <p
          className={`text-[15px] font-semibold ${danger ? "text-[#ef4444]" : "text-[#111111]"}`}
        >
          {title}
        </p>
        {sub && <p className="text-xs text-[#9ca3af] mt-0.5">{sub}</p>}
      </div>
      {right ?? (
        <span className="text-[#9ca3af]">
          <Icon.ChevronRight />
        </span>
      )}
    </>
  );
  const cls =
    "flex items-center gap-4 py-3 px-3 -mx-3 border-b border-[#f3f4f6] last:border-b-0 rounded-lg cursor-pointer hover:bg-[#f7f7f8] no-underline";
  return href ? (
    <Link href={href} className={cls}>
      {content}
    </Link>
  ) : (
    <div className={cls} onClick={onClick}>
      {content}
    </div>
  );
}

// ── Prescription settings field display ──────────────────────────────────────
function PrefField({
  label,
  value,
  accent = false,
}: {
  label: string;
  value: string;
  accent?: boolean;
}) {
  return (
    <div className="py-2">
      <p className="text-[10px] uppercase tracking-wider text-[#9ca3af] font-bold mb-0.5">
        {label}
      </p>
      <p
        className={`text-sm font-semibold ${accent ? "text-[#16a34a]" : "text-[#111111]"}`}
      >
        {value}
      </p>
    </div>
  );
}

// ── Main Page ──────────────────────────────────────────────────────────────────
export default function SettingsPage() {
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [user, setUser] = useState<any>(null);
  const router = useRouter();

  // Modal states
  const [isEditProfileOpen, setIsEditProfileOpen] = useState(false);
  const [isWizardOpen, setIsWizardOpen] = useState(false);
  const [isPrintInfoOpen, setIsPrintInfoOpen] = useState(false);
  const [isTemplateOpen, setIsTemplateOpen] = useState(false);
  const [logoutOpen, setLogoutOpen] = useState(false);
  const [deleteOpen, setDeleteOpen] = useState(false);

  // Local preferences state (keeps UI in sync without re-fetching)
  const [localPrefs, setLocalPrefs] = useState<Partial<UserPreferences>>({});
  const [template, setTemplate] = useState("regular");

  const { masterData, fetchMasterData } = useMasterDataStore();
  const { updateProfile, loadUserFromStorage } = useUserStore();
  const { selectedTemplateName, selectedTemplateId, loadSelectedTemplate } =
    useTemplateStore();

  type PanelEntry = { key: string; props?: Record<string, any> };

  const [panelStack, setPanelStack] = useState<PanelEntry[]>([]);

  const openPanel = (key: string, props?: Record<string, any>) => {
    setPanelStack((prev) => [...prev, { key, props }]);
  };

  const closeAllPanels = () => setPanelStack([]);

  const goBackPanel = () => setPanelStack((prev) => prev.slice(0, -1));

  const activeEntry = panelStack[panelStack.length - 1] ?? null;
  useEffect(() => {
    const storedUser = localStorage.getItem("user");
    if (storedUser) setUser(JSON.parse(storedUser));
    loadUserFromStorage();
    fetchMasterData();
    loadSelectedTemplate();
  }, []);

  const { logout, deleteAccount } = useUserStore();

  const handleLogout = async () => {
    await logout();
  };
  const handleDeleteAccount = async () => {
    const success = await deleteAccount();

    if (success) {
      setDeleteOpen(false);
    }
  };
  const handleTemplateSelect = (id: string, name: string) => {
    setIsTemplateOpen(false);
  };

  useEffect(() => {
    const storedUser = localStorage.getItem("user");
    if (storedUser) setUser(JSON.parse(storedUser));
    loadUserFromStorage();
    fetchMasterData();
  }, []);

  useEffect(() => {
    if (masterData?.user_preferences) {
      setLocalPrefs(masterData.user_preferences);
    }
  }, [masterData?.user_preferences]);

  const mergePrefs = (updated: Partial<UserPreferences>) => {
    setLocalPrefs((prev) => ({ ...prev, ...updated }));
  };

  const prefs: Partial<UserPreferences> = {
    ...DEFAULT_PREFERENCES,
    ...localPrefs,
  };
  const medicalData = [
    {
      icon: <Icon.List />,
      title: "Category order",
      sub: "Drag to reorder medicine categories",
      href: "/dashboard/settings/category-order",
      key: "category-order",
    },
    {
      icon: <Icon.Pill />,
      title: "Saved medicines",
      sub: `${masterData?.medicines?.length || 0} saved medicines`,
      href: "/dashboard/settings/medicines",
      key: "medicines",
    },
    {
      icon: <Icon.Heart />,
      title: "Saved symptoms",
      sub: `${masterData?.symptoms?.length || 0} symptoms`,
      href: "/dashboard/settings/symptoms",
      key: "symptoms",
    },
    {
      icon: <Icon.Clock />,
      title: "Saved dose frequencies",
      sub: `${masterData?.dose_frequencies?.length || 0} frequencies`,
      href: "/dashboard/settings/dose-frequencies",
      key: "dose-frequencies",
    },
    {
      icon: <Icon.FileText />,
      title: "Instructions / advices",
      sub: `${masterData?.instructions?.length || 0} instructions/advices`,
      href: "/dashboard/settings/instructions",
      key: "instructions",
    },
    {
      icon: <Icon.Stethoscope />,
      title: "Saved diagnoses",
      sub: `${masterData?.diagnoses?.length || 0} diagnoses`,
      href: "/dashboard/settings/diagnoses",
      key: "diagnoses",
    },
    {
      icon: <Icon.Microscope />,
      title: "Saved investigations",
      sub: `${masterData?.investigations?.length || 0} investigations`,
      href: "/dashboard/settings/investigations",
      key: "investigations",
    },
  ];
  const searchParams = useSearchParams();

  useEffect(() => {
    const panel = searchParams.get("panel");
    if (panel === "medicines") openPanel("medicines");
    if (panel === "diagnoses") openPanel("diagnoses");
    if (panel === "settings") openPanel("settings");
    if (panel === "practices") openPanel("my-practices");
  }, [searchParams]);

  const panelTitles: Record<string, string> = {
    "category-order": "Category order",
    medicines: "Saved medicines",
    symptoms: "Saved symptoms",
    "dose-frequencies": "Saved dose frequencies",
    instructions: "Instructions / advices",
    diagnoses: "Saved diagnoses",
    investigations: "Saved investigations",
    feedback: "Provide feedback & suggestions",
    "my-practices": "My Practices",
    "hospital-details": "Hospital Details",
    "add-hospital": "Add Hospital",
    // "subscription": "Choose your plan",
  };

  const renderPanelContent = () => {
    if (!activeEntry) return null;

    switch (activeEntry.key) {
      case "category-order":
        return (
          <CategoryOrderPage
            onBack={closeAllPanels}
            onClose={closeAllPanels}
          />
        );

      case "medicines":
        return (
          <SavedMedicinesPage
            onClose={closeAllPanels}
          />
        );

      case "symptoms":
        return (
          <SavedSymptomsPage
            onClose={closeAllPanels}
          />
        );

      case "dose-frequencies":
        return (
          <DoseFrequenciesPage
            onClose={closeAllPanels}
          />
        );

      case "instructions":
        return (
          <InstructionsPage
            onClose={closeAllPanels}
          />
        );

      case "diagnoses":
        return (
          <SavedDiagnosesPage
            onClose={closeAllPanels}
          />
        );

      case "investigations":
        return (
          <SavedInvestigationsPage
            onClose={closeAllPanels}
          />
        );

      case "feedback":
        return (
          <FeedbackPage
            onClose={closeAllPanels}
          />
        );
      case "my-practices":
        return (
          <MyPracticesPage
            onSelectHospital={(hospitalId: string) =>
              openPanel("hospital-details", { hospitalId })
            }
            onAddHospital={() => openPanel("add-hospital")}
          />
        );
      case "hospital-details":
        return (
          <HospitalDetailsPage
            hospitalId={activeEntry.props?.hospitalId}
            onClose={goBackPanel}
          />
        );
      case "add-hospital":
        return <AddHospitalPage onDone={goBackPanel} />;
      // case "subscription":
      //   return <SubscriptionPlansPage  />;
      default:
        return null;
    }
  };

  return (
    <div className="flex min-h-screen bg-[#f7f7f8] font-sans">
      {/* Desktop sidebar */}
      <aside className="hidden md:block w-64 flex-shrink-0 bg-white border-r border-[#e5e7eb] sticky top-0 h-screen">
        <Sidebar user={user} />
      </aside>

      {/* Mobile sidebar overlay */}
      {sidebarOpen && (
        <div className="fixed inset-0 z-50">
          <div
            className="absolute inset-0 bg-black/30"
            onClick={() => setSidebarOpen(false)}
          />
          <div className="absolute left-0 top-0 bottom-0 w-64 bg-white shadow-[4px_0_20px_rgba(0,0,0,0.08)]">
            <Sidebar user={user} onClose={() => setSidebarOpen(false)} />
          </div>
        </div>
      )}

      <div className="flex-1 flex flex-col min-w-0">
        {/* Topbar */}
        <header className="h-[72px] flex items-center justify-between px-7 bg-white border-b border-[#e5e7eb] sticky top-0 z-20">
          <div className="flex items-center gap-4">
            {/* Mobile Menu Trigger */}
            <button
              className="md:hidden text-[#374151] bg-transparent border-none cursor-pointer p-0"
              onClick={() => setSidebarOpen(true)}
            >
              <Icon.Menu />
            </button>
            <div>
              <h1 className="text-lg font-bold text-gray-900">Settings</h1>
              <p className="text-xs text-gray-400 font-medium">
                Manage your account & preferences
              </p>
            </div>
          </div>
        </header>

        <main className="flex-1 p-7">
          <div className="mx-auto">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* ── LEFT ── */}
              <div>
                {/* My Profile */}
                <Card>
                  <CardHeader
                    icon={<Icon.User />}
                    label="My profile"
                    onEdit={() => setIsEditProfileOpen(true)}
                  />
                  <div className="flex items-center gap-4 pb-6 mb-2 border-b border-[#f3f4f6]">
                    <div className="w-16 h-16 rounded-full bg-[#d4537e] text-white flex items-center justify-center text-2xl font-semibold flex-shrink-0">
                      {user?.fullname?.charAt(0)?.toUpperCase() || "U"}
                    </div>
                    <div>
                      <p className="text-xl font-semibold text-[#111111]">
                        {user?.fullname || "User"}
                      </p>
                      <span className="text-xs font-semibold bg-[#fceef3] text-[#993556] px-3 py-1 rounded-full">
                        {user?.subscriptionPlan || "Free"} Plan
                      </span>
                      <p className="text-sm text-[#d4537e] mt-1.5 cursor-pointer"
                        onClick={() => router.push("/dashboard/settings/subscription")}
                      >
                        Upgrade to Pro →
                      </p>
                    </div>
                  </div>

                  <RowItem
                    icon={<Icon.Mail />}
                    label="Email address"
                    value={user?.email || ""}
                    iconBgClass="bg-[#f7f7f8]"
                  />
                  {/* My hospitals PRO */}
                  <ListRow
                    icon={<Icon.Hospital />}
                    title="My Practices"
                    sub="Manage your hospitals and clinics"
                    onClick={() => openPanel("my-practices")}
                    iconBgClass="bg-[#f7f7f8]"
                    iconColorClass="text-[#4b5563]"
                  />
                </Card>

                {/* ── Page & Prescription Settings — REDESIGNED ── */}
                <Card>
                  {/* Card header — no edit button here, each section has its own */}
                  <div className="flex items-center gap-2.5 mb-5">
                    <span className="text-[#d4537e]">
                      <Icon.Printer />
                    </span>
                    <span className="text-sm font-semibold uppercase tracking-wider text-[#4b5563]">
                      Page & prescription settings
                    </span>
                  </div>

                  {/* ── Section 1: Paper size & spacing ── */}
                  <div className="border border-[#f3f4f6] rounded-xl p-4 mb-4">
                    <div className="flex items-center justify-between mb-3">
                      <p className="text-xs font-semibold uppercase tracking-wider text-[#9ca3af]">
                        Paper size & margins
                      </p>
                      <button
                        onClick={() => setIsWizardOpen(true)}
                        className="w-8 h-8 rounded-full bg-[#fceef3] text-[#d4537e] flex items-center justify-center hover:bg-[#f8d9e4] transition-colors cursor-pointer border-none"
                      >
                        <Pencil size={14} />
                      </button>
                    </div>
                    <div className="grid grid-cols-2 gap-x-4">
                      <PrefField
                        label="Paper size"
                        value={prefs.page_size || "-"}
                      />
                      <PrefField
                        label="Header spacing"
                        value={`${prefs.page_header_size_mm ?? 0} mm`}
                      />
                      <PrefField
                        label="Footer spacing"
                        value={`${prefs.page_footer_size_mm ?? 0} mm`}
                      />
                      <PrefField
                        label="Left/Start spacing"
                        value={`${prefs.page_left_side_spacing ?? 0} mm`}
                      />
                      <PrefField
                        label="Right/End spacing"
                        value={`${prefs.page_right_side_spacing ?? 0} mm`}
                      />
                    </div>
                  </div>

                  {/* ── Section 2: Language, font, toggles ── */}
                  <div className="border border-[#f3f4f6] rounded-xl p-4 mb-4">
                    <div className="flex items-center justify-between mb-3">
                      <p className="text-xs font-semibold uppercase tracking-wider text-[#9ca3af]">
                        Print information
                      </p>
                      <button
                        onClick={() => setIsPrintInfoOpen(true)}
                        className="w-8 h-8 rounded-full bg-[#fceef3] text-[#d4537e] flex items-center justify-center hover:bg-[#f8d9e4] transition-colors cursor-pointer border-none"
                      >
                        <Pencil size={14} />
                      </button>
                    </div>
                    <div className="grid grid-cols-2 gap-x-4">
                      <PrefField
                        label="Language"
                        value={prefs.prescription_language || "-"}
                      />
                      <PrefField
                        label="Font size"
                        value={`${prefs.font_size ?? 14}`}
                      />
                      <PrefField
                        label="Signature Box"
                        value={
                          prefs.is_signature_required ? "Enable" : "Disable"
                        }
                        accent={prefs.is_signature_required}
                      />
                      <PrefField
                        label="Doctor Info"
                        value={
                          prefs.is_doctor_info_required ? "Enable" : "Disable"
                        }
                        accent={prefs.is_doctor_info_required}
                      />
                    </div>
                  </div>

                  {/* ── Print template row ── */}
                  <button
                    onClick={() => setIsTemplateOpen(true)}
                    className="w-full flex items-center gap-4 cursor-pointer hover:bg-[#f7f7f8] rounded-xl p-2 -mx-2 transition-colors bg-transparent border-none text-left"
                  >
                    <div className="w-12 h-14 rounded-lg bg-[#f7f7f8] border border-[#e5e7eb] text-[#4b5563] flex items-center justify-center">
                      <Icon.FileText />
                    </div>
                    <div className="flex-1">
                      <p className="text-xs text-[#9ca3af]">Print template</p>
                      <p className="text-base font-medium text-[#111111] capitalize">
                        {template}
                      </p>
                      <p className="text-sm text-[#d4537e]">Tap to change</p>
                    </div>
                    <span className="text-[#9ca3af]">
                      <Icon.ChevronRight />
                    </span>
                  </button>
                </Card>
              </div>

              {/* ── RIGHT ── */}
              <div>
                <Card>
                  <CardHeader icon={<Icon.Database />} label="Medical data" />
                  {medicalData.map(({ icon, title, sub, key }) => (
                    <ListRow
                      key={title}
                      icon={icon}
                      title={title}
                      sub={sub}
                      onClick={() => openPanel(key)}
                    />
                  ))}
                </Card>

                <Card>
                  <CardHeader icon={<Icon.Info />} label="About" />
                  {ABOUT_ITEMS.map(({ icon, title, sub, key }) => (
                    <ListRow
                      key={title}
                      icon={icon}
                      title={title}
                      sub={sub}
                      onClick={() => openPanel(key)}
                      iconBgClass="bg-[#f7f7f8]"
                      iconColorClass="text-[#4b5563]"
                    />
                  ))}
                </Card>

                <Card>
                  <CardHeader icon={<Icon.User />} label="Account" />
                  <ListRow
                    icon={<Icon.LogOut />}
                    title="Log out"
                    sub="You will be signed out of your account"
                    onClick={() => setLogoutOpen(true)}
                  />
                  <ListRow
                    icon={<Icon.Trash />}
                    title="Delete account"
                    sub="Permanently removes all your data"
                    danger
                    onClick={() => setDeleteOpen(true)}
                  />
                </Card>

                <SidePanel
                  isOpen={panelStack.length > 0}
                  onClose={closeAllPanels}
                  onBack={panelStack.length > 1 ? goBackPanel : undefined}
                  title={activeEntry ? panelTitles[activeEntry.key] : ""}
                >
                  {renderPanelContent()}
                </SidePanel>
              </div>
            </div>
          </div>
        </main>
      </div>

      {/* ── Modals ── */}

      {/* Edit Profile */}
      <EditProfileModal
        open={isEditProfileOpen}
        onClose={() => setIsEditProfileOpen(false)}
        initialData={{
          fullname: user?.fullname || "",
          email: user?.email || "",
          phone: user?.phone || "",
          title: user?.title || "",
          degree: user?.degree || "",
          specialisation: user?.specialisation || "",
        }}
        onSave={async (data) => {
          const success = await updateProfile({
            fullname: data.fullname,
            title: data.title,
            degree: data.degree,
            specialisation: data.specialisation,
            phoneNumber: data.phone,
            email: data.email,
          });
          if (success) {
            const updatedUser = JSON.parse(
              localStorage.getItem("user") || "{}",
            );
            setUser(updatedUser);
            setIsEditProfileOpen(false);
          }
        }}
      />

      {/* Paper Size Wizard → on save, open Print Info modal */}
      <PaperSizeWizardModal
        open={isWizardOpen}
        onClose={() => setIsWizardOpen(false)}
        initial={prefs}
        onSaved={(updated) => {
          mergePrefs(updated);
          setIsWizardOpen(false);
          setIsPrintInfoOpen(false); // chain: wizard done → open print info
        }}
      />

      {/* Saved Print Information */}
      <SavedPrintInfoModal
        open={isPrintInfoOpen}
        onClose={() => setIsPrintInfoOpen(false)}
        initial={prefs}
        onSaved={(updated) => {
          mergePrefs(updated);
          setIsPrintInfoOpen(false);
        }}
      />

      {/* Select Template */}
      <SelectTemplateModal
        open={isTemplateOpen}
        onClose={() => setIsTemplateOpen(false)}
        currentTemplateId={selectedTemplateId}
        onSelect={handleTemplateSelect}
      />
      <ConfirmDeleteModal
        open={logoutOpen}
        title="Log out?"
        description="Are you sure you want to log out?"
        onCancel={() => setLogoutOpen(false)}
        onConfirm={handleLogout}
      />

      <ConfirmDeleteModal
        open={deleteOpen}
        title="Delete Account?"
        description="This action cannot be undone."
        onCancel={() => setDeleteOpen(false)}
        onConfirm={handleDeleteAccount}
      />
    </div>
  );
}