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

namespace TeamsISO.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.
///   • TeamsLauncher.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.",
                "TeamsISO — embed",
                MessageBoxButton.OK, MessageBoxImage.Warning);
            return;
        }

        var w = (int)EmbedHost.ActualWidth;
        var h = (int)EmbedHost.ActualHeight;
        if (!TeamsLauncher.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.",
                "TeamsISO — 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.
        TeamsLauncher.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 { TeamsLauncher.RestoreEmbed(); }
        catch { /* defensive — restore is best-effort */ }
    }

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