import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:recipe_flutter/core/l10n/l10n.dart';
import 'package:recipe_flutter/features/pantry/data/pantry_providers.dart';
import 'package:recipe_flutter/features/pantry/domain/pantry_item.dart';
import 'package:recipe_flutter/features/pantry/presentation/pantry_screen.dart';

Widget _buildTestApp(List<PantryItem> items) {
  return ProviderScope(
    overrides: [
      pantryProvider.overrideWith((ref) => items),
    ],
    child: MaterialApp(
      localizationsDelegates: const [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: AppLocalizations.supportedLocales,
      locale: const Locale('sv'),
      home: const Scaffold(body: PantryScreen()),
    ),
  );
}

void main() {
  testWidgets('shows deepest category in pantry chip and full path in tooltip', (
    tester,
  ) async {
    const items = [
      PantryItem(
        id: 1,
        productId: 7,
        productName: 'Jordgubbssylt',
        canonicalName: 'Jordgubbssylt',
        categoryPath: 'Skafferi > Sylt, mos & marmelad > Sylt',
        location: 'Skafferi',
      ),
    ];

    await tester.pumpWidget(_buildTestApp(items));
    await tester.pumpAndSettle();

    expect(find.text('Sylt'), findsOneWidget);
    final tooltipFinder = find.ancestor(
      of: find.text('Sylt'),
      matching: find.byType(Tooltip),
    );
    final tooltip = tester.widget<Tooltip>(tooltipFinder);
    expect(tooltip.message, 'Skafferi > Sylt, mos & marmelad > Sylt');
  });

  testWidgets('falls back to L1/category when category path is missing', (
    tester,
  ) async {
    const items = [
      PantryItem(
        id: 2,
        productId: 8,
        productName: 'Vetemjol',
        canonicalName: 'Vetemjol',
        category: 'Skafferi',
        categoryPath: null,
        location: 'Skafferi',
      ),
    ];

    await tester.pumpWidget(_buildTestApp(items));
    await tester.pumpAndSettle();

    expect(find.text('Skafferi'), findsWidgets);
    final itemTooltipFinder = find.ancestor(
      of: find.byType(Chip).last,
      matching: find.byType(Tooltip),
    );
    final tooltip = tester.widget<Tooltip>(itemTooltipFinder);
    expect(tooltip.message, 'Skafferi');
  });
}
