// lib/widgets/viewer/entry_viewer_page_dlna.dart
//
// Viewer locale per DLNA.
// - Nessuna logica di cast qui dentro.
// - Il backend DLNA gestisce invio entry, next, prev, stop.
// - Questo widget notifica solo il cambio entry tramite onEntryChanged.

import 'package:flutter/material.dart';

import 'package:aves/model/entry/entry.dart';
import 'package:aves/widgets/common/basic/scaffold.dart';
import 'package:aves/widgets/common/extensions/theme.dart';
import 'package:aves/widgets/viewer/controls/controller.dart';
import 'package:aves/widgets/viewer/entry_viewer_stack.dart';
import 'package:aves/widgets/viewer/providers.dart';
import 'package:provider/provider.dart';
import 'package:aves/model/source/collection_lens.dart';

class EntryViewerPageDlna extends StatefulWidget {
  final CollectionLens? collection;
  final AvesEntry initialEntry;

  // Controller esterno (obbligatorio)
  final ViewerController viewerController;

  // Callback quando cambia entry
  final void Function(AvesEntry entry)? onEntryChanged;

  const EntryViewerPageDlna({
    super.key,
    this.collection,
    required this.initialEntry,
    required this.viewerController,
    this.onEntryChanged,
  });

  @override
  State<EntryViewerPageDlna> createState() => _EntryViewerPageDlnaState();

  static Color getBackground(BuildContext context) =>
      Theme.of(context).isDark ? Colors.black : Colors.white;
}

class _EntryViewerPageDlnaState extends State<EntryViewerPageDlna> {
  @override
  void initState() {
    super.initState();

    // Ascolta cambio entry dal viewer
    widget.viewerController.entryNotifier.addListener(_onEntryChanged);
  }

  void _onEntryChanged() {
    final entry = widget.viewerController.entryNotifier.value;
    if (entry != null) {
      widget.onEntryChanged?.call(entry);
    }
  }

  @override
  void dispose() {
    widget.viewerController.entryNotifier.removeListener(_onEntryChanged);
    widget.collection?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final collection = widget.collection;

    return AvesScaffold(
      body: MultiProvider(
        providers: [
          ViewStateConductorProvider(),
          VideoConductorProvider(collection: collection),
          MultiPageConductorProvider(),
        ],
        child: EntryViewerStack(
          collection: collection,
          initialEntry: widget.initialEntry,
          viewerController: widget.viewerController,
        ),
      ),
      backgroundColor: Navigator.canPop(context)
          ? Colors.transparent
          : EntryViewerPageDlna.getBackground(context),
      resizeToAvoidBottomInset: false,
    );
  }
}
