import { style, globalStyle } from '@vanilla-extract/css';
import { DefaultReset, toRem, color } from 'folds';

/*
 * CSS custom properties --vojo-* are managed manually (not via createVar)
 * because they're read/written from JS layout logic in AuthLayout.tsx.
 */

/* ── Root page ── */
export const AuthLayout = style({
  width: '100%',
  height: '100dvh',
  position: 'relative',
  display: 'flex',
  flexDirection: 'column',
  overflow: 'hidden',
  // Flat DAWN.bg2 — same backdrop as the Android native splash and the DM 1:1
  // chat surface so cold start / auth read as one continuous canvas.
  background: '#0d0e11',
  color: '#e8e4df',
  // Status-bar inset for native: `#root` no longer reserves it
  // (src/index.css), so the AuthLayout backdrop now extends through the
  // status-bar zone. Padding pushes the mascot / modal stack below the
  // system icons. AuthLayout reads `#root`'s computed paddingTop into
  // `padTop` (AuthLayout.tsx) for its anchor math; with that 0 the math
  // sees the full body height and positions content against the local
  // padding instead.
  paddingTop: 'var(--vojo-safe-top, 0px)',
  boxSizing: 'border-box',

  '@media': {
    'only screen and (max-width: 768px)': {
      vars: {
        '--vojo-mascot-size': 'min(14rem, 30dvh, 60vw)',
        '--vojo-mascot-top': 'clamp(0.5rem, 1.5dvh, 1rem)',
        '--vojo-stack-pad': '0.75rem',
        '--vojo-anchor-ratio': '0.64',
        '--vojo-modal-min-top': 'clamp(7rem, 18dvh, 12rem)',
        '--vojo-modal-gap': '0.75rem',
        '--vojo-footer-space': '4.4rem',
      },
    },
    'only screen and (max-height: 760px)': {
      vars: {
        '--vojo-mascot-size': 'min(12rem, 24dvh, 55vw)',
        '--vojo-mascot-top': '0.5rem',
        '--vojo-anchor-ratio': '0.56',
        '--vojo-modal-min-top': '6rem',
        '--vojo-modal-gap': '0.4rem',
        '--vojo-footer-space': '4rem',
      },
    },
  },
});

/* ── Stack (mascot + modal zone) ── */
export const AuthStack = style({
  flex: '1 1 auto',
  minHeight: 0,
  position: 'relative',
  padding: '0 var(--vojo-stack-pad) var(--vojo-footer-space)',
  boxSizing: 'border-box',
});

export const AuthStackSplash = style({
  padding: 0,
});

/* ── Mascot ── */
export const AuthMascot = style({
  position: 'absolute',
  insetInlineStart: '50%',
  top: 'var(--vojo-mascot-top)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  zIndex: 0,
  transform: 'translateX(-50%)',
});

/*
 * Splash-gate variant: mascot fills the viewport-sized stack and centers both axes.
 * Mirrors the Android 12+ system splash (centered icon on flat background)
 * so the native splash → WebView mount → web AuthSplashScreen handoff reads
 * as one continuous splash that "matures" into a richer render, instead of
 * the previous three-jump sequence (centered launcher icon on black →
 * blank dark body → top-anchored mascot on dark gradient).
 */
export const AuthMascotCentered = style({
  position: 'absolute',
  inset: 0,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  zIndex: 0,
  pointerEvents: 'none',
});

export const AuthMascotHidden = style({
  display: 'none',
});

export const AuthMascotVideo = style({
  display: 'block',
  width: 'var(--vojo-mascot-size)',
  height: 'auto',
  aspectRatio: '1',
  maxWidth: 'calc(100vw - (2 * var(--vojo-stack-pad)))',
  pointerEvents: 'none',
  userSelect: 'none',
  filter: 'drop-shadow(0 0 70px rgba(45, 47, 50, 0.7))',
});

/* ── Modal zone (position driven by JS) ── */
export const AuthModalZone = style({
  position: 'absolute',
  insetInline: 'var(--vojo-stack-pad)',
  top: 'var(--vojo-modal-top)',
  display: 'flex',
  justifyContent: 'center',
  boxSizing: 'border-box',
  zIndex: 1,
});

export const AuthSplashContent = style({
  position: 'relative',
  zIndex: 1,
  minHeight: '100%',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  paddingInline: 'var(--vojo-stack-pad)',
  boxSizing: 'border-box',
});

/* ── Auth card (glassmorphism) ── */
export const AuthCard = style({
  display: 'flex',
  borderRadius: toRem(24),
  backgroundColor: 'transparent',
  boxShadow: '0 24px 70px rgba(0, 0, 0, 0.5)',
  maxWidth: '100%',
});

export const AuthCardContent = style({
  borderRadius: 'inherit',
  backgroundColor: 'rgba(18, 19, 22, 0.55)',
  backdropFilter: 'blur(22px) saturate(150%)',
  WebkitBackdropFilter: 'blur(22px) saturate(150%)',
  border: '1px solid rgba(255, 255, 255, 0.08)',
  width: `min(${toRem(492)}, calc(100vw - 2rem))`,
  boxSizing: 'border-box',
  maxHeight: 'var(--vojo-modal-max-h)',
  overflowY: 'hidden',
});

export const AuthCardContentScrollable = style({
  overflowY: 'auto',
  overscrollBehavior: 'contain',
});

export const AuthCardBody = style({
  display: 'flex',
  flexDirection: 'column',
  padding: `${toRem(32)} ${toRem(40)}`,
  boxSizing: 'border-box',
  gap: toRem(20),

  '@media': {
    'only screen and (max-width: 480px)': {
      padding: `${toRem(20)} ${toRem(24)}`,
      gap: toRem(14),
    },
  },
});

/* ── Server info row ── */
export const ServerRow = style({
  display: 'grid',
  gridTemplateColumns: 'auto min-content',
  gridTemplateRows: 'auto auto',
  gap: '4px',
  paddingBottom: toRem(16),
  marginBottom: toRem(4),
  borderBottom: '1px solid rgba(141, 151, 165, 0.2)',
});

export const ServerLabel = style({
  gridColumn: '1 / -1',
  gridRow: '1',
  fontSize: toRem(13),
  color: 'rgba(232, 228, 223, 0.55)',
});

export const ServerName = style({
  gridColumn: '1',
  gridRow: '2',
  fontSize: toRem(15),
  color: '#e8e4df',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
  whiteSpace: 'nowrap',
  alignSelf: 'center',
});

export const ServerEdit = style({
  gridColumn: '2',
  gridRow: '2',
  alignSelf: 'center',
  fontSize: toRem(13),
  color: '#e8e4df',
  background: 'none',
  border: 'none',
  cursor: 'pointer',
  padding: 0,
  textDecoration: 'underline',
  textUnderlineOffset: '2px',
  whiteSpace: 'nowrap',
  selectors: {
    '&:hover': {
      color: '#ffffff',
    },
  },
});

/* ── Server edit dialog ── */
export const ServerDialog = style({
  position: 'fixed',
  inset: 0,
  zIndex: 100,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
});

export const ServerDialogBackdrop = style({
  position: 'absolute',
  inset: 0,
  backgroundColor: 'rgba(0, 0, 0, 0.6)',
});

export const ServerDialogCard = style({
  position: 'relative',
  backgroundColor: '#1a1b1d',
  border: '1px solid rgba(255, 255, 255, 0.12)',
  borderRadius: toRem(16),
  padding: toRem(32),
  width: `min(${toRem(420)}, calc(100vw - 3rem))`,
  display: 'flex',
  flexDirection: 'column',
  gap: toRem(20),
  color: '#e8e4df',
  boxShadow: '0 16px 48px rgba(0, 0, 0, 0.5)',
});

/* ── Logo ── */
export const AuthLogo = style([
  DefaultReset,
  {
    width: toRem(26),
    height: toRem(26),
    borderRadius: '50%',
  },
]);

/* ── Bottom nav link (e.g. "Впервые здесь? Создать учётную запись") ── */
export const AuthBottomLink = style({
  fontSize: toRem(15),

  '@media': {
    'only screen and (max-width: 480px)': {
      fontSize: toRem(12),
    },
  },
});

/* ── Footer ── */
export const AuthFooter = style({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  gap: '6px',
  width: '100%',
  padding: '20px 24px 10px',
  fontSize: '14px',
  color: 'rgba(232, 228, 223, 0.55)',
  letterSpacing: '0.02em',
});

/* Pre-login proxy entry — a subtle text button under "Powered by Matrix".
   Android-only (gated in ProxySettingsEntry); never affects the bistable
   layout since AuthLayout measures footer.offsetHeight dynamically. */
export const AuthProxyEntry = style({
  appearance: 'none',
  border: 'none',
  background: 'none',
  cursor: 'pointer',
  fontSize: '13px',
  color: 'rgba(232, 228, 223, 0.55)',
  textDecoration: 'underline',
  textUnderlineOffset: '2px',
  padding: '2px 6px',
  selectors: {
    '&:hover': { color: '#ffffff' },
  },
});

/* ── Theme overrides for folds components inside auth card ── */
/* Extract CSS custom property name from folds color token reference */
/* e.g. "var(--oq6d070)" → "--oq6d070" — tied to folds API, not hashed names */
const v = (token: string) => token.replace(/^var\((.+)\)$/, '$1');

globalStyle(`${AuthCardContent}`, {
  vars: {
    /* Background variant: make inputs transparent dark */
    [v(color.Background.Container)]: 'rgba(255, 255, 255, 0.06)',
    [v(color.Background.ContainerHover)]: 'rgba(255, 255, 255, 0.10)',
    [v(color.Background.ContainerActive)]: 'rgba(255, 255, 255, 0.14)',
    [v(color.Background.ContainerLine)]: 'rgba(255, 255, 255, 0.18)',
    [v(color.Background.OnContainer)]: '#e8e4df',

    /* Surface variant */
    [v(color.Surface.Container)]: 'rgba(255, 255, 255, 0.04)',
    [v(color.Surface.ContainerHover)]: 'rgba(255, 255, 255, 0.08)',
    [v(color.Surface.ContainerActive)]: 'rgba(255, 255, 255, 0.12)',
    [v(color.Surface.ContainerLine)]: 'rgba(255, 255, 255, 0.18)',
    [v(color.Surface.OnContainer)]: '#e8e4df',

    /* Primary: white button with dark text */
    [v(color.Primary.Main)]: '#e8e4df',
    [v(color.Primary.MainHover)]: '#ffffff',
    [v(color.Primary.MainActive)]: '#d4d0cc',
    [v(color.Primary.MainLine)]: 'rgba(255, 255, 255, 0.18)',
    [v(color.Primary.OnMain)]: '#121314',
  },
});

globalStyle(`${AuthCardContent} input::placeholder`, {
  color: 'rgba(232, 228, 223, 0.35)',
});

/*
 * Chromium's UA stylesheet paints a saved-credentials overlay on
 * :-webkit-autofill inputs, forcing a light background and dark text. Without
 * this block, the auth inputs render with an opaque rectangle on top of the
 * glass card.
 *
 *   - `transition: background-color 9999s` defers the UA background animation
 *      indefinitely (UA !important still sets the target, but the animated
 *      value never reaches it).
 *   - `-webkit-background-clip: text` clips any residual background to the
 *      glyphs, keeping the glass blur visible behind the text.
 *   - `-webkit-text-fill-color` / `caret-color` override the UA text color
 *      (these aren't touched by UA !important, unlike `color`).
 *
 * There's a separate cosmetic quirk where autofilled text can render in the
 * Arial web-font fallback until the user focuses the input (Chrome doesn't
 * repaint autofill on font-swap). Not fixed — happens once per profile on
 * cold cache, repeat visits hit HTTP cache and render Inter immediately.
 */
globalStyle(
  `${AuthCardContent} input:-webkit-autofill,
   ${AuthCardContent} input:-webkit-autofill:hover,
   ${AuthCardContent} input:-webkit-autofill:focus,
   ${AuthCardContent} input:-webkit-autofill:active`,
  {
    WebkitTextFillColor: '#e8e4df',
    caretColor: '#e8e4df',
    transition: 'background-color 9999s ease-in-out 0s',
    WebkitBackgroundClip: 'text',
  }
);

globalStyle(`${AuthCardContent} a`, {
  color: '#e8e4df',
  textDecoration: 'underline',
  textUnderlineOffset: '2px',
});

globalStyle(`${AuthCardContent} a:hover`, {
  color: '#ffffff',
});
