// SPDX-License-Identifier: Apache-2.0
// Viewport info inherited widget for Chanora.
//
// Computes [LayoutClass] once per frame from the current [MediaQuery] size
// and provides it to the entire widget subtree. Downstream widgets read
// `ViewportInfo.of(context)` instead of calling `LayoutBuilder` or
// `MediaQuery.sizeOf` directly for layout-class decisions.

import 'package:flutter/widgets.dart';

import 'breakpoints.dart';

/// Inherited widget that exposes the current layout class and viewport
/// dimensions to the entire subtree.
///
/// Insert this once near the top of the widget tree (inside the Scaffold
/// body or equivalent). All descendants can then read
/// `ViewportInfo.of(context)` to determine their layout behaviour.
class ViewportInfo extends InheritedWidget {
  /// Creates a [ViewportInfo].
  const ViewportInfo({
    super.key,
    required this.layoutClass,
    required this.width,
    required this.height,
    required super.child,
  });

  /// Current layout class derived from viewport width.
  final LayoutClass layoutClass;

  /// Current viewport width in logical pixels.
  final double width;

  /// Current viewport height in logical pixels.
  final double height;

  /// Returns the nearest [ViewportInfo] in the widget tree.
  ///
  /// Asserts that a [ViewportInfo] ancestor exists.
  static ViewportInfo of(BuildContext context) {
    final info = context.dependOnInheritedWidgetOfExactType<ViewportInfo>();
    assert(info != null, 'No ViewportInfo found in widget tree');
    return info!;
  }

  /// Whether the current layout is compact (< 600dp).
  bool get isCompact => layoutClass == LayoutClass.compact;

  /// Whether the current layout is medium (600–1023dp).
  bool get isMedium => layoutClass == LayoutClass.medium;

  /// Whether the current layout is expanded (≥ 1024dp).
  bool get isExpanded => layoutClass == LayoutClass.expanded;

  /// Whether the layout has room for at least two panels (medium or expanded).
  bool get isWide => !isCompact;

  @override
  bool updateShouldNotify(ViewportInfo old) =>
      layoutClass != old.layoutClass ||
      width != old.width ||
      height != old.height;
}
