import { useState } from "react";
import {
  Box,
  IconButton,
  Divider,
  Slider,
  Typography,
  Tooltip,
  Button,
  Paper,
  Popover,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Chip,
  Switch,
  FormControlLabel,
  useMediaQuery,
  useTheme,
  Menu,
  MenuItem,
  Collapse,
  Badge,
  Avatar,
  Stack,
  alpha,
  CircularProgress,
} from "@mui/material";
import {
  TextFields as TextIcon,
  Image as ImageIcon,
  Rectangle as ShapeIcon,
  TableChart as TableIcon,
  HorizontalRule as LineIcon,
  GridOn as GridIcon,
  GridOff as GridOffIcon,
  ZoomIn as ZoomInIcon,
  ZoomOut as ZoomOutIcon,
  Undo as UndoIcon,
  Redo as RedoIcon,
  Save as SaveIcon,
  Visibility as PreviewIcon,
  Delete as DeleteIcon,
  ContentCopy as CopyIcon,
  Lock as LockIcon,
  LockOpen as UnlockIcon,
  Add as AddIcon,
  ZoomOutMap as FitIcon,
  Keyboard as ShortcutsIcon,
  NearMe as SnapIcon,
  Apps as GridSnapIcon,
  CropSquare as ObjectSnapIcon,
  BorderOuter as BorderSnapIcon,
  CenterFocusStrong as CenterSnapIcon,
  LinearScale as TangentSnapIcon,
  ChevronLeft as PrevPageIcon,
  ChevronRight as NextPageIcon,
  Description as PageIcon,
  ExpandMore as ExpandMoreIcon,
  ExpandLess as ExpandLessIcon,
  Search as SearchIcon,
  CloudDone as SavedIcon,
  CloudOff as UnsavedIcon,
  ArrowDropDown as DropdownIcon,
  History as HistoryIcon,
  AutoMode as AutoSaveIcon,
} from "@mui/icons-material";
import type { ElementType } from "../../types/report";

// Snap options type
export interface SnapOptions {
  grid: boolean;
  objects: boolean;
  borders: boolean;
  center: boolean;
  tangent: boolean;
}

interface EditorToolbarProps {
  onAddElement: (type: ElementType) => void;
  onDeleteElement: () => void;
  onCopyElement: () => void;
  onToggleLock: () => void;
  zoom: number;
  onZoomChange: (zoom: number) => void;
  showGrid: boolean;
  onToggleGrid: () => void;
  snapOptions: SnapOptions;
  onSnapOptionsChange: (options: SnapOptions) => void;
  canUndo: boolean;
  canRedo: boolean;
  onUndo: () => void;
  onRedo: () => void;
  onSave: () => void;
  onPreview: () => void;
  hasSelection: boolean;
  isLocked: boolean;
  isSaving: boolean;
  // Page navigation props
  currentPageIndex: number;
  totalPages: number;
  currentPageName: string;
  onPrevPage: () => void;
  onNextPage: () => void;
  // Optional: save status
  hasUnsavedChanges?: boolean;
  lastSavedAt?: Date | null;
  // Optional: command palette
  onOpenCommandPalette?: () => void;
  // Optional: history panel
  onOpenHistory?: () => void;
  // Auto-save feature
  autoSaveEnabled?: boolean;
  onAutoSaveToggle?: (enabled: boolean) => void;
}

const ZOOM_PRESETS = [
  { value: 0.25, label: "25%" },
  { value: 0.5, label: "50%" },
  { value: 0.75, label: "75%" },
  { value: 1, label: "100%" },
  { value: 1.25, label: "125%" },
  { value: 1.5, label: "150%" },
  { value: 2, label: "200%" },
  { value: 3, label: "300%" },
];

const ELEMENT_TYPES = [
  {
    type: "text" as ElementType,
    icon: TextIcon,
    label: "Testo",
    shortcut: "T",
    color: "#2196f3",
    description: "Aggiungi un campo di testo",
  },
  {
    type: "image" as ElementType,
    icon: ImageIcon,
    label: "Immagine",
    shortcut: "I",
    color: "#9c27b0",
    description: "Inserisci un'immagine",
  },
  {
    type: "shape" as ElementType,
    icon: ShapeIcon,
    label: "Forma",
    shortcut: "R",
    color: "#ff9800",
    description: "Disegna una forma geometrica",
  },
  {
    type: "table" as ElementType,
    icon: TableIcon,
    label: "Tabella",
    shortcut: "B",
    color: "#4caf50",
    description: "Inserisci una tabella dati",
  },
  {
    type: "line" as ElementType,
    icon: LineIcon,
    label: "Linea",
    shortcut: "L",
    color: "#607d8b",
    description: "Traccia una linea",
  },
];

// Snap option configuration
const SNAP_OPTIONS_CONFIG = [
  {
    key: "grid" as keyof SnapOptions,
    icon: GridSnapIcon,
    label: "Griglia",
    description: "Allinea alla griglia",
  },
  {
    key: "objects" as keyof SnapOptions,
    icon: ObjectSnapIcon,
    label: "Oggetti",
    description: "Allinea agli altri oggetti",
  },
  {
    key: "borders" as keyof SnapOptions,
    icon: BorderSnapIcon,
    label: "Margini",
    description: "Allinea ai margini pagina",
  },
  {
    key: "center" as keyof SnapOptions,
    icon: CenterSnapIcon,
    label: "Centro",
    description: "Allinea al centro",
  },
  {
    key: "tangent" as keyof SnapOptions,
    icon: TangentSnapIcon,
    label: "Bordi",
    description: "Allinea ai bordi adiacenti",
  },
];

// Format time ago
function formatTimeAgo(date: Date | null | undefined): string {
  if (!date) return "";
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return "Ora";
  if (minutes < 60) return `${minutes}m fa`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h fa`;
  return date.toLocaleDateString("it-IT", { day: "2-digit", month: "short" });
}

// ToolbarSection component for consistent styling
function ToolbarSection({
  children,
  label,
  compact = false,
}: {
  children: React.ReactNode;
  label?: string;
  compact?: boolean;
}) {
  return (
    <Box
      sx={{
        display: "flex",
        alignItems: "center",
        gap: compact ? 0.25 : 0.5,
        position: "relative",
      }}
    >
      {label && (
        <Typography
          variant="caption"
          sx={{
            position: "absolute",
            top: -14,
            left: 0,
            fontSize: "0.6rem",
            color: "text.disabled",
            textTransform: "uppercase",
            letterSpacing: "0.5px",
            whiteSpace: "nowrap",
          }}
        >
          {label}
        </Typography>
      )}
      {children}
    </Box>
  );
}

// StyledIconButton with better feedback
function StyledIconButton({
  children,
  tooltip,
  active,
  disabled,
  onClick,
  color,
  size = "small",
  badge,
  ...props
}: {
  children: React.ReactNode;
  tooltip: string;
  active?: boolean;
  disabled?: boolean;
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
  color?: string;
  size?: "small" | "medium";
  badge?: number;
}) {
  const button = (
    <IconButton
      size={size}
      disabled={disabled}
      onClick={onClick}
      sx={{
        borderRadius: 1.5,
        transition: "all 0.15s ease",
        bgcolor: active ? alpha(color || "#1976d2", 0.15) : "transparent",
        color: active ? color || "primary.main" : "action.active",
        "&:hover": {
          bgcolor: active ? alpha(color || "#1976d2", 0.25) : "action.hover",
          transform: "scale(1.05)",
        },
        "&:active": {
          transform: "scale(0.95)",
        },
        "&.Mui-disabled": {
          opacity: 0.4,
        },
      }}
      {...props}
    >
      {children}
    </IconButton>
  );

  const wrappedButton =
    badge !== undefined ? (
      <Badge badgeContent={badge} color="primary" max={99}>
        {button}
      </Badge>
    ) : (
      button
    );

  return (
    <Tooltip title={tooltip} enterDelay={500} arrow>
      <span>{wrappedButton}</span>
    </Tooltip>
  );
}

export default function EditorToolbar({
  onAddElement,
  onDeleteElement,
  onCopyElement,
  onToggleLock,
  zoom,
  onZoomChange,
  showGrid,
  onToggleGrid,
  snapOptions,
  onSnapOptionsChange,
  canUndo,
  canRedo,
  onUndo,
  onRedo,
  onSave,
  onPreview,
  hasSelection,
  isLocked,
  isSaving,
  currentPageIndex,
  totalPages,
  currentPageName,
  onPrevPage,
  onNextPage,
  hasUnsavedChanges = false,
  lastSavedAt,
  onOpenCommandPalette,
  onOpenHistory,
  autoSaveEnabled = true,
  onAutoSaveToggle,
}: EditorToolbarProps) {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
  const isTablet = useMediaQuery(theme.breakpoints.between("sm", "md"));
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("lg"));

  const [addMenuAnchor, setAddMenuAnchor] = useState<HTMLElement | null>(null);
  const [zoomMenuAnchor, setZoomMenuAnchor] = useState<HTMLElement | null>(
    null,
  );
  const [shortcutsAnchor, setShortcutsAnchor] = useState<HTMLElement | null>(
    null,
  );
  const [snapMenuAnchor, setSnapMenuAnchor] = useState<HTMLElement | null>(
    null,
  );

  const [pageMenuAnchor, setPageMenuAnchor] = useState<HTMLElement | null>(
    null,
  );
  const [showSecondRow, setShowSecondRow] = useState(false);

  // Count active snap options
  const activeSnapCount = Object.values(snapOptions).filter(Boolean).length;

  // Toggle individual snap option
  const handleToggleSnapOption = (key: keyof SnapOptions) => {
    onSnapOptionsChange({
      ...snapOptions,
      [key]: !snapOptions[key],
    });
  };

  // Toggle all snap options
  const handleToggleAllSnap = () => {
    const allEnabled = activeSnapCount === SNAP_OPTIONS_CONFIG.length;
    const newValue = !allEnabled;
    onSnapOptionsChange({
      grid: newValue,
      objects: newValue,
      borders: newValue,
      center: newValue,
      tangent: newValue,
    });
  };

  const handleAddElement = (type: ElementType) => {
    onAddElement(type);
    setAddMenuAnchor(null);
  };

  // Save status indicator
  const renderSaveStatus = () => {
    return (
      <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
        {/* Auto-save toggle */}
        {onAutoSaveToggle && (
          <Tooltip
            title={
              autoSaveEnabled
                ? "Auto-salvataggio attivo"
                : "Auto-salvataggio disattivato"
            }
          >
            <IconButton
              size="small"
              onClick={() => onAutoSaveToggle(!autoSaveEnabled)}
              sx={{
                borderRadius: 1.5,
                bgcolor: autoSaveEnabled
                  ? alpha(theme.palette.success.main, 0.1)
                  : alpha(theme.palette.grey[500], 0.1),
                color: autoSaveEnabled ? "success.main" : "text.disabled",
                "&:hover": {
                  bgcolor: autoSaveEnabled
                    ? alpha(theme.palette.success.main, 0.2)
                    : alpha(theme.palette.grey[500], 0.2),
                },
              }}
            >
              <AutoSaveIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        )}

        {/* Save status */}
        {isSaving ? (
          <Tooltip title="Salvataggio in corso...">
            <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
              <CircularProgress size={16} />
              <Typography variant="caption" color="text.secondary">
                Salvo...
              </Typography>
            </Box>
          </Tooltip>
        ) : hasUnsavedChanges ? (
          <Tooltip
            title={
              autoSaveEnabled
                ? "Salvataggio automatico in attesa..."
                : "Modifiche non salvate"
            }
          >
            <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
              <UnsavedIcon fontSize="small" sx={{ color: "warning.main" }} />
              <Typography variant="caption" color="warning.main">
                Non salvato
              </Typography>
            </Box>
          </Tooltip>
        ) : (
          <Tooltip
            title={
              lastSavedAt
                ? `Ultimo salvataggio: ${formatTimeAgo(lastSavedAt)}`
                : "Salvato"
            }
          >
            <Box sx={{ display: "flex", alignItems: "center", gap: 0.5 }}>
              <SavedIcon fontSize="small" sx={{ color: "success.main" }} />
              <Typography variant="caption" color="success.main">
                {formatTimeAgo(lastSavedAt) || "Salvato"}
              </Typography>
            </Box>
          </Tooltip>
        )}
      </Box>
    );
  };

  // Mobile: Compact toolbar with essential actions
  if (isMobile) {
    return (
      <Paper
        elevation={0}
        sx={{
          borderBottom: 1,
          borderColor: "divider",
          bgcolor: "background.paper",
        }}
      >
        {/* Primary Row */}
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            gap: 0.5,
            px: 1,
            py: 0.75,
          }}
        >
          {/* Add Element */}
          <Button
            variant="contained"
            size="small"
            onClick={(e) => setAddMenuAnchor(e.currentTarget)}
            sx={{
              minWidth: 36,
              width: 36,
              height: 36,
              p: 0,
              borderRadius: 2,
            }}
          >
            <AddIcon />
          </Button>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.25 }} />

          {/* Undo/Redo */}
          <StyledIconButton
            tooltip="Annulla"
            onClick={onUndo}
            disabled={!canUndo}
          >
            <UndoIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip="Ripeti"
            onClick={onRedo}
            disabled={!canRedo}
          >
            <RedoIcon fontSize="small" />
          </StyledIconButton>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.25 }} />

          {/* Delete */}
          <StyledIconButton
            tooltip="Elimina"
            onClick={onDeleteElement}
            disabled={!hasSelection}
            color="#f44336"
          >
            <DeleteIcon fontSize="small" />
          </StyledIconButton>

          <Box flex={1} />

          {/* Page Navigation - Compact */}
          <Button
            size="small"
            onClick={(e) => setPageMenuAnchor(e.currentTarget)}
            endIcon={<DropdownIcon />}
            sx={{
              bgcolor: "grey.100",
              borderRadius: 1.5,
              textTransform: "none",
              fontFamily: "monospace",
              fontWeight: 600,
              px: 1,
            }}
          >
            {currentPageIndex + 1}/{totalPages}
          </Button>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.25 }} />

          {/* Save/Preview */}
          <StyledIconButton tooltip="Anteprima" onClick={onPreview}>
            <PreviewIcon fontSize="small" />
          </StyledIconButton>
          {!autoSaveEnabled && (
            <StyledIconButton
              tooltip="Salva"
              onClick={onSave}
              disabled={isSaving}
              color="#1976d2"
              active={hasUnsavedChanges}
            >
              {isSaving ? (
                <CircularProgress size={18} />
              ) : (
                <SaveIcon fontSize="small" />
              )}
            </StyledIconButton>
          )}

          {/* Expand/Collapse */}
          <IconButton
            size="small"
            onClick={() => setShowSecondRow(!showSecondRow)}
          >
            {showSecondRow ? <ExpandLessIcon /> : <ExpandMoreIcon />}
          </IconButton>
        </Box>

        {/* Secondary Row - Collapsible */}
        <Collapse in={showSecondRow}>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              gap: 0.5,
              px: 1,
              py: 0.5,
              borderTop: 1,
              borderColor: "divider",
              bgcolor: alpha(theme.palette.primary.main, 0.02),
            }}
          >
            {/* Zoom */}
            <StyledIconButton
              tooltip="Zoom out"
              onClick={() => onZoomChange(Math.max(0.25, zoom - 0.25))}
            >
              <ZoomOutIcon fontSize="small" />
            </StyledIconButton>
            <Button
              size="small"
              onClick={(e) => setZoomMenuAnchor(e.currentTarget)}
              sx={{
                minWidth: 55,
                fontFamily: "monospace",
                fontWeight: 600,
                bgcolor: "grey.100",
                borderRadius: 1,
              }}
            >
              {Math.round(zoom * 100)}%
            </Button>
            <StyledIconButton
              tooltip="Zoom in"
              onClick={() => onZoomChange(Math.min(3, zoom + 0.25))}
            >
              <ZoomInIcon fontSize="small" />
            </StyledIconButton>

            <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

            {/* Grid & Snap */}
            <StyledIconButton
              tooltip="Griglia"
              onClick={onToggleGrid}
              active={showGrid}
            >
              {showGrid ? (
                <GridIcon fontSize="small" />
              ) : (
                <GridOffIcon fontSize="small" />
              )}
            </StyledIconButton>
            <StyledIconButton
              tooltip="Snap"
              onClick={(e) => setSnapMenuAnchor(e.currentTarget)}
              active={activeSnapCount > 0}
              badge={activeSnapCount || undefined}
            >
              <SnapIcon fontSize="small" />
            </StyledIconButton>

            <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

            {/* Copy/Lock */}
            <StyledIconButton
              tooltip="Duplica"
              onClick={onCopyElement}
              disabled={!hasSelection}
            >
              <CopyIcon fontSize="small" />
            </StyledIconButton>
            <StyledIconButton
              tooltip={isLocked ? "Sblocca" : "Blocca"}
              onClick={onToggleLock}
              disabled={!hasSelection}
              active={isLocked}
              color="#ff9800"
            >
              {isLocked ? (
                <LockIcon fontSize="small" />
              ) : (
                <UnlockIcon fontSize="small" />
              )}
            </StyledIconButton>
          </Box>
        </Collapse>

        {/* Add Menu */}
        <Menu
          anchorEl={addMenuAnchor}
          open={Boolean(addMenuAnchor)}
          onClose={() => setAddMenuAnchor(null)}
          PaperProps={{ sx: { borderRadius: 2, minWidth: 200 } }}
        >
          {ELEMENT_TYPES.map(
            ({ type, icon: Icon, label, color, description }) => (
              <MenuItem
                key={type}
                onClick={() => handleAddElement(type)}
                sx={{ py: 1.5 }}
              >
                <ListItemIcon>
                  <Avatar
                    sx={{ bgcolor: alpha(color, 0.15), width: 32, height: 32 }}
                  >
                    <Icon sx={{ color, fontSize: 18 }} />
                  </Avatar>
                </ListItemIcon>
                <ListItemText
                  primary={label}
                  secondary={description}
                  primaryTypographyProps={{ fontWeight: 500 }}
                  secondaryTypographyProps={{ fontSize: "0.7rem" }}
                />
              </MenuItem>
            ),
          )}
        </Menu>

        {/* Page Menu */}
        <Menu
          anchorEl={pageMenuAnchor}
          open={Boolean(pageMenuAnchor)}
          onClose={() => setPageMenuAnchor(null)}
        >
          <Box sx={{ px: 2, py: 1 }}>
            <Typography variant="subtitle2" fontWeight={600}>
              {currentPageName}
            </Typography>
          </Box>
          <Divider />
          <MenuItem
            onClick={() => {
              onPrevPage();
              setPageMenuAnchor(null);
            }}
            disabled={currentPageIndex <= 0}
          >
            <ListItemIcon>
              <PrevPageIcon />
            </ListItemIcon>
            <ListItemText>Pagina precedente</ListItemText>
          </MenuItem>
          <MenuItem
            onClick={() => {
              onNextPage();
              setPageMenuAnchor(null);
            }}
            disabled={currentPageIndex >= totalPages - 1}
          >
            <ListItemIcon>
              <NextPageIcon />
            </ListItemIcon>
            <ListItemText>Pagina successiva</ListItemText>
          </MenuItem>
        </Menu>

        {/* Snap Menu (shared) */}
        <Popover
          open={Boolean(snapMenuAnchor)}
          anchorEl={snapMenuAnchor}
          onClose={() => setSnapMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
          PaperProps={{ sx: { borderRadius: 2 } }}
        >
          <Box sx={{ p: 1.5, minWidth: 220 }}>
            <Box
              display="flex"
              justifyContent="space-between"
              alignItems="center"
              mb={1}
            >
              <Typography variant="subtitle2" fontWeight={600}>
                Opzioni Snap
              </Typography>
              <Switch
                size="small"
                checked={activeSnapCount === SNAP_OPTIONS_CONFIG.length}
                onChange={handleToggleAllSnap}
              />
            </Box>
            <Divider sx={{ mb: 1 }} />
            {SNAP_OPTIONS_CONFIG.map(({ key, icon: Icon, label }) => (
              <ListItemButton
                key={key}
                onClick={() => handleToggleSnapOption(key)}
                dense
                sx={{
                  borderRadius: 1,
                  mb: 0.5,
                  bgcolor: snapOptions[key]
                    ? alpha(theme.palette.primary.main, 0.08)
                    : "transparent",
                }}
              >
                <ListItemIcon sx={{ minWidth: 32 }}>
                  <Icon
                    fontSize="small"
                    color={snapOptions[key] ? "primary" : "inherit"}
                  />
                </ListItemIcon>
                <ListItemText
                  primary={label}
                  primaryTypographyProps={{ variant: "body2" }}
                />
                <Switch size="small" checked={snapOptions[key]} />
              </ListItemButton>
            ))}
          </Box>
        </Popover>

        {/* Zoom Popover */}
        <Popover
          open={Boolean(zoomMenuAnchor)}
          anchorEl={zoomMenuAnchor}
          onClose={() => setZoomMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
          PaperProps={{ sx: { borderRadius: 2 } }}
        >
          <Box sx={{ p: 1.5, width: 180 }}>
            <Slider
              value={zoom}
              min={0.25}
              max={3}
              step={0.05}
              onChange={(_, value) => onZoomChange(value as number)}
              size="small"
              valueLabelDisplay="auto"
              valueLabelFormat={(v) => `${Math.round(v * 100)}%`}
            />
            <Divider sx={{ my: 1 }} />
            <Box display="flex" flexWrap="wrap" gap={0.5}>
              {ZOOM_PRESETS.map(({ value, label }) => (
                <Chip
                  key={value}
                  label={label}
                  size="small"
                  variant={zoom === value ? "filled" : "outlined"}
                  color={zoom === value ? "primary" : "default"}
                  onClick={() => {
                    onZoomChange(value);
                    setZoomMenuAnchor(null);
                  }}
                  sx={{ fontSize: "0.7rem", cursor: "pointer" }}
                />
              ))}
            </Box>
          </Box>
        </Popover>
      </Paper>
    );
  }

  // Tablet: Medium toolbar
  if (isTablet) {
    return (
      <Paper
        elevation={0}
        sx={{
          borderBottom: 1,
          borderColor: "divider",
          bgcolor: "background.paper",
        }}
      >
        <Box
          sx={{
            display: "flex",
            alignItems: "center",
            gap: 0.5,
            px: 1.5,
            py: 0.75,
          }}
        >
          {/* Add Element */}
          <Button
            variant="contained"
            size="small"
            startIcon={<AddIcon />}
            onClick={(e) => setAddMenuAnchor(e.currentTarget)}
            sx={{ borderRadius: 2, textTransform: "none", fontWeight: 600 }}
          >
            Aggiungi
          </Button>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

          {/* Quick Add Buttons */}
          {ELEMENT_TYPES.slice(0, 3).map(
            ({ type, icon: Icon, label, color }) => (
              <StyledIconButton
                key={type}
                tooltip={label}
                onClick={() => onAddElement(type)}
                color={color}
              >
                <Icon fontSize="small" />
              </StyledIconButton>
            ),
          )}

          <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

          {/* Selection Actions */}
          <StyledIconButton
            tooltip="Duplica"
            onClick={onCopyElement}
            disabled={!hasSelection}
          >
            <CopyIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip="Elimina"
            onClick={onDeleteElement}
            disabled={!hasSelection}
            color="#f44336"
          >
            <DeleteIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip={isLocked ? "Sblocca" : "Blocca"}
            onClick={onToggleLock}
            disabled={!hasSelection}
            active={isLocked}
            color="#ff9800"
          >
            {isLocked ? (
              <LockIcon fontSize="small" />
            ) : (
              <UnlockIcon fontSize="small" />
            )}
          </StyledIconButton>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

          {/* Undo/Redo */}
          <StyledIconButton
            tooltip="Annulla (Ctrl+Z)"
            onClick={onUndo}
            disabled={!canUndo}
          >
            <UndoIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip="Ripeti (Ctrl+Y)"
            onClick={onRedo}
            disabled={!canRedo}
          >
            <RedoIcon fontSize="small" />
          </StyledIconButton>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

          {/* View Controls */}
          <StyledIconButton
            tooltip="Griglia"
            onClick={onToggleGrid}
            active={showGrid}
          >
            {showGrid ? (
              <GridIcon fontSize="small" />
            ) : (
              <GridOffIcon fontSize="small" />
            )}
          </StyledIconButton>
          <StyledIconButton
            tooltip="Snap"
            onClick={(e) => setSnapMenuAnchor(e.currentTarget)}
            active={activeSnapCount > 0}
            badge={activeSnapCount || undefined}
          >
            <SnapIcon fontSize="small" />
          </StyledIconButton>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

          {/* Zoom */}
          <StyledIconButton
            tooltip="Zoom out"
            onClick={() => onZoomChange(Math.max(0.25, zoom - 0.25))}
          >
            <ZoomOutIcon fontSize="small" />
          </StyledIconButton>
          <Button
            size="small"
            onClick={(e) => setZoomMenuAnchor(e.currentTarget)}
            sx={{
              minWidth: 55,
              fontFamily: "monospace",
              fontWeight: 600,
              bgcolor: "grey.100",
              borderRadius: 1.5,
            }}
          >
            {Math.round(zoom * 100)}%
          </Button>
          <StyledIconButton
            tooltip="Zoom in"
            onClick={() => onZoomChange(Math.min(3, zoom + 0.25))}
          >
            <ZoomInIcon fontSize="small" />
          </StyledIconButton>

          <Divider orientation="vertical" flexItem sx={{ mx: 0.5 }} />

          {/* Page Navigation */}
          <StyledIconButton
            tooltip="Pagina precedente"
            onClick={onPrevPage}
            disabled={currentPageIndex <= 0}
          >
            <PrevPageIcon fontSize="small" />
          </StyledIconButton>
          <Tooltip title={currentPageName}>
            <Button
              size="small"
              onClick={(e) => setPageMenuAnchor(e.currentTarget)}
              sx={{
                fontFamily: "monospace",
                fontWeight: 600,
                bgcolor: "grey.100",
                borderRadius: 1.5,
                px: 1.5,
              }}
            >
              <PageIcon
                fontSize="small"
                sx={{ mr: 0.5, color: "primary.main" }}
              />
              {currentPageIndex + 1}/{totalPages}
            </Button>
          </Tooltip>
          <StyledIconButton
            tooltip="Pagina successiva"
            onClick={onNextPage}
            disabled={currentPageIndex >= totalPages - 1}
          >
            <NextPageIcon fontSize="small" />
          </StyledIconButton>

          <Box flex={1} />

          {/* Actions */}
          <Button
            variant="outlined"
            size="small"
            startIcon={<PreviewIcon />}
            onClick={onPreview}
            sx={{ borderRadius: 2, textTransform: "none" }}
          >
            Anteprima
          </Button>
          {!autoSaveEnabled && (
            <Button
              variant="contained"
              size="small"
              startIcon={
                isSaving ? (
                  <CircularProgress size={16} color="inherit" />
                ) : (
                  <SaveIcon />
                )
              }
              onClick={onSave}
              disabled={isSaving}
              sx={{ borderRadius: 2, textTransform: "none", fontWeight: 600 }}
            >
              {isSaving ? "Salvo..." : "Salva"}
            </Button>
          )}
        </Box>

        {/* Shared Popovers */}
        <Menu
          anchorEl={addMenuAnchor}
          open={Boolean(addMenuAnchor)}
          onClose={() => setAddMenuAnchor(null)}
          PaperProps={{ sx: { borderRadius: 2, minWidth: 220 } }}
        >
          {ELEMENT_TYPES.map(
            ({ type, icon: Icon, label, color, description, shortcut }) => (
              <MenuItem
                key={type}
                onClick={() => handleAddElement(type)}
                sx={{ py: 1.5 }}
              >
                <ListItemIcon>
                  <Avatar
                    sx={{ bgcolor: alpha(color, 0.15), width: 36, height: 36 }}
                  >
                    <Icon sx={{ color, fontSize: 20 }} />
                  </Avatar>
                </ListItemIcon>
                <ListItemText
                  primary={label}
                  secondary={description}
                  primaryTypographyProps={{ fontWeight: 500 }}
                  secondaryTypographyProps={{ fontSize: "0.7rem" }}
                />
                <Chip
                  label={shortcut}
                  size="small"
                  variant="outlined"
                  sx={{ height: 20, fontSize: "0.65rem" }}
                />
              </MenuItem>
            ),
          )}
        </Menu>

        <Popover
          open={Boolean(snapMenuAnchor)}
          anchorEl={snapMenuAnchor}
          onClose={() => setSnapMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
          PaperProps={{ sx: { borderRadius: 2 } }}
        >
          <Box sx={{ p: 1.5, minWidth: 260 }}>
            <Box
              display="flex"
              justifyContent="space-between"
              alignItems="center"
              mb={1}
            >
              <Typography variant="subtitle2" fontWeight={600}>
                Opzioni Snap
              </Typography>
              <FormControlLabel
                control={
                  <Switch
                    size="small"
                    checked={activeSnapCount === SNAP_OPTIONS_CONFIG.length}
                    onChange={handleToggleAllSnap}
                  />
                }
                label={<Typography variant="caption">Tutti</Typography>}
                labelPlacement="start"
                sx={{ mr: 0 }}
              />
            </Box>
            <Divider sx={{ mb: 1 }} />
            {SNAP_OPTIONS_CONFIG.map(
              ({ key, icon: Icon, label, description }) => (
                <ListItemButton
                  key={key}
                  onClick={() => handleToggleSnapOption(key)}
                  sx={{
                    py: 0.5,
                    borderRadius: 1,
                    bgcolor: snapOptions[key]
                      ? alpha(theme.palette.primary.main, 0.08)
                      : "transparent",
                  }}
                >
                  <ListItemIcon sx={{ minWidth: 32 }}>
                    <Icon
                      fontSize="small"
                      color={snapOptions[key] ? "primary" : "inherit"}
                    />
                  </ListItemIcon>
                  <ListItemText
                    primary={label}
                    secondary={description}
                    primaryTypographyProps={{
                      variant: "body2",
                      fontWeight: snapOptions[key] ? 600 : 400,
                    }}
                    secondaryTypographyProps={{ variant: "caption" }}
                  />
                  <Switch size="small" checked={snapOptions[key]} />
                </ListItemButton>
              ),
            )}
          </Box>
        </Popover>

        <Popover
          open={Boolean(zoomMenuAnchor)}
          anchorEl={zoomMenuAnchor}
          onClose={() => setZoomMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
          PaperProps={{ sx: { borderRadius: 2 } }}
        >
          <Box sx={{ p: 1.5, width: 180 }}>
            <Slider
              value={zoom}
              min={0.25}
              max={3}
              step={0.05}
              onChange={(_, value) => onZoomChange(value as number)}
              size="small"
              valueLabelDisplay="auto"
              valueLabelFormat={(v) => `${Math.round(v * 100)}%`}
            />
            <Divider sx={{ my: 1 }} />
            <Box display="flex" flexWrap="wrap" gap={0.5}>
              {ZOOM_PRESETS.map(({ value, label }) => (
                <Chip
                  key={value}
                  label={label}
                  size="small"
                  variant={zoom === value ? "filled" : "outlined"}
                  color={zoom === value ? "primary" : "default"}
                  onClick={() => {
                    onZoomChange(value);
                    setZoomMenuAnchor(null);
                  }}
                  sx={{ fontSize: "0.7rem", cursor: "pointer" }}
                />
              ))}
            </Box>
          </Box>
        </Popover>

        <Menu
          anchorEl={pageMenuAnchor}
          open={Boolean(pageMenuAnchor)}
          onClose={() => setPageMenuAnchor(null)}
        >
          <Box sx={{ px: 2, py: 1 }}>
            <Typography variant="subtitle2" fontWeight={600}>
              {currentPageName}
            </Typography>
          </Box>
          <Divider />
          <MenuItem
            onClick={() => {
              onPrevPage();
              setPageMenuAnchor(null);
            }}
            disabled={currentPageIndex <= 0}
          >
            <ListItemIcon>
              <PrevPageIcon />
            </ListItemIcon>
            <ListItemText>Pagina precedente</ListItemText>
          </MenuItem>
          <MenuItem
            onClick={() => {
              onNextPage();
              setPageMenuAnchor(null);
            }}
            disabled={currentPageIndex >= totalPages - 1}
          >
            <ListItemIcon>
              <NextPageIcon />
            </ListItemIcon>
            <ListItemText>Pagina successiva</ListItemText>
          </MenuItem>
        </Menu>
      </Paper>
    );
  }

  // Desktop: Full professional toolbar
  return (
    <Paper
      elevation={0}
      sx={{
        borderBottom: 1,
        borderColor: "divider",
        bgcolor: "background.paper",
      }}
    >
      {/* Main Toolbar Row */}
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 1,
          px: 2,
          py: 1,
        }}
      >
        {/* Add Element - Primary Action */}
        <Button
          variant="contained"
          size="medium"
          startIcon={<AddIcon />}
          onClick={(e) => setAddMenuAnchor(e.currentTarget)}
          sx={{
            borderRadius: 2,
            textTransform: "none",
            fontWeight: 600,
            px: 2,
            boxShadow: 2,
            background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
            "&:hover": {
              boxShadow: 4,
              background: `linear-gradient(135deg, ${theme.palette.primary.dark} 0%, ${theme.palette.primary.main} 100%)`,
            },
          }}
        >
          Aggiungi
        </Button>

        {/* Add Menu with rich descriptions */}
        <Popover
          open={Boolean(addMenuAnchor)}
          anchorEl={addMenuAnchor}
          onClose={() => setAddMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
          PaperProps={{
            sx: { mt: 1, borderRadius: 3, minWidth: 280, overflow: "hidden" },
          }}
        >
          <Box sx={{ p: 1 }}>
            <Typography
              variant="overline"
              sx={{
                px: 1.5,
                py: 0.5,
                display: "block",
                color: "text.secondary",
              }}
            >
              Inserisci elemento
            </Typography>
            <List dense sx={{ py: 0 }}>
              {ELEMENT_TYPES.map(
                ({ type, icon: Icon, label, shortcut, color, description }) => (
                  <ListItemButton
                    key={type}
                    onClick={() => handleAddElement(type)}
                    sx={{
                      py: 1.5,
                      px: 1.5,
                      borderRadius: 2,
                      mb: 0.5,
                      transition: "all 0.15s ease",
                      "&:hover": {
                        bgcolor: alpha(color, 0.08),
                        transform: "translateX(4px)",
                      },
                    }}
                  >
                    <Avatar
                      sx={{
                        bgcolor: alpha(color, 0.12),
                        width: 40,
                        height: 40,
                        mr: 1.5,
                      }}
                    >
                      <Icon sx={{ color, fontSize: 22 }} />
                    </Avatar>
                    <ListItemText
                      primary={label}
                      secondary={description}
                      primaryTypographyProps={{
                        fontWeight: 600,
                        fontSize: "0.95rem",
                      }}
                      secondaryTypographyProps={{
                        fontSize: "0.75rem",
                        color: "text.secondary",
                      }}
                    />
                    <Chip
                      label={shortcut}
                      size="small"
                      variant="outlined"
                      sx={{
                        height: 22,
                        fontSize: "0.7rem",
                        fontFamily: "monospace",
                        fontWeight: 600,
                        borderColor: alpha(color, 0.3),
                        color: color,
                      }}
                    />
                  </ListItemButton>
                ),
              )}
            </List>
          </Box>
        </Popover>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* Quick Add Toolbar */}
        <ToolbarSection label={isSmallScreen ? undefined : "INSERISCI"}>
          {ELEMENT_TYPES.map(({ type, icon: Icon, label, color }) => (
            <StyledIconButton
              key={type}
              tooltip={`${label} (${ELEMENT_TYPES.find((e) => e.type === type)?.shortcut})`}
              onClick={() => onAddElement(type)}
              color={color}
            >
              <Icon fontSize="small" />
            </StyledIconButton>
          ))}
        </ToolbarSection>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* Selection Actions */}
        <ToolbarSection label={isSmallScreen ? undefined : "MODIFICA"}>
          <StyledIconButton
            tooltip="Duplica (Ctrl+D)"
            onClick={onCopyElement}
            disabled={!hasSelection}
          >
            <CopyIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip="Elimina (Canc)"
            onClick={onDeleteElement}
            disabled={!hasSelection}
            color="#f44336"
          >
            <DeleteIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip={isLocked ? "Sblocca (Ctrl+L)" : "Blocca (Ctrl+L)"}
            onClick={onToggleLock}
            disabled={!hasSelection}
            active={isLocked}
            color="#ff9800"
          >
            {isLocked ? (
              <LockIcon fontSize="small" />
            ) : (
              <UnlockIcon fontSize="small" />
            )}
          </StyledIconButton>
        </ToolbarSection>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* History */}
        <ToolbarSection label={isSmallScreen ? undefined : "CRONOLOGIA"}>
          <StyledIconButton
            tooltip="Annulla (Ctrl+Z)"
            onClick={onUndo}
            disabled={!canUndo}
          >
            <UndoIcon fontSize="small" />
          </StyledIconButton>
          <StyledIconButton
            tooltip="Ripeti (Ctrl+Y)"
            onClick={onRedo}
            disabled={!canRedo}
          >
            <RedoIcon fontSize="small" />
          </StyledIconButton>
          {onOpenHistory && (
            <StyledIconButton
              tooltip="Cronologia modifiche"
              onClick={onOpenHistory}
            >
              <HistoryIcon fontSize="small" />
            </StyledIconButton>
          )}
        </ToolbarSection>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* View Controls */}
        <ToolbarSection label={isSmallScreen ? undefined : "VISTA"}>
          <StyledIconButton
            tooltip={showGrid ? "Nascondi griglia (G)" : "Mostra griglia (G)"}
            onClick={onToggleGrid}
            active={showGrid}
          >
            {showGrid ? (
              <GridIcon fontSize="small" />
            ) : (
              <GridOffIcon fontSize="small" />
            )}
          </StyledIconButton>

          <Button
            size="small"
            onClick={(e) => setSnapMenuAnchor(e.currentTarget)}
            startIcon={<SnapIcon />}
            endIcon={
              activeSnapCount > 0 ? (
                <Badge badgeContent={activeSnapCount} color="primary" />
              ) : undefined
            }
            sx={{
              borderRadius: 1.5,
              textTransform: "none",
              fontWeight: 500,
              bgcolor:
                activeSnapCount > 0
                  ? alpha(theme.palette.primary.main, 0.1)
                  : "grey.100",
              color: activeSnapCount > 0 ? "primary.main" : "text.primary",
              px: 1.5,
              "&:hover": {
                bgcolor:
                  activeSnapCount > 0
                    ? alpha(theme.palette.primary.main, 0.2)
                    : "grey.200",
              },
            }}
          >
            Snap
          </Button>
        </ToolbarSection>

        {/* Snap Popover */}
        <Popover
          open={Boolean(snapMenuAnchor)}
          anchorEl={snapMenuAnchor}
          onClose={() => setSnapMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
          PaperProps={{ sx: { mt: 1, borderRadius: 2, minWidth: 300 } }}
        >
          <Box sx={{ p: 2 }}>
            <Box
              display="flex"
              justifyContent="space-between"
              alignItems="center"
              mb={1.5}
            >
              <Typography variant="subtitle1" fontWeight={600}>
                Allineamento automatico
              </Typography>
              <FormControlLabel
                control={
                  <Switch
                    checked={activeSnapCount === SNAP_OPTIONS_CONFIG.length}
                    onChange={handleToggleAllSnap}
                  />
                }
                label={
                  <Typography variant="body2" color="text.secondary">
                    Tutti
                  </Typography>
                }
                labelPlacement="start"
                sx={{ mr: 0 }}
              />
            </Box>
            <Divider sx={{ mb: 1.5 }} />
            <Stack spacing={0.5}>
              {SNAP_OPTIONS_CONFIG.map(
                ({ key, icon: Icon, label, description }) => (
                  <ListItemButton
                    key={key}
                    onClick={() => handleToggleSnapOption(key)}
                    sx={{
                      py: 1,
                      px: 1.5,
                      borderRadius: 2,
                      bgcolor: snapOptions[key]
                        ? alpha(theme.palette.primary.main, 0.08)
                        : "transparent",
                      transition: "all 0.15s ease",
                      "&:hover": {
                        bgcolor: snapOptions[key]
                          ? alpha(theme.palette.primary.main, 0.15)
                          : "action.hover",
                      },
                    }}
                  >
                    <Avatar
                      sx={{
                        width: 32,
                        height: 32,
                        mr: 1.5,
                        bgcolor: snapOptions[key]
                          ? alpha(theme.palette.primary.main, 0.15)
                          : "grey.100",
                      }}
                    >
                      <Icon
                        fontSize="small"
                        sx={{
                          color: snapOptions[key]
                            ? "primary.main"
                            : "text.secondary",
                        }}
                      />
                    </Avatar>
                    <ListItemText
                      primary={label}
                      secondary={description}
                      primaryTypographyProps={{
                        fontWeight: snapOptions[key] ? 600 : 400,
                        color: snapOptions[key]
                          ? "primary.main"
                          : "text.primary",
                      }}
                      secondaryTypographyProps={{ fontSize: "0.75rem" }}
                    />
                    <Switch
                      checked={snapOptions[key]}
                      onClick={(e) => e.stopPropagation()}
                    />
                  </ListItemButton>
                ),
              )}
            </Stack>
          </Box>
        </Popover>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* Zoom Controls */}
        <ToolbarSection label={isSmallScreen ? undefined : "ZOOM"}>
          <StyledIconButton
            tooltip="Riduci zoom (-)"
            onClick={() => onZoomChange(Math.max(0.25, zoom - 0.25))}
          >
            <ZoomOutIcon fontSize="small" />
          </StyledIconButton>

          <Button
            size="small"
            onClick={(e) => setZoomMenuAnchor(e.currentTarget)}
            sx={{
              minWidth: 70,
              borderRadius: 1.5,
              textTransform: "none",
              fontWeight: 600,
              fontFamily: "monospace",
              bgcolor: "grey.100",
              color: "text.primary",
              "&:hover": { bgcolor: "grey.200" },
            }}
          >
            {Math.round(zoom * 100)}%
          </Button>

          <StyledIconButton
            tooltip="Aumenta zoom (+)"
            onClick={() => onZoomChange(Math.min(3, zoom + 0.25))}
          >
            <ZoomInIcon fontSize="small" />
          </StyledIconButton>

          <StyledIconButton
            tooltip="Adatta alla finestra"
            onClick={() => onZoomChange(0.75)}
          >
            <FitIcon fontSize="small" />
          </StyledIconButton>
        </ToolbarSection>

        {/* Zoom Popover */}
        <Popover
          open={Boolean(zoomMenuAnchor)}
          anchorEl={zoomMenuAnchor}
          onClose={() => setZoomMenuAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
          PaperProps={{ sx: { mt: 1, borderRadius: 2, p: 2, width: 220 } }}
        >
          <Typography
            variant="caption"
            color="text.secondary"
            gutterBottom
            sx={{ display: "block" }}
          >
            Livello zoom: {Math.round(zoom * 100)}%
          </Typography>
          <Slider
            value={zoom}
            min={0.25}
            max={3}
            step={0.05}
            onChange={(_, value) => onZoomChange(value as number)}
            valueLabelDisplay="auto"
            valueLabelFormat={(v) => `${Math.round(v * 100)}%`}
            sx={{ mt: 1, mb: 2 }}
          />
          <Typography
            variant="caption"
            color="text.secondary"
            sx={{ mb: 1, display: "block" }}
          >
            Preset
          </Typography>
          <Box display="flex" flexWrap="wrap" gap={0.5}>
            {ZOOM_PRESETS.map(({ value, label }) => (
              <Chip
                key={value}
                label={label}
                size="small"
                variant={Math.abs(zoom - value) < 0.01 ? "filled" : "outlined"}
                color={Math.abs(zoom - value) < 0.01 ? "primary" : "default"}
                onClick={() => {
                  onZoomChange(value);
                  setZoomMenuAnchor(null);
                }}
                sx={{ cursor: "pointer" }}
              />
            ))}
          </Box>
        </Popover>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* Page Navigation */}
        <ToolbarSection label={isSmallScreen ? undefined : "PAGINA"}>
          <StyledIconButton
            tooltip="Pagina precedente (PgUp)"
            onClick={onPrevPage}
            disabled={currentPageIndex <= 0}
          >
            <PrevPageIcon fontSize="small" />
          </StyledIconButton>

          <Button
            size="small"
            onClick={(e) => setPageMenuAnchor(e.currentTarget)}
            endIcon={<DropdownIcon />}
            sx={{
              px: 1.5,
              borderRadius: 1.5,
              textTransform: "none",
              bgcolor: "grey.100",
              "&:hover": { bgcolor: "grey.200" },
            }}
          >
            <PageIcon
              fontSize="small"
              sx={{ mr: 0.5, color: "primary.main" }}
            />
            <Typography variant="body2" fontFamily="monospace" fontWeight={600}>
              {currentPageIndex + 1} / {totalPages}
            </Typography>
          </Button>

          <StyledIconButton
            tooltip="Pagina successiva (PgDn)"
            onClick={onNextPage}
            disabled={currentPageIndex >= totalPages - 1}
          >
            <NextPageIcon fontSize="small" />
          </StyledIconButton>
        </ToolbarSection>

        {/* Page Menu */}
        <Menu
          anchorEl={pageMenuAnchor}
          open={Boolean(pageMenuAnchor)}
          onClose={() => setPageMenuAnchor(null)}
          PaperProps={{ sx: { borderRadius: 2, minWidth: 200 } }}
        >
          <Box sx={{ px: 2, py: 1.5 }}>
            <Typography variant="overline" color="text.secondary">
              Pagina corrente
            </Typography>
            <Typography variant="subtitle1" fontWeight={600}>
              {currentPageName}
            </Typography>
          </Box>
          <Divider />
          <MenuItem
            onClick={() => {
              onPrevPage();
              setPageMenuAnchor(null);
            }}
            disabled={currentPageIndex <= 0}
          >
            <ListItemIcon>
              <PrevPageIcon />
            </ListItemIcon>
            <ListItemText primary="Pagina precedente" secondary="PgUp" />
          </MenuItem>
          <MenuItem
            onClick={() => {
              onNextPage();
              setPageMenuAnchor(null);
            }}
            disabled={currentPageIndex >= totalPages - 1}
          >
            <ListItemIcon>
              <NextPageIcon />
            </ListItemIcon>
            <ListItemText primary="Pagina successiva" secondary="PgDn" />
          </MenuItem>
        </Menu>

        <Box flex={1} />

        {/* Save Status */}
        <Box sx={{ display: "flex", alignItems: "center", mr: 1 }}>
          {renderSaveStatus()}
        </Box>

        {/* Command Palette / Search */}
        {onOpenCommandPalette && (
          <Tooltip title="Cerca comando (Ctrl+K)">
            <Button
              size="small"
              onClick={onOpenCommandPalette}
              startIcon={<SearchIcon />}
              sx={{
                borderRadius: 2,
                textTransform: "none",
                color: "text.secondary",
                bgcolor: "grey.100",
                px: 2,
                "&:hover": { bgcolor: "grey.200" },
              }}
            >
              Cerca...
            </Button>
          </Tooltip>
        )}

        {/* Keyboard Shortcuts */}
        <StyledIconButton
          tooltip="Scorciatoie tastiera"
          onClick={(e) => setShortcutsAnchor(e.currentTarget)}
        >
          <ShortcutsIcon fontSize="small" />
        </StyledIconButton>

        {/* Shortcuts Popover */}
        <Popover
          open={Boolean(shortcutsAnchor)}
          anchorEl={shortcutsAnchor}
          onClose={() => setShortcutsAnchor(null)}
          anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
          transformOrigin={{ vertical: "top", horizontal: "right" }}
          PaperProps={{ sx: { mt: 1, borderRadius: 2, p: 2, minWidth: 300 } }}
        >
          <Typography variant="subtitle1" fontWeight={600} gutterBottom>
            Scorciatoie Tastiera
          </Typography>
          <Divider sx={{ mb: 1.5 }} />
          <Box
            component="table"
            sx={{
              width: "100%",
              "& td": { py: 0.75 },
              "& td:first-of-type": { pr: 2 },
            }}
          >
            <tbody>
              {[
                ["Ctrl + Z", "Annulla"],
                ["Ctrl + Y", "Ripeti"],
                ["Ctrl + S", "Salva"],
                ["Ctrl + D", "Duplica"],
                ["Ctrl + K", "Cerca comando"],
                ["Canc / Backspace", "Elimina"],
                ["Frecce", "Sposta (1px)"],
                ["Shift + Frecce", "Sposta (10px)"],
                ["G", "Mostra/nascondi griglia"],
                ["+ / -", "Zoom in/out"],
                ["PgUp / PgDn", "Cambia pagina"],
              ].map(([key, action]) => (
                <tr key={key}>
                  <td>
                    <Chip
                      label={key}
                      size="small"
                      variant="outlined"
                      sx={{
                        fontFamily: "monospace",
                        fontSize: "0.7rem",
                        height: 24,
                      }}
                    />
                  </td>
                  <td>
                    <Typography variant="body2" color="text.secondary">
                      {action}
                    </Typography>
                  </td>
                </tr>
              ))}
            </tbody>
          </Box>
        </Popover>

        <Divider
          orientation="vertical"
          flexItem
          sx={{ mx: 0.5, height: 32, alignSelf: "center" }}
        />

        {/* Primary Actions */}
        <Button
          variant="outlined"
          size="medium"
          startIcon={<PreviewIcon />}
          onClick={onPreview}
          sx={{
            borderRadius: 2,
            textTransform: "none",
            fontWeight: 500,
            px: 2,
          }}
        >
          Anteprima
        </Button>

        {!autoSaveEnabled && (
          <Button
            variant="contained"
            size="medium"
            startIcon={
              isSaving ? (
                <CircularProgress size={18} color="inherit" />
              ) : hasUnsavedChanges ? (
                <Badge variant="dot" color="warning">
                  <SaveIcon />
                </Badge>
              ) : (
                <SaveIcon />
              )
            }
            onClick={onSave}
            disabled={isSaving}
            sx={{
              borderRadius: 2,
              textTransform: "none",
              fontWeight: 600,
              px: 3,
              boxShadow: 2,
              "&:hover": { boxShadow: 4 },
            }}
          >
            {isSaving ? "Salvataggio..." : "Salva"}
          </Button>
        )}
      </Box>
    </Paper>
  );
}
