using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace DeepDrftShared.Client.Components;

/// <summary>
/// Scroll-driven parallax image window. As the component scrolls up through the viewport,
/// the image pans through the window faster than the page scrolls. An optional second image
/// crossfades in on hover (pure CSS). A <see cref="FullWidth"/> flag breaks the container out
/// of parent padding to span the viewport.
/// </summary>
/// <remarks>
/// Progressive enhancement: renders a static framed image at SSR; the parallax attaches after
/// interactive boot via <c>OnAfterRenderAsync(firstRender)</c>. When <see cref="WindowHeight"/>
/// is left null, the window renders at 300px and the JS module recomputes height from the
/// container width and image aspect ratio (see <see cref="WindowHeightFraction"/>), tracking
/// container resizes — this may cause a layout shift on first paint or on orientation change. Pass an explicit
/// <see cref="WindowHeight"/> for above-the-fold hero usage to avoid the shift.
/// When <see cref="NaturalWidth"/> and <see cref="NaturalHeight"/> are provided, height is set
/// via CSS <c>aspect-ratio</c> at render time — no layout shift occurs on any render mode.
/// </remarks>
public abstract class ParallaxImageBase : ComponentBase, IAsyncDisposable
{
    [Inject] private IJSRuntime JS { get; set; } = default!;

    /// <summary>Primary image URL, shown at rest.</summary>
    [Parameter, EditorRequired] public string Image1 { get; set; } = default!;

    /// <summary>Optional hover image (assumed same dimensions as <see cref="Image1"/>).</summary>
    [Parameter] public string? Image2 { get; set; }

    /// <summary>Accessible name for <see cref="Image1"/>. When null, the window is decorative.</summary>
    [Parameter] public string? Alt1 { get; set; }

    /// <summary>Accessible name for <see cref="Image2"/> (only relevant if it adds semantic meaning).</summary>
    [Parameter] public string? Alt2 { get; set; }

    /// <summary>CSS height of the parallax window. When null, renders at 300px then recomputes from container width, image aspect ratio, and <see cref="WindowHeightFraction"/>.</summary>
    [Parameter] public string? WindowHeight { get; set; }

    /// <summary>
    /// Natural pixel width of <see cref="Image1"/>. When provided together with
    /// <see cref="NaturalHeight"/>, the window height is set via CSS <c>aspect-ratio</c>
    /// at render time — eliminating the SSR/hydration layout shift that occurs when
    /// dimensions are unknown. Has no effect when <see cref="WindowHeight"/> is set.
    /// </summary>
    [Parameter] public int? NaturalWidth { get; set; }

    /// <summary>
    /// Natural pixel height of <see cref="Image1"/>. See <see cref="NaturalWidth"/>.
    /// </summary>
    [Parameter] public int? NaturalHeight { get; set; }

    /// <summary>
    /// Fraction of the aspect-ratio-correct image height to use as the parallax window height.
    /// Only active when <see cref="WindowHeight"/> is null.
    /// E.g. 0.5 (default) = window is half the height the image would be if displayed at full container width.
    /// Recalculates on container resize (orientation change, responsive layout shift).
    /// </summary>
    [Parameter] public double WindowHeightFraction { get; set; } = 0.5;

    /// <summary><c>background-size</c> width.</summary>
    [Parameter] public string ImageWidth { get; set; } = "auto";

    /// <summary><c>background-size</c> height.</summary>
    [Parameter] public string ImageHeight { get; set; } = "auto";

    /// <summary>When true, stretches the container to 100vw via a negative-margin breakout.</summary>
    [Parameter] public bool FullWidth { get; set; }

    /// <summary>Speed multiplier, clamped to [0,1] in the JS module.</summary>
    [Parameter] public double ParallaxSpeed { get; set; } = 0.5;

    /// <summary>When false: top-on-entry to bottom-at-top. When true: inverted.</summary>
    [Parameter] public bool InvertDirection { get; set; }

    /// <summary>Extra CSS classes on the outer element.</summary>
    [Parameter] public string? Class { get; set; }

    protected ElementReference WindowRef;
    protected string WindowStyle { get; private set; } = "--window-height: 300px; --parallax-from: 0%; --parallax-to: 50%;";

    private bool AspectRatioMode =>
        WindowHeight is null && NaturalWidth is > 0 && NaturalHeight is > 0;

    private IJSObjectReference? _module;
    private string? _handle;

    // --parallax-from/--parallax-to are inherited custom properties read by the
    // CSS @keyframes parallax-pan, which animates background-position-y on each
    // .layer (scroll-driven, pre-WASM). They encode ParallaxSpeed and
    // InvertDirection. After WASM boots, parallax.js sets data-parallax-active to
    // cancel that animation and drives background-position-y on the layers
    // directly — a clean handoff with no competing writers.
    private string ParallaxVars()
    {
        var end = (int)Math.Round(ParallaxSpeed * 100);
        end = Math.Max(1, end); // floor at 1% so the property is always valid
        return InvertDirection
            ? $"--parallax-from: {end}%; --parallax-to: 0%;"
            : $"--parallax-from: 0%; --parallax-to: {end}%;";
    }

    protected override void OnParametersSet()
    {
        var pv = ParallaxVars();
        if (WindowHeight != null)
        {
            WindowStyle = $"--window-height: {WindowHeight}; {pv}";
        }
        else if (AspectRatioMode)
        {
            // Aspect-ratio mode: height: auto lets aspect-ratio take effect;
            // the inline height: auto overrides the CSS --window-height rule.
            // aspect-ratio: W / (H * fraction) → window is WindowHeightFraction
            // of the image's full display height at container width.
            var h = Math.Max(1, (int)Math.Round(NaturalHeight!.Value * WindowHeightFraction));
            WindowStyle = $"height: auto; aspect-ratio: {NaturalWidth!.Value} / {h}; {pv}";
        }
        else
        {
            WindowStyle = $"--window-height: 300px; {pv}";
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
        {
            return;
        }

        _module = await JS.InvokeAsync<IJSObjectReference>(
            "import", "./_content/DeepDrftShared.Client/js/parallax/parallax.js");

        _handle = await _module.InvokeAsync<string>(
            "register",
            WindowRef,
            new
            {
                speed = ParallaxSpeed,
                invertDirection = InvertDirection,
                // heightFraction is null in explicit-height and aspect-ratio modes;
                // JS auto-height only runs in the fallback (no dimensions provided).
                heightFraction = (WindowHeight == null && !AspectRatioMode)
                    ? (double?)WindowHeightFraction
                    : null,
                image1 = Image1
            });
    }

    public async ValueTask DisposeAsync()
    {
        if (_module != null)
        {
            try
            {
                if (_handle != null)
                {
                    await _module.InvokeVoidAsync("unregister", _handle);
                }

                await _module.DisposeAsync();
            }
            catch (JSDisconnectedException)
            {
                // Circuit already torn down (e.g. browser navigated away) — nothing to clean up.
            }
        }

        GC.SuppressFinalize(this);
    }
}
