/**
 * ============================================================================
 * TASKO DESIGN SYSTEM — theme.ts
 * ============================================================================
 *
 * This is the single source of truth for Tasko's visual design.
 * Every color, font size, spacing value, and component customization
 * lives here. MUI reads this file and applies it everywhere.
 *
 * GUIDELINES:
 *   1. Try not to hardcode colors/sizes in components — always use the theme
 *   2. Keep overrides minimal — MUI handles most things automatically
 *   3. On proposing design style changes - ask Uwe
 *   4. Questions about MUI components - ask me
 *
 * HOW TO MODIFY:
 *   - Colors → edit lightPalette below
 *   - Typography → edit the typography section
 *   - Spacing/shape → edit shape and spacing
 *   - Component tweaks → edit the components section
 *
 * Docs: https://mui.com/material-ui/customization/theming/
 * Default theme viewer: https://mui.com/material-ui/customization/default-theme/
 * ============================================================================
 */

import { createTheme } from "@mui/material/styles";
import { isPrimaryMouseButton } from "fullcalendar/src/util";

// =============================================================================
// 1. COLORS — Light Mode
// =============================================================================
// Only define base colors. MUI auto-generates hover/focus/selected states.
// To find these values in Figma: Local Variables → Palette collection
//
// NOTE: Dark mode is not in scope — only the light colorScheme is defined.

const lightPalette = {
  primary: {
    main: "#0084ff",       // Tasko brand blue — confirmed with Uwe
    dark: "#1565C0",
    light: "#2196F3",
    contrastText: "#FFFFFF",
  },
  secondary: {
    main: "#F5F5F5",       // light grey — used for secondary/ghost buttons
    dark: "#E0E0E0",
    light: "#FAFAFA",
    contrastText: "rgba(0, 0, 0, 0.87)",
  },
  error: {
    main: "#e20202",       // brighter red than MUI default — more visible on white
    dark: "#D32F2F",       // red-700
    light: "#F44336",      // red-500
    contrastText: "#FFFFFF",
  },
  warning: {
    main: "#FFD600",       // yellow — dark text needed (see contrastText below)
    dark: "#FBC02D",
    light: "#FFA726",
    contrastText: "rgba(0, 0, 0, 0.87)", // dark text on yellow background
  },
  info: {
    // Info is repurposed as a "white/light" variant for light-on-dark use cases
    main: "#FFFFFF",       // Figma: grey/0
    dark: "#F5F5F5",       // grey/100
    light: "#FAFAFA",      // grey/50
    contrastText: "rgba(0, 0, 0, 0.87)",
  },
  success: {
    main: "#43A047",
    dark: "#2E7D32",
    light: "#66BB6A",
    contrastText: "#FFFFFF",
  },
  text: {
    primary: "rgba(0, 0, 0, 0.87)",
    // secondary and disabled are MUI defaults — no override needed
  },
  background: {
    paper: "#FFFFFF",
    default: "#F9FBFF",    // pale blue page background — confirmed with Uwe
  },
  action: {
    // These control hover/focus/selected opacities globally.
    // MUI defaults: hover 0.04, selected 0.08, focus 0.12
    // Uncomment to adjust if the designer wants different intensities:
    // hoverOpacity: 0.04,
    // selectedOpacity: 0.08,
    // focusOpacity: 0.12,
    active: "rgba(0, 0, 0, 0.54)",
    disabled: "rgba(0, 0, 0, 0.26)",
    disabledBackground: "rgba(0, 0, 0, 0.12)",
  },

  // --- Tasko brand tokens (from Figma: Local Variables → Tasko/colors) ---
  // Commented out — requires module augmentation to type-safe extend the palette.
  // Uncomment and add augmentation file if brand tokens are needed in components.
//   tasko: {
//     brandNavy:           "#243E66",  // Primary brand navy
//     brandLightBlue:      "#02BAF4",  // Accent light blue
//     brandBgLightBlue:    "#E5F1FF",  // Light blue background
//     brandOutlineGreyBlue:"#CFDBE5",  // Outline / border grey-blue
//     menuBar:             "#EEEEEE",  // Top menu bar background
//     sideBar:             "#FEFEFE",  // Sidebar background
//     bgBody:              "#F5F5F5",  // Page body background (grey/100)
//     bgSection:           "#FEFEFE",  // Section/card background
//     logoLightBlue:       "#99CCFF",  // Logo light blue
//     logoBlue:            "#6899C9",  // Logo mid blue
//     logoDarkBlue:        "#356696",  // Logo dark blue
//     mobileGreyHeader:    "#BABBBE",  // Mobile header grey
//     mobileBgBlue:        "#EDF5FD",  // Mobile background blue
//     greyHeader:          "#EEEEEE",  // Grey header (grey/200)
//     darkGreyHeader:      "#E0E0E0",  // Dark grey header (grey/300)
//   },
};

// =============================================================================
// 2. TYPOGRAPHY
// =============================================================================
// To find these values in Figma: Text Styles
//
// We use a compressed heading scale — h2 through h6 are much smaller than
// MUI defaults because our app is data-dense, not marketing/editorial.
//
// NOTE: Figma contains "h1MUI", "h2MUI" etc. styles — do NOT use those here.
//       Those are Figma-only references to MUI's original scale.
//
// Figma token reference (--typography--*):
//   h1=48px  h2=22px  h3=20px  h4=16px  h5=14px  h6=12px
//   body1=16px  body2=14px  subtitle1=16px  subtitle2=14px
//   caption=12px  overline=12px
//
// body1/body2/subtitle/caption/overline match MUI defaults — no override needed.
// All headings use var(--mui-palette-text-primary) so they respond to theme changes.

const typography = {
  h1: { fontSize: "3rem",    fontWeight: 400, color: "var(--mui-palette-text-primary)" },         // 48px — page-level hero titles only
  h2: { fontSize: "1.375rem", fontWeight: 500, lineHeight: "160%", color: "var(--mui-palette-text-primary)" }, // 22px
  h3: { fontSize: "1.25rem",  fontWeight: 500, lineHeight: "160%", color: "var(--mui-palette-text-primary)" }, // 20px — section headers
  h4: { fontSize: "1rem",     fontWeight: 500, lineHeight: "160%", color: "var(--mui-palette-text-primary)" }, // 16px — card headers
  h5: { fontSize: "0.875rem", fontWeight: 500, color: "var(--mui-palette-text-primary)" },                     // 14px — sub-headers
  h6: { fontSize: "0.75rem",  fontWeight: 500, color: "var(--mui-palette-text-primary)" },                     // 12px — labels, captions
};

// =============================================================================
// 3. COMPONENT OVERRIDES
// =============================================================================
// Only add overrides when our design intentionally differs from MUI defaults.
// Always include a comment explaining what changed and why.
//
// Figma token reference for components used below:
//   --button--large: 20px (1.25rem)
//   --button--medium: 16px (1rem)      ← MUI default is 0.875rem, we override
//   --button--small: 14px (0.875rem)   ← MUI default is 0.8125rem, we override
//   --input--label: 12px (0.75rem), letterSpacing: 0.8px
//   --input--value: 20px (1.25rem)     ← MUI default is 1rem, we override
//   --input--helper: 12px (0.75rem)    ← MUI default already 0.75rem ✓
//
// Quick reference for common MUI component names:
//   MuiButton, MuiTextField, MuiOutlinedInput, MuiFilledInput,
//   MuiSelect, MuiCard, MuiPaper, MuiDialog, MuiChip, MuiSwitch,
//   MuiAppBar, MuiDrawer, MuiTable, MuiTableCell, MuiTab, MuiTabs

const components = {
  // --- Buttons ---
  MuiButton: {
    defaultProps: {
      disableElevation: false, // allow elevation on buttons — overrideable per instance
    },
    styleOverrides: {
      root: {
        textTransform: "none" as const, // no uppercase labels
        borderRadius: "var(--mui-shape-borderRadius)",
      },
      sizeLarge: {
        // Figma: --button--large = 20px
        fontSize: "1.25rem",
        fontWeight: 500,
        lineHeight: "26px",
        letterSpacing: "0.46px",
        padding: "8px 22px",
      },
      sizeMedium: {
        // Figma: --button--medium = 16px (MUI default is 0.875rem)
        fontSize: "1rem",
        fontWeight: 500,
        lineHeight: "24px",
        letterSpacing: "0.4px",
        padding: "6px 16px",
      },
      sizeSmall: {
        // Figma: --button--small = 14px (MUI default is 0.8125rem)
        fontSize: "0.875rem",
        fontWeight: 400,
        lineHeight: "22px",
        letterSpacing: "0.46px",
        padding: "4px 10px",
      },
      // Text variant needs tighter padding (no background, so visual weight differs)
      textSizeLarge: { padding: "8px 11px" },
      textSizeMedium: { padding: "6px 8px" },
      textSizeSmall: { padding: "4px 5px" },
    },
  },

  // --- Input / TextField ---
  MuiInputBase: {
    styleOverrides: {
      root: {
        // Figma --input--value = 20px. MUI default is 1rem/16px — too small for our forms.
        fontSize: "1.25rem",
      },
    },
  },

  // --- Input Label ---
  MuiInputLabel: {
    styleOverrides: {
      root: {
        // Figma specifies 0.8px letter spacing on input labels.
        // The Figma plugin didn't export this — added manually.
        letterSpacing: "0.8px",
      },
    },
  },

  // --- Tabs ---
  MuiTab: {
    styleOverrides: {
      root: {
        textTransform: "none" as const, // match button style — no uppercase
        fontSize: "1rem",
        fontWeight: 500,
      },
    },
  },

  // --- Sidebar list items ---
  // Rounded pill style with a left-edge accent bar on selected state.
  // Uses color-mix() to derive hover/selected backgrounds from primary automatically —
  // so if primary.main changes, the sidebar states update with no extra work.
  MuiListItemButton: {
    styleOverrides: {
      root: ({ theme }) => ({
        margin: '2px 8px',           // horizontal gutters so items float inside the sidebar
        borderRadius: '8px',
        width: 'auto',               // needed so margin doesn't collapse full-width default
        '&:hover': {
          backgroundColor: `color-mix(in srgb, ${theme.palette.primary.main} 8%, transparent)`,
        },
        '&.Mui-selected': {
          backgroundColor: `color-mix(in srgb, ${theme.palette.primary.main} 16%, transparent)`,
          borderRadius: '0 8px 8px 0', // flat left edge so the accent bar sits flush
          color: theme.palette.primary.main,
          '& .MuiListItemIcon-root': {
            color: theme.palette.primary.main,
          },
          // Left accent bar via ::before pseudo-element
          '&::before': {
            content: '""',
            position: 'absolute',
            left: 0,
            top: 0,
            height: '100%',
            width: '4px',
            backgroundColor: theme.palette.primary.main,
            borderRadius: '0 4px 4px 0',
          },
          '&:hover': {
            backgroundColor: `color-mix(in srgb, ${theme.palette.primary.main} 20%, transparent)`,
          },
        },
      }),
    },
  },

  // --- Card ---
  // MuiCard has its own internal elevation default (elevation=1) which would
  // override MuiPaper's defaultProps. We set it explicitly here so Card
  // gets the same flat, bordered style as Paper automatically.
  MuiCard: {
    defaultProps: {
      elevation: 0,
    },
  },

  // --- Paper (and Card, which extends Paper) ---
  // Design decision: flat cards with a border instead of shadows.
  // This gives a cleaner, more structured look on the pale blue background.
  //
  // Defaults applied globally:
  //   - elevation: 0 (no shadow)
  //   - border: 1px solid divider colour
  //   - padding: 16px mobile / 20px desktop
  //
  // How to override per component:
  //   - Remove padding:     sx={{ padding: '0 !important' }}
  //   - Restore elevation:  <Paper elevation={3}>
  MuiPaper: {
    defaultProps: {
      elevation: 0,
    },
    styleOverrides: {
      root: {
        border: '1px solid',
        borderColor: 'var(--mui-palette-divider)',
        // Responsive padding — mirrors sx={{ p: { xs: 4, md: 5 } }}
        // (styleOverrides can't use sx breakpoint syntax, so we use raw media queries)
        padding: '16px',
        '@media (min-width: 900px)': {
          padding: '24px', //use p: 0 !important to remove overwrite padding 
        },
      },
    },
    variants: [
      {
        // For components that need zero padding (e.g. task cards with their own internal layout).
        // Usage: <Paper variant="nopadding"> or <Card variant="nopadding">
        // Note: due to MUI TypeScript constraints, sx={{ padding: '0 !important' }} also works.
        props: { variant: 'nopadding' as any },
        style: { padding: 0 },
      },
    ],
  },

  // --- Drawer / Sidebar ---
  // The Drawer paper inherits from MuiPaper, so we need to explicitly cancel
  // the padding and full border, keeping only the right-side divider line.
  // !important is required because MuiPaper root styles have higher cascade priority.
  MuiDrawer: {
    styleOverrides: {
      paper: {
        backgroundColor: '#F7F9FD',  // pale grey-blue sidebar background
        boxSizing: 'border-box' as const,
        border: 'none !important',               // cancel MuiPaper's all-sides border
        borderRight: '1px solid !important',     // only show the right divider
        borderColor: `var(--mui-palette-divider) !important`,
        overflowY: 'auto' as const,
        padding: '0 !important',                 // cancel MuiPaper's default padding
      },
    },
  },

  // ──────────────────────────────────────────────────────────
  // ADD NEW COMPONENT OVERRIDES BELOW THIS LINE
  // Format:
  //   MuiComponentName: {
  //     styleOverrides: {
  //       root: {
  //         // Reason for the override
  //         property: "value",
  //       },
  //     },
  //   },
  // ──────────────────────────────────────────────────────────
};

// =============================================================================
// 4. CREATE THEME — Don't modify this section unless changing infrastructure
// =============================================================================

const theme = createTheme({
  // CSS Variables mode: enables var(--mui-palette-*) syntax throughout the app.
  // colorSchemeSelector: 'class' means dark mode is toggled by adding a class to <html>.
  // We only use 'light' for now — dark mode is not in scope.
  cssVariables: {
    colorSchemeSelector: "class",
  },
  defaultColorScheme: "light",

  colorSchemes: {
    light: { palette: lightPalette },
  },

  typography,

  shape: {
    borderRadius: 10, // Figma: Local Variables → Shape → borderRadius
  },

  // Custom spacing array (in px).
  // Index 1=4px, 2=8px, 3=12px, 4=16px, 5=24px, 6=32px ...
  // IMPORTANT: theme.spacing(1) = 4px, not 8px (MUI default).
  // If adding new components, audit any sx={{ p/m/gap: N }} usages accordingly.
  spacing: [0, 4, 8, 12, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96],

  breakpoints: {
    values: {
      xs: 444,   // Small phones
      sm: 600,   // Large phones
      md: 900,   // Tablets
      lg: 1190,  // Small desktops
      xl: 1536,  // Large desktops
    },
  },

  components,
});

export default theme;