import 'dart:async';
import 'dart:ui' as ui;

import 'package:device_preview/device_preview.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:jiffy/jiffy.dart';
import 'package:kasy_kit/core/dev_inspector/dev_inspector.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/i18n/translations.g.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_html/html.dart' as html;

const String webDevicePreviewEnabledPrefKey = 'web_device_preview_enabled';
const String _platformPrefKey = 'web_device_preview_platform';
const String _iosIndexPrefKey = 'web_device_preview_ios_index';
const String _androidIndexPrefKey = 'web_device_preview_android_index';
const String _iPadIndexPrefKey = 'web_device_preview_ipad_index';
const String _bgDarkPrefKey = 'web_device_preview_bg_dark';
const String _landscapePrefKey = 'web_device_preview_landscape';
const String _textScalePrefKey = 'web_device_preview_text_scale';

final ValueNotifier<bool> webDevicePreviewEnabledNotifier =
    ValueNotifier<bool>(false);

// Platform order: 0 = iOS, 1 = Android, 2 = iPad

// iOS: compact → standard → pro
final List<DeviceInfo> _iosDevices = [
  Devices.ios.iPhoneSE,
  Devices.ios.iPhone16,
  Devices.ios.iPhone16Pro,
];

// Android: compact → standard → pro
final List<DeviceInfo> _androidDevices = [
  Devices.android.samsungGalaxyA50,
  Devices.android.googlePixel9,
  Devices.android.samsungGalaxyS25,
];

// iPad: standard → pro 11" → pro 13"
final List<DeviceInfo> _iPadDevices = [
  Devices.ios.iPad,
  Devices.ios.iPadPro11Inches,
  Devices.ios.iPadPro13InchesM4,
];

// Compact labels so the pill stays narrow regardless of how many devices we add.
String _shortName(String name) => switch (name) {
      'iPhone SE' => 'SE',
      'iPhone 16' => '16',
      'iPhone 16 Pro' => '16 Pro',
      'iPad' => 'iPad',
      'iPad Pro 11" (M4)' => '11"',
      'iPad Pro 13" (M4)' => '13"',
      'Samsung Galaxy A50' => 'A50',
      'Google Pixel 9' => 'Pixel 9',
      'Samsung Galaxy S25' => 'S25',
      _ => name,
    };

class WebDevicePreview extends StatefulWidget {
  const WebDevicePreview({super.key, required this.child});

  final Widget child;

  static Widget wrap({required Widget child}) {
    if (!kIsWeb || !kDebugMode) return child;
    return WebDevicePreview(child: child);
  }

  @override
  State<WebDevicePreview> createState() => _WebDevicePreviewState();
}

class _WebDevicePreviewState extends State<WebDevicePreview> {
  int _platform = 0; // 0 = iOS, 1 = Android, 2 = iPad
  int _iosIndex = 1;     // default: iPhone 16
  int _androidIndex = 1; // default: Google Pixel 9
  int _iPadIndex = 0;
  bool _controlsVisible = false;
  Timer? _controlsTimer;

  final ValueNotifier<DeviceInfo> _deviceNotifier =
      ValueNotifier<DeviceInfo>(_iosDevices[1]); // iPhone 16
  final ValueNotifier<bool> _frameVisibleNotifier = ValueNotifier<bool>(true);
  final ValueNotifier<bool> _bgDarkNotifier = ValueNotifier<bool>(false);
  final ValueNotifier<bool> _landscapeNotifier = ValueNotifier<bool>(false);
  final ValueNotifier<double> _textScaleNotifier = ValueNotifier<double>(1.0);
  late final ValueNotifier<AppLocale> _localeNotifier;
  final _screenshotKey = GlobalKey();

  static const _textScaleSteps = [1.0, 1.3, 1.5];

  List<DeviceInfo> get _devices => switch (_platform) {
        1 => _androidDevices,
        2 => _iPadDevices,
        _ => _iosDevices,
      };

  int get _currentIndex => switch (_platform) {
        1 => _androidIndex,
        2 => _iPadIndex,
        _ => _iosIndex,
      };

  DeviceInfo get _currentDevice => _devices[_currentIndex];

  @override
  void initState() {
    super.initState();
    _localeNotifier = ValueNotifier<AppLocale>(
      LocaleSettings.instance.currentLocale,
    );
    webDevicePreviewEnabledNotifier.addListener(_onEnabledChanged);
    _bgDarkNotifier.addListener(_onBgChanged);
    unawaited(_bootstrap());
  }

  @override
  void dispose() {
    webDevicePreviewEnabledNotifier.removeListener(_onEnabledChanged);
    _bgDarkNotifier.removeListener(_onBgChanged);
    _deviceNotifier.dispose();
    _frameVisibleNotifier.dispose();
    _bgDarkNotifier.dispose();
    _landscapeNotifier.dispose();
    _textScaleNotifier.dispose();
    _localeNotifier.dispose();
    _controlsTimer?.cancel();
    super.dispose();
  }

  void _onEnabledChanged() {
    if (webDevicePreviewEnabledNotifier.value) {
      _controlsTimer?.cancel();
      _controlsTimer = Timer(const Duration(milliseconds: 800), () {
        if (mounted) setState(() => _controlsVisible = true);
      });
      setState(() {}); // rebuild DevicePreview with enabled: true
    } else {
      _controlsTimer?.cancel();
      setState(() => _controlsVisible = false);
    }
  }

  void _onBgChanged() => setState(() {});

  Future<void> _bootstrap() async {
    final prefs = await SharedPreferences.getInstance();

    final savedEnabled = prefs.getBool(webDevicePreviewEnabledPrefKey) ?? false;
    final savedPlatform = prefs.getInt(_platformPrefKey);
    final savedIosIndex = prefs.getInt(_iosIndexPrefKey);
    final savedAndroidIndex = prefs.getInt(_androidIndexPrefKey);
    final savedIPadIndex = prefs.getInt(_iPadIndexPrefKey);
    final savedBgDark = prefs.getBool(_bgDarkPrefKey);
    final savedLandscape = prefs.getBool(_landscapePrefKey);
    final savedTextScale = prefs.getDouble(_textScalePrefKey);

    if (!mounted) return;
    setState(() {
      if (savedPlatform != null) _platform = savedPlatform.clamp(0, 2);
      if (savedIosIndex != null) {
        _iosIndex = savedIosIndex.clamp(0, _iosDevices.length - 1);
      }
      if (savedAndroidIndex != null) {
        _androidIndex = savedAndroidIndex.clamp(0, _androidDevices.length - 1);
      }
      if (savedIPadIndex != null) {
        _iPadIndex = savedIPadIndex.clamp(0, _iPadDevices.length - 1);
      }
    });
    _deviceNotifier.value = _currentDevice;
    if (savedBgDark != null) _bgDarkNotifier.value = savedBgDark;
    if (savedLandscape != null) _landscapeNotifier.value = savedLandscape;
    if (savedTextScale != null && _textScaleSteps.contains(savedTextScale)) {
      _textScaleNotifier.value = savedTextScale;
    }
    if (savedEnabled) webDevicePreviewEnabledNotifier.value = true;
  }

  Future<void> _close() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(webDevicePreviewEnabledPrefKey, false);
    webDevicePreviewEnabledNotifier.value = false;
  }

  Future<void> _savePlatform() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_platformPrefKey, _platform);
  }

  Future<void> _saveDeviceIndices() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_iosIndexPrefKey, _iosIndex);
    await prefs.setInt(_androidIndexPrefKey, _androidIndex);
    await prefs.setInt(_iPadIndexPrefKey, _iPadIndex);
  }

  Future<void> _saveBgDark() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_bgDarkPrefKey, _bgDarkNotifier.value);
  }

  Future<void> _saveLandscape() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_landscapePrefKey, _landscapeNotifier.value);
  }

  Future<void> _saveTextScale() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setDouble(_textScalePrefKey, _textScaleNotifier.value);
  }

  Future<void> _saveLocale(AppLocale locale) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('app_locale', locale.languageCode);
  }

  void _setPlatform(int p) {
    setState(() => _platform = p);
    _deviceNotifier.value = _currentDevice;
    unawaited(_savePlatform());
  }

  void _toggleFrame() {
    _frameVisibleNotifier.value = !_frameVisibleNotifier.value;
  }

  void _toggleBg() {
    _bgDarkNotifier.value = !_bgDarkNotifier.value;
    unawaited(_saveBgDark());
  }

  void _toggleInspector() {
    WidgetsBinding.instance.debugShowWidgetInspectorOverride =
        !WidgetsBinding.instance.debugShowWidgetInspectorOverride;
  }

  void _copyInspection() {
    devInspectorCopyTriggerNotifier.value = true;
  }

  void _toggleLandscape() {
    _landscapeNotifier.value = !_landscapeNotifier.value;
    unawaited(_saveLandscape());
  }

  void _cycleTextScale() {
    final idx = _textScaleSteps.indexWhere(
      (s) => (s - _textScaleNotifier.value).abs() < 0.01,
    );
    _textScaleNotifier.value =
        _textScaleSteps[(idx + 1) % _textScaleSteps.length];
    unawaited(_saveTextScale());
  }

  void _cycleLocale() {
    const locales = AppLocale.values;
    final idx = locales.indexOf(_localeNotifier.value);
    final next = locales[(idx + 1) % locales.length];
    LocaleSettings.setLocale(next);
    unawaited(Jiffy.setLocale(next.languageCode));
    _localeNotifier.value = next;
    unawaited(_saveLocale(next));
  }

  Future<void> _takeScreenshot() async {
    final boundary = _screenshotKey.currentContext?.findRenderObject()
        as RenderRepaintBoundary?;
    if (boundary == null) return;
    final dpr =
        WidgetsBinding.instance.platformDispatcher.implicitView?.devicePixelRatio
        ?? 2.0;
    final image = await boundary.toImage(pixelRatio: dpr);
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    if (byteData == null) return;
    final bytes = byteData.buffer.asUint8List();
    final blob = html.Blob([bytes], 'image/png');
    final url = html.Url.createObjectUrlFromBlob(blob);
    html.AnchorElement(href: url)
      ..setAttribute(
        'download',
        'preview_${DateTime.now().millisecondsSinceEpoch}.png',
      )
      ..click();
    html.Url.revokeObjectUrl(url);
  }

  void _prev() {
    setState(() {
      switch (_platform) {
        case 1:
          _androidIndex =
              (_androidIndex - 1 + _androidDevices.length) %
              _androidDevices.length;
        case 2:
          _iPadIndex =
              (_iPadIndex - 1 + _iPadDevices.length) % _iPadDevices.length;
        default:
          _iosIndex =
              (_iosIndex - 1 + _iosDevices.length) % _iosDevices.length;
      }
    });
    _deviceNotifier.value = _currentDevice;
    unawaited(_saveDeviceIndices());
  }

  void _next() {
    setState(() {
      switch (_platform) {
        case 1:
          _androidIndex = (_androidIndex + 1) % _androidDevices.length;
        case 2:
          _iPadIndex = (_iPadIndex + 1) % _iPadDevices.length;
        default:
          _iosIndex = (_iosIndex + 1) % _iosDevices.length;
      }
    });
    _deviceNotifier.value = _currentDevice;
    unawaited(_saveDeviceIndices());
  }

  @override
  Widget build(BuildContext context) {
    final enabled = webDevicePreviewEnabledNotifier.value;
    // Depend on ThemeProvider so the pill icon updates when app theme changes.
    final appIsDark = ThemeProvider.of(context).mode == ThemeMode.dark;

    // ThemeData.light() in Flutter 3.x M3 uses a lavender-tinted surface.
    // Passing backgroundColor directly avoids that and gives us an exact color.
    final canvasColor =
        _bgDarkNotifier.value ? const Color(0xFF1C1C1E) : Colors.white;

    final preview = DevicePreview(
      enabled: enabled,
      isToolbarVisible: false,
      backgroundColor: canvasColor,
      storage: DevicePreviewStorage.none(),
      defaultDevice: _currentDevice,
      devices: [..._iosDevices, ..._androidDevices, ..._iPadDevices],
      builder: (context) => ListenableBuilder(
        listenable: _textScaleNotifier,
        builder: (ctx, _) => MediaQuery(
          data: MediaQuery.of(ctx).copyWith(
            textScaler: TextScaler.linear(_textScaleNotifier.value),
          ),
          child: _DeviceSwitchBridge(
            deviceNotifier: _deviceNotifier,
            frameVisibleNotifier: _frameVisibleNotifier,
            landscapeNotifier: _landscapeNotifier,
            child: widget.child,
          ),
        ),
      ),
    );

    if (!enabled) return preview;

    return TapRegionSurface(
      child: Directionality(
      textDirection: TextDirection.ltr,
      child: Stack(
        fit: StackFit.expand,
        children: [
          RepaintBoundary(key: _screenshotKey, child: preview),
          Positioned(
            top: 24,
            right: 24,
            child: AnimatedOpacity(
              opacity: _controlsVisible ? 1.0 : 0.0,
              duration: const Duration(milliseconds: 400),
              child: IgnorePointer(
                ignoring: !_controlsVisible,
                child: ListenableBuilder(
                  listenable: Listenable.merge([
                    _frameVisibleNotifier,
                    _bgDarkNotifier,
                    _landscapeNotifier,
                    _textScaleNotifier,
                    _localeNotifier,
                    WidgetsBinding.instance
                        .debugShowWidgetInspectorOverrideNotifier,
                  ]),
                  builder: (context, child) => _PreviewControls(
                    platform: _platform,
                    deviceName: _shortName(_currentDevice.name),
                    frameVisible: _frameVisibleNotifier.value,
                    bgDark: _bgDarkNotifier.value,
                    appIsDark: appIsDark,
                    isLandscape: _landscapeNotifier.value,
                    textScale: _textScaleNotifier.value,
                    currentLocale: _localeNotifier.value,
                    inspectorEnabled: WidgetsBinding
                        .instance.debugShowWidgetInspectorOverride,
                    onPlatformChanged: _setPlatform,
                    onPrev: _prev,
                    onNext: _next,
                    onToggleFrame: _toggleFrame,
                    onToggleBg: _toggleBg,
                    onToggleAppTheme: () => ThemeProvider.of(context).toggle(),
                    onToggleLandscape: _toggleLandscape,
                    onCycleTextScale: _cycleTextScale,
                    onCycleLocale: _cycleLocale,
                    onToggleInspector: _toggleInspector,
                    onCopyInspection: _copyInspection,
                    onScreenshot: () => unawaited(_takeScreenshot()),
                    onClose: () => unawaited(_close()),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    ),
    );
  }
}

// ---------------------------------------------------------------------------
// Bridge — inside DevicePreview.builder, has DevicePreviewStore in context.
// ---------------------------------------------------------------------------

class _DeviceSwitchBridge extends StatefulWidget {
  const _DeviceSwitchBridge({
    required this.deviceNotifier,
    required this.frameVisibleNotifier,
    required this.landscapeNotifier,
    required this.child,
  });

  final ValueNotifier<DeviceInfo> deviceNotifier;
  final ValueNotifier<bool> frameVisibleNotifier;
  final ValueNotifier<bool> landscapeNotifier;
  final Widget child;

  @override
  State<_DeviceSwitchBridge> createState() => _DeviceSwitchBridgeState();
}

class _DeviceSwitchBridgeState extends State<_DeviceSwitchBridge> {
  @override
  void initState() {
    super.initState();
    widget.deviceNotifier.addListener(_onDeviceChanged);
    widget.frameVisibleNotifier.addListener(_onFrameVisibleChanged);
    widget.landscapeNotifier.addListener(_onOrientationChanged);
    WidgetsBinding.instance.addPostFrameCallback((_) => _syncOrientation());
  }

  @override
  void dispose() {
    widget.deviceNotifier.removeListener(_onDeviceChanged);
    widget.frameVisibleNotifier.removeListener(_onFrameVisibleChanged);
    widget.landscapeNotifier.removeListener(_onOrientationChanged);
    super.dispose();
  }

  void _onDeviceChanged() {
    if (!mounted) return;
    DevicePreview.selectDevice(context, widget.deviceNotifier.value.identifier);
  }

  void _onFrameVisibleChanged() {
    if (!mounted) return;
    final store = Provider.of<DevicePreviewStore>(context, listen: false);
    if (store.data.isFrameVisible != widget.frameVisibleNotifier.value) {
      store.toggleFrame();
    }
  }

  void _onOrientationChanged() => _syncOrientation();

  void _syncOrientation() {
    if (!mounted) return;
    final store = Provider.of<DevicePreviewStore>(context, listen: false);
    final target = widget.landscapeNotifier.value
        ? Orientation.landscape
        : Orientation.portrait;
    if (store.data.orientation != target) {
      store.data = store.data.copyWith(orientation: target);
    }
  }

  @override
  Widget build(BuildContext context) => widget.child;
}

// ---------------------------------------------------------------------------
// Controls pill — StatefulWidget so the platform dropdown can self-manage.
// ---------------------------------------------------------------------------

class _PreviewControls extends StatefulWidget {
  const _PreviewControls({
    required this.platform,
    required this.deviceName,
    required this.frameVisible,
    required this.bgDark,
    required this.appIsDark,
    required this.isLandscape,
    required this.textScale,
    required this.currentLocale,
    required this.inspectorEnabled,
    required this.onPlatformChanged,
    required this.onPrev,
    required this.onNext,
    required this.onToggleFrame,
    required this.onToggleBg,
    required this.onToggleAppTheme,
    required this.onToggleLandscape,
    required this.onCycleTextScale,
    required this.onCycleLocale,
    required this.onToggleInspector,
    required this.onCopyInspection,
    required this.onScreenshot,
    required this.onClose,
  });

  final int platform;
  final String deviceName;
  final bool frameVisible;
  final bool bgDark;
  final bool appIsDark;
  final bool isLandscape;
  final double textScale;
  final AppLocale currentLocale;
  final bool inspectorEnabled;
  final ValueChanged<int> onPlatformChanged;
  final VoidCallback onPrev;
  final VoidCallback onNext;
  final VoidCallback onToggleFrame;
  final VoidCallback onToggleBg;
  final VoidCallback onToggleAppTheme;
  final VoidCallback onToggleLandscape;
  final VoidCallback onCycleTextScale;
  final VoidCallback onCycleLocale;
  final VoidCallback onToggleInspector;
  final VoidCallback onCopyInspection;
  final VoidCallback onScreenshot;
  final VoidCallback onClose;

  @override
  State<_PreviewControls> createState() => _PreviewControlsState();
}

class _PreviewControlsState extends State<_PreviewControls> {
  bool _menuOpen = false;
  bool _toolsMenuOpen = false;
  bool _minimized = true;
  bool _platformBtnHovered = false;
  bool _toolsBtnHovered = false;
  bool _shadowVisible = true;
  Timer? _shadowTimer;

  static const _platformLabels = ['iOS', 'Android', 'iPad'];

  static const _pillDecoration = BoxDecoration(
    color: Color(0xFF2C2C2E),
    borderRadius: BorderRadius.all(Radius.circular(24)),
  );

  static const _pillShadow = [
    BoxShadow(
      color: Color(0x73000000),
      blurRadius: 20,
      offset: Offset(0, 6),
    ),
  ];

  static String _textScaleLabel(double scale) => switch (scale) {
        1.0 => '1×',
        1.3 => '1.3×',
        _ => '1.5×',
      };

  void _toggleMenu() => setState(() {
        _menuOpen = !_menuOpen;
        if (_menuOpen) _toolsMenuOpen = false;
      });

  void _toggleToolsMenu() => setState(() {
        _toolsMenuOpen = !_toolsMenuOpen;
        if (_toolsMenuOpen) _menuOpen = false;
      });

  void _selectPlatform(int i) {
    widget.onPlatformChanged(i);
    setState(() {
      _menuOpen = false;
      _toolsMenuOpen = false;
    });
  }

  @override
  void dispose() {
    _shadowTimer?.cancel();
    super.dispose();
  }

  void _hideShadowDuringAnimation() {
    _shadowTimer?.cancel();
    setState(() => _shadowVisible = false);
    _shadowTimer = Timer(const Duration(milliseconds: 140), () {
      if (mounted) setState(() => _shadowVisible = true);
    });
  }

  void _minimize() {
    setState(() {
      _minimized = true;
      _menuOpen = false;
      _toolsMenuOpen = false;
    });
    _hideShadowDuringAnimation();
  }

  void _maximize() {
    setState(() => _minimized = false);
    _hideShadowDuringAnimation();
  }

  @override
  Widget build(BuildContext context) {
    return TapRegion(
      onTapOutside: (_) {
        if (_menuOpen || _toolsMenuOpen) {
          setState(() {
            _menuOpen = false;
            _toolsMenuOpen = false;
          });
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          AnimatedOpacity(
            opacity: _shadowVisible ? 1.0 : 0.0,
            duration: const Duration(milliseconds: 80),
            child: DecoratedBox(
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(24)),
                boxShadow: _pillShadow,
              ),
              child: AnimatedSize(
                duration: const Duration(milliseconds: 140),
                curve: Curves.easeInOutCubic,
                alignment: Alignment.centerRight,
                child: _minimized ? _buildMinimizedPill() : _buildPill(),
              ),
            ),
          ),
          if (_menuOpen && !_minimized) _buildMenu(),
          if (_toolsMenuOpen && !_minimized) _buildToolsMenu(),
        ],
      ),
    );
  }

  Widget _buildMinimizedPill() {
    return Container(
      height: 40,
      padding: const EdgeInsets.symmetric(horizontal: 4),
      decoration: _pillDecoration,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          _IconBtn(
            icon: Icons.unfold_more_rounded,
            onTap: _maximize,
          ),
          _VerticalDivider(),
          _IconBtn(
            icon: Icons.close_rounded,
            onTap: widget.onClose,
            color: Colors.white54,
          ),
          const SizedBox(width: 2),
        ],
      ),
    );
  }

  Widget _buildPill() {
    return Container(
      height: 40,
      padding: const EdgeInsets.symmetric(horizontal: 4),
      decoration: _pillDecoration,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Platform selector button
          MouseRegion(
            onEnter: (_) => setState(() => _platformBtnHovered = true),
            onExit: (_) => setState(() => _platformBtnHovered = false),
            cursor: SystemMouseCursors.click,
            child: GestureDetector(
            onTap: _toggleMenu,
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 160),
              margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
              decoration: BoxDecoration(
                color: Colors.white.withValues(
                  alpha: _menuOpen ? 0.22 : (_platformBtnHovered ? 0.20 : 0.14),
                ),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _platformLabels[widget.platform],
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(width: 2),
                  AnimatedRotation(
                    turns: _menuOpen ? 0.5 : 0,
                    duration: const Duration(milliseconds: 160),
                    child: const Icon(
                      Icons.keyboard_arrow_down_rounded,
                      color: Colors.white70,
                      size: 13,
                    ),
                  ),
                ],
              ),
            ),
            ),
          ),
          _VerticalDivider(),
          _IconBtn(icon: Icons.chevron_left_rounded, onTap: widget.onPrev),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 8),
            child: Text(
              widget.deviceName,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w500,
                letterSpacing: -0.2,
              ),
            ),
          ),
          _IconBtn(icon: Icons.chevron_right_rounded, onTap: widget.onNext),
          // Locale chip
          _VerticalDivider(),
          _PillChip(
            label: widget.currentLocale.languageCode.toUpperCase(),
            onTap: widget.onCycleLocale,
          ),
          // Tools dropdown
          _VerticalDivider(),
          MouseRegion(
            onEnter: (_) => setState(() => _toolsBtnHovered = true),
            onExit: (_) => setState(() => _toolsBtnHovered = false),
            cursor: SystemMouseCursors.click,
            child: GestureDetector(
              onTap: _toggleToolsMenu,
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 160),
                margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                decoration: BoxDecoration(
                  color: Colors.white.withValues(
                    alpha: _toolsMenuOpen ? 0.22 : (_toolsBtnHovered ? 0.20 : 0.14),
                  ),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Text(
                      'Tools',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(width: 2),
                    AnimatedRotation(
                      turns: _toolsMenuOpen ? 0.5 : 0,
                      duration: const Duration(milliseconds: 160),
                      child: const Icon(
                        Icons.keyboard_arrow_down_rounded,
                        color: Colors.white70,
                        size: 13,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          // Inspector group
          _VerticalDivider(),
          _IconBtn(
            icon: Icons.touch_app_rounded,
            onTap: widget.onToggleInspector,
            color: widget.inspectorEnabled ? Colors.white : Colors.white30,
          ),
          if (widget.inspectorEnabled)
            _IconBtn(
              icon: Icons.content_copy_rounded,
              onTap: widget.onCopyInspection,
            ),
          // Utilities: minimize · close
          _VerticalDivider(),
          _IconBtn(
            icon: Icons.unfold_less_rounded,
            onTap: _minimize,
            color: Colors.white30,
          ),
          _IconBtn(
            icon: Icons.close_rounded,
            onTap: widget.onClose,
            color: Colors.white54,
          ),
          const SizedBox(width: 2),
        ],
      ),
    );
  }

  Widget _buildMenu() {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      padding: const EdgeInsets.symmetric(vertical: 4),
      decoration: BoxDecoration(
        color: const Color(0xFF3A3A3C),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.4),
            blurRadius: 16,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: IntrinsicWidth(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisSize: MainAxisSize.min,
          children: List.generate(_platformLabels.length, (i) {
            final selected = widget.platform == i;
            return _DropdownItem(
              label: _platformLabels[i],
              selected: selected,
              onTap: () => _selectPlatform(i),
            );
          }),
        ),
      ),
    );
  }

  Widget _buildToolsMenu() {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      padding: const EdgeInsets.symmetric(vertical: 4),
      decoration: BoxDecoration(
        color: const Color(0xFF3A3A3C),
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.4),
            blurRadius: 16,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: IntrinsicWidth(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisSize: MainAxisSize.min,
          children: [
            _ToolsItem(
              icon: widget.frameVisible
                  ? Icons.smartphone_rounded
                  : Icons.crop_free_rounded,
              label: t.webDevicePreview.frame,
              checked: widget.frameVisible,
              onTap: widget.onToggleFrame,
            ),
            _ToolsItem(
              icon: Icons.contrast_rounded,
              label: t.webDevicePreview.darkBackground,
              checked: widget.bgDark,
              onTap: widget.onToggleBg,
            ),
            _ToolsItem(
              icon: widget.appIsDark
                  ? Icons.dark_mode_rounded
                  : Icons.light_mode_rounded,
              label: t.webDevicePreview.darkTheme,
              checked: widget.appIsDark,
              onTap: widget.onToggleAppTheme,
            ),
            _ToolsItem(
              icon: widget.isLandscape
                  ? Icons.stay_current_landscape_rounded
                  : Icons.stay_current_portrait_rounded,
              label: t.webDevicePreview.landscape,
              checked: widget.isLandscape,
              onTap: widget.onToggleLandscape,
            ),
            _ToolsItem(
              icon: Icons.text_fields_rounded,
              label: t.webDevicePreview.textScale,
              trailingLabel: _textScaleLabel(widget.textScale),
              onTap: widget.onCycleTextScale,
            ),
            Divider(
              height: 1,
              color: Colors.white.withValues(alpha: 0.10),
            ),
            _ToolsItem(
              icon: Icons.photo_camera_rounded,
              label: t.webDevicePreview.screenshot,
              onTap: () {
                setState(() => _toolsMenuOpen = false);
                widget.onScreenshot();
              },
            ),
          ],
        ),
      ),
    );
  }
}

class _DropdownItem extends StatefulWidget {
  const _DropdownItem({
    required this.label,
    required this.selected,
    required this.onTap,
  });

  final String label;
  final bool selected;
  final VoidCallback onTap;

  @override
  State<_DropdownItem> createState() => _DropdownItemState();
}

class _DropdownItemState extends State<_DropdownItem> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 120),
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
          color: _hovered
              ? Colors.white.withValues(alpha: 0.10)
              : Colors.transparent,
          child: Text(
            widget.label,
            style: TextStyle(
              color: widget.selected ? Colors.white : Colors.white54,
              fontWeight:
                  widget.selected ? FontWeight.w600 : FontWeight.w400,
              fontSize: 13,
            ),
          ),
        ),
      ),
    );
  }
}

class _PillChip extends StatefulWidget {
  const _PillChip({
    required this.label,
    required this.onTap,
  });

  final String label;
  final VoidCallback onTap;

  @override
  State<_PillChip> createState() => _PillChipState();
}

class _PillChipState extends State<_PillChip> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 120),
          margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.white.withValues(alpha: _hovered ? 0.22 : 0.14),
            borderRadius: BorderRadius.circular(20),
          ),
          child: Text(
            widget.label,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 11,
              fontWeight: FontWeight.w600,
              letterSpacing: 0.3,
            ),
          ),
        ),
      ),
    );
  }
}

class _ToolsItem extends StatefulWidget {
  const _ToolsItem({
    required this.icon,
    required this.label,
    required this.onTap,
    this.checked,
    this.trailingLabel,
  });

  final IconData icon;
  final String label;
  final VoidCallback onTap;
  final bool? checked;
  final String? trailingLabel;

  @override
  State<_ToolsItem> createState() => _ToolsItemState();
}

class _ToolsItemState extends State<_ToolsItem> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 120),
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9),
          color: _hovered
              ? Colors.white.withValues(alpha: 0.10)
              : Colors.transparent,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(widget.icon, color: Colors.white60, size: 14),
              const SizedBox(width: 10),
              Text(
                widget.label,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 13,
                  fontWeight: FontWeight.w400,
                ),
              ),
              const SizedBox(width: 16),
              if (widget.trailingLabel != null)
                Text(
                  widget.trailingLabel!,
                  style: const TextStyle(
                    color: Colors.white38,
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                )
              else
                Icon(
                  Icons.check_rounded,
                  size: 14,
                  color: (widget.checked ?? false)
                      ? Colors.white
                      : Colors.transparent,
                ),
            ],
          ),
        ),
      ),
    );
  }
}

class _VerticalDivider extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 1,
      height: 18,
      margin: const EdgeInsets.symmetric(horizontal: 4),
      color: Colors.white.withValues(alpha: 0.12),
    );
  }
}

class _IconBtn extends StatefulWidget {
  const _IconBtn({
    required this.icon,
    required this.onTap,
    this.color = Colors.white60,
  });

  final IconData icon;
  final VoidCallback onTap;
  final Color color;

  @override
  State<_IconBtn> createState() => _IconBtnState();
}

class _IconBtnState extends State<_IconBtn> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => setState(() => _hovered = true),
      onExit: (_) => setState(() => _hovered = false),
      cursor: SystemMouseCursors.click,
      child: GestureDetector(
        onTap: widget.onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 120),
          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
          decoration: BoxDecoration(
            color: _hovered
                ? Colors.white.withValues(alpha: 0.12)
                : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(widget.icon, color: widget.color, size: 16),
        ),
      ),
    );
  }
}
