using System.Windows;
using System.Windows.Interop;
using DragonISO.App.Services;

namespace DragonISO.App;

/// <summary>
/// Phase E.4 experimental â€” hosts an embedded copy of the Teams main
/// window via SetParent. Operator opens this from Settings â†’ DISPLAY â†’
/// 'Embed Teams window'. The host Border's HWND becomes Teams' parent on
/// Loaded; SizeChanged keeps Teams fitted; Closing always restores Teams
/// to a normal top-level window before we exit.
///
/// Failsafes:
///   â€¢ If no Teams window is found at Loaded, show a friendly message
///     instead of leaving the host blank.
///   â€¢ Restore-on-close runs in a finally block so a crash mid-host
///     can't leave Teams orphaned with stripped window styles.
///   â€¢ TeamsEmbedHost.RestoreEmbed is idempotent â€” safe to call even if
///     embedding never succeeded.
/// </summary>
public partial class TeamsEmbedWindow : Window
{
    public TeamsEmbedWindow()
    {
        InitializeComponent();
        Loaded += OnWindowLoaded;
        Closed += OnWindowClosed;
    }

    private void OnWindowLoaded(object sender, RoutedEventArgs e)
    {
        var src = PresentationSource.FromVisual(EmbedHost) as HwndSource;
        if (src is null || src.Handle == IntPtr.Zero)
        {
            MessageBox.Show(
                "Couldn't obtain a host HWND for the embed window. " +
                "Try closing and re-opening the embed window.",
                "Dragon-ISO â€” embed",
                MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        var w = (int)EmbedHost.ActualWidth;
        var h = (int)EmbedHost.ActualHeight;
        if (!TeamsEmbedHost.EmbedTeamsInto(src.Handle, w, h))
        {
            MessageBox.Show(
                "Couldn't find a Microsoft Teams window to embed. " +
                "Launch Teams first (rail camera icon), then re-open this window.",
                "Dragon-ISO â€” embed",
                MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }

    private void OnHostSizeChanged(object sender, SizeChangedEventArgs e)
    {
        // Keep Teams sized to match the host as the embed window resizes.
        // No-op when nothing is embedded.
        TeamsEmbedHost.ResizeEmbedded((int)e.NewSize.Width, (int)e.NewSize.Height);
    }

    private void OnWindowClosed(object? sender, EventArgs e)
    {
        // ALWAYS restore Teams to top-level state when this window closes,
        // even if the embed never succeeded. Idempotent.
        try { TeamsEmbedHost.RestoreEmbed(); }
        catch { /* defensive â€” restore is best-effort */ }
    }

    private void OnClose(object sender, RoutedEventArgs e) => Close();
}
