### A Pluto.jl notebook ###
# v1.0.0

using Markdown
using InteractiveUtils

# ╔═╡ 8a13b3b2-faf6-4f7c-b53b-7d5a7b6f5a8a
begin
    import Pkg
    Pkg.activate(joinpath(@__DIR__, ".."))
    using CoupledDipole
    using CairoMakie
    using Rotations
    using DataFrames
    using StaticArrays
end

# ╔═╡ 7f8e5b1b-6b52-4c8d-9b84-b3528bc9d728
md"""
# Planar-interface dye dimers (prototype)

This notebook mirrors the sphere-coupling workflows, but for a **planar substrate**
using the current Phase-10 prototype.

Focus:
- fixed incidence at **45°**,
- two orthogonal polarisations,
- dipoles at **0.5 nm** above the plane,
- several dimer orientation cases,
- inter-dipole separation sweep,
- differential absorption `Δσ_abs = σ_abs(pol1) - σ_abs(pol2)`.

The half-space backend is still prototype quality, but this notebook is useful
to explore qualitative trends and sensitivity to geometry.
"""

# ╔═╡ d40e5983-6654-4f5d-8774-b7d6a6be3c5a
begin
    wavelengths = collect(400.0:4.0:900.0)
    alpha_nileblue(λ) = alpha_lorentzmolecule(λ; α_∞=9.6e-39, α_k=7.5e-38, λ_k=635.0, µ_k=8000)
    mat = Material(wavelengths, Dict("NileBlue" => alpha_nileblue, "medium" => (_ -> 1.33)))

    incidence = [RotZYZ(0.0, π / 4, 0.0)] # fixed 45° tilt
    height_nm = 0.5
    separations_nm = [0.8, 1.2, 1.6, 2.0]

    cases = [
        :head_to_tail_parallel,
        :head_to_tail_perpendicular,
        :side_by_side_parallel,
        :side_by_side_perpendicular,
    ]

    # Gold substrate model (wavelength-dispersive via ε_Au(λ)).
    # state_metal(λ) = HalfSpaceOpticalState(λ, 1.33 + 0im, 1.5 + 0im)
    state_metal(λ) = 1.5
    state_equal = HalfSpaceOpticalState(600.0, 1.33 + 0im, 1.33 + 0im)
end

# ╔═╡ 0d311556-7ca6-4642-aaec-fba9c97e4ad0
begin
    function _to_halfspace_state(spec, λ; n_upper=1.33 + 0im)
        if spec isa HalfSpaceOpticalState
            return spec
        elseif spec isa Function
            val = spec(λ)
            if val isa HalfSpaceOpticalState
                return val
            elseif val isa Number
                return HalfSpaceOpticalState(λ, n_upper, ComplexF64(val))
            else
                throw(ArgumentError("half-space state function must return HalfSpaceOpticalState or Number, got $(typeof(val))"))
            end
        elseif spec isa Number
            return HalfSpaceOpticalState(λ, n_upper, ComplexF64(spec))
        else
            throw(ArgumentError("half-space state must be HalfSpaceOpticalState, Number, or Function, got $(typeof(spec))"))
        end
    end

    function dimer_cluster(case::Symbol, d_nm::Real; z_nm::Real=5.5)
        if case == :head_to_tail_parallel
            positions = [SVector(0.0, -d_nm / 2, z_nm), SVector(0.0, d_nm / 2, z_nm)]
            sizes = [SVector(0.0, 1.0, 0.0), SVector(0.0, 1.0, 0.0)] # dipole axis parallel to plane
        elseif case == :head_to_tail_perpendicular
            positions = [SVector(0.0, -d_nm / 2, z_nm), SVector(0.0, d_nm / 2, z_nm)]
            sizes = [SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, 1.0)] # dipole axis normal to plane
        elseif case == :side_by_side_parallel
            positions = [SVector(-d_nm / 2, 0.0, z_nm), SVector(d_nm / 2, 0.0, z_nm)]
            sizes = [SVector(0.0, 1.0, 0.0), SVector(0.0, 1.0, 0.0)]
        elseif case == :side_by_side_perpendicular
            positions = [SVector(-d_nm / 2, 0.0, z_nm), SVector(d_nm / 2, 0.0, z_nm)]
            sizes = [SVector(0.0, 0.0, 1.0), SVector(0.0, 0.0, 1.0)]
        else
            throw(ArgumentError("unknown case $(repr(case))"))
        end

        rotations = [one(QuatRotation{Float64}), one(QuatRotation{Float64})]
        materials = ["NileBlue", "NileBlue"]
        types = [PointDipole(), PointDipole()]
        return Cluster(positions, rotations, sizes, materials, types)
    end

    function _material_single_wavelength(mat::Material, λ::Real)
        Material([λ], mat.media)
    end

    function _run_halfspace_channels(cl, mat::Material, incidence, state; reflected_self=true, N_sca=36)
        if state isa Function || state isa Number
            rows = DataFrame[]
            for λ in mat.wavelengths
                mat1 = _material_single_wavelength(mat, λ)
                out1 = spectrum_dispersion_halfspace_channels_prototype(
                    cl,
                    mat1,
                    incidence;
                    N_sca=N_sca,
                    method="direct",
                    halfspace_state=_to_halfspace_state(state, λ),
                    halfspace_reflected_self=reflected_self,
                    halfspace_rtol=1e-6,
                    halfspace_atol=1e-10,
                )
                x = out1.cross_sections
                ch = out1.channels
                push!(
                    rows,
                    DataFrame(
                        wavelength=[λ],
                        cabs1=[x.absorption[1, 1]],
                        cabs2=[x.absorption[1, 2]],
                        dabs=[x.absorption[1, 1] - x.absorption[1, 2]],
                        loss1=[ch.substrate_loss_estimate[1, 1]],
                        loss2=[ch.substrate_loss_estimate[1, 2]],
                    ),
                )
            end
            return reduce(vcat, rows)
        end

        out = spectrum_dispersion_halfspace_channels_prototype(
            cl,
            mat,
            incidence;
            N_sca=N_sca,
            method="direct",
            halfspace_state=_to_halfspace_state(state, mat.wavelengths[1]),
            halfspace_reflected_self=reflected_self,
            halfspace_rtol=1e-6,
            halfspace_atol=1e-10,
        )
        x = out.cross_sections
        ch = out.channels
        return DataFrame(
            wavelength=mat.wavelengths,
            cabs1=x.absorption[:, 1],
            cabs2=x.absorption[:, 2],
            dabs=x.absorption[:, 1] .- x.absorption[:, 2],
            loss1=ch.substrate_loss_estimate[:, 1],
            loss2=ch.substrate_loss_estimate[:, 2],
        )
    end

    function run_case(case::Symbol, d_nm::Real, state; reflected_self=true, N_sca=36)
        cl = dimer_cluster(case, d_nm; z_nm=height_nm)
        tab = _run_halfspace_channels(cl, mat, incidence, state; reflected_self=reflected_self, N_sca=N_sca)
        cabs_mean = 0.5 .* (tab.cabs1 .+ tab.cabs2)
        return DataFrame(
            wavelength=tab.wavelength,
            d=d_nm,
            case=String(case),
            cabs_mean=cabs_mean,
            dabs=tab.dabs,
            loss_pol1=tab.loss1,
            loss_pol2=tab.loss2,
            loss_diff=tab.loss1 .- tab.loss2,
        )
    end

    function run_single(state; reflected_self=true, N_sca=36)
        cl = Cluster(
            [SVector(0.0, 0.0, height_nm)],
            [one(QuatRotation{Float64})],
            [SVector(0.0, 1.0, 0.0)],
            ["NileBlue"],
            [PointDipole()],
        )
        tab = _run_halfspace_channels(cl, mat, incidence, state; reflected_self=reflected_self, N_sca=N_sca)
        DataFrame(
            wavelength=tab.wavelength,
            cabs_mean=0.5 .* (tab.cabs1 .+ tab.cabs2),
            dabs=tab.dabs,
        )
    end
end

# ╔═╡ 73d93bf0-926d-45e3-8d74-86dc9209ac5f
begin
    # Full sweep: 4 orientation cases × separations
    sweep = reduce(vcat, [run_case(c, d, state_metal) for c in cases for d in separations_nm])
    @assert nrow(sweep) == length(cases) * length(separations_nm) * length(wavelengths)
end

# ╔═╡ 1573412d-2265-41f9-a447-cd48d4f02771
let
    fig = Figure(size=(980, 760))
    gl = fig[1, 1] = GridLayout()

    panel_cases = cases
    for (idx, case) in enumerate(panel_cases)
        i = Int(ceil(idx / 2))
        j = idx % 2 == 1 ? 1 : 2
        ax = Axis(gl[i, j], title=String(case), xlabel="Wavelength / nm", ylabel="Δσ_abs / nm²")
        for d in separations_nm
            mask = (sweep.case .== String(case)) .& (sweep.d .== d)
            lines!(ax, sweep.wavelength[mask], sweep.dabs[mask], label="d=$(d) nm")
        end
        axislegend(ax; position=:rt)
    end
    fig
end

# ╔═╡ 5b291475-c0d8-47d5-8a42-997050715f7c
md"""
### Quick single-case controls

Edit these two values and re-run dependent cells:
- `selected_case`
- `selected_d_nm`
"""

# ╔═╡ 5d724ccc-58fa-4196-99d3-f9d6a9d76656
begin
    selected_case = :side_by_side_perpendicular
    selected_d_nm = 0.8

    dimer_gold = run_case(selected_case, selected_d_nm, state_metal)
    dimer_free = run_case(selected_case, selected_d_nm, state_equal)
    single_gold = run_single(state_metal)
    single_free = run_single(state_equal)

    # "substrate-only" baseline in the current dipole-scatterer model:
    # with no dyes there are no dipole moments, hence zero absorption signal.
    substrate_only_free = zeros(length(wavelengths))
    substrate_only_gold = zeros(length(wavelengths))

    # Cross-sections returned by the high-level wrappers are already normalized
    # per dipole (1/N_dip), so no extra "/2" is needed for dimer-vs-single
    # comparisons in this notebook.
    diffabs_free = dimer_free.cabs_mean .- substrate_only_free
    diffabs_gold = dimer_gold.cabs_mean .- substrate_only_gold

    Δsingle = single_gold.cabs_mean .- single_free.cabs_mean
    Δdimer = dimer_gold.cabs_mean .- dimer_free.cabs_mean
    max_abs_Δsingle = maximum(abs.(Δsingle))
    max_abs_Δdimer = maximum(abs.(Δdimer))
end

# ╔═╡ 911813c5-d4ec-4958-9060-84e2d3e51cbf
let
    fig = Figure(size=(920, 760))

    ax_top = Axis(
        fig[1, 1],
        xlabel="Wavelength / nm",
        ylabel="⟨σ_abs⟩ / nm²",
        title="Absorption spectrum: single dye vs dimer/2",
    )
    lines!(ax_top, single_free.wavelength, single_free.cabs_mean, label="single (no substrate)", linestyle=:dash)
    lines!(ax_top, dimer_free.wavelength, dimer_free.cabs_mean, label="dimer/2 (no substrate)", linestyle=:dashdot)
    lines!(ax_top, single_gold.wavelength, single_gold.cabs_mean, label="single (gold substrate)")
    lines!(ax_top, dimer_gold.wavelength, dimer_gold.cabs_mean, label="dimer/2 (gold substrate)")
    axislegend(ax_top; position=:rt)

    ax_bottom = Axis(
        fig[2, 1],
        xlabel="Wavelength / nm",
        ylabel="σ_abs(dyes on substrate) - σ_abs(substrate only) / nm²",
        title="Differential absorption (definition requested)",
    )
    lines!(ax_bottom, dimer_free.wavelength, diffabs_free, label="no substrate", linestyle=:dash)
    lines!(ax_bottom, dimer_gold.wavelength, diffabs_gold, label="gold substrate")
    axislegend(ax_bottom; position=:rt)

    fig
end

# ╔═╡ a6c89d9c-7b9b-4ab7-b2af-3ca17ab2f5dc
md"""
Diagnostic magnitude check (selected case):
- `max |Δ single| = $(round(max_abs_Δsingle, sigdigits=4)) nm²`
- `max |Δ dimer| = $(round(max_abs_Δdimer, sigdigits=4)) nm²`

If both values are near zero after rerunning all cells, your session likely
did not pick up the updated package code yet (restart Pluto kernel and rerun).
"""

# ╔═╡ 71f89f72-e84a-4777-a11a-f13da2e9af10
begin
    # Example of tabular export for plotting/reporting outside Pluto
    # Use a concrete half-space state in this export cell for compatibility
    # with Pluto sessions that may have an older CoupledDipole method table.
    state_export = _to_halfspace_state(state_metal(600.0), 600.0)
    chdf = channel_spectra_df(
        spectrum_dispersion_halfspace_channels_prototype(
            dimer_cluster(selected_case, selected_d_nm; z_nm=height_nm),
            mat,
            incidence;
            N_sca=36,
            method="direct",
            halfspace_state=state_export,
            halfspace_reflected_self=true,
        ).channels,
        wavelengths,
    )
    first(chdf, 8)
end

# ╔═╡ 7b53c71e-267d-4e17-8dd5-0ce24f9887a2
md"""
### Notes

- This notebook uses the current planar-interface **prototype** pipeline.
- The gold substrate model is wavelength-dispersive (`ε_Au(λ)`) in this version.
- In this dipole-scatterer model, a strict "substrate-only" run has zero signal
  (no dipoles to absorb), so the differential-absorption baseline is zero.
- Physically complete total absorption should include both dye absorption and
  dissipation inside the substrate (from incident + dipole-scattered fields in
  the substrate volume), which is not yet implemented in this prototype.
- The reflected-kernel model here includes a fuller Weyl/projector tensor
  assembly and improved near-interface high-`kρ` support, but still requires
  benchmark validation before quantitative use.
- For quantitative publication-grade comparisons, increase `N_sca` and perform
  explicit convergence sweeps against the same observables.
"""

# ╔═╡ Cell order:
# ╠═8a13b3b2-faf6-4f7c-b53b-7d5a7b6f5a8a
# ╟─7f8e5b1b-6b52-4c8d-9b84-b3528bc9d728
# ╠═d40e5983-6654-4f5d-8774-b7d6a6be3c5a
# ╠═0d311556-7ca6-4642-aaec-fba9c97e4ad0
# ╠═73d93bf0-926d-45e3-8d74-86dc9209ac5f
# ╠═1573412d-2265-41f9-a447-cd48d4f02771
# ╟─5b291475-c0d8-47d5-8a42-997050715f7c
# ╠═5d724ccc-58fa-4196-99d3-f9d6a9d76656
# ╠═911813c5-d4ec-4958-9060-84e2d3e51cbf
# ╟─a6c89d9c-7b9b-4ab7-b2af-3ca17ab2f5dc
# ╠═71f89f72-e84a-4777-a11a-f13da2e9af10
# ╟─7b53c71e-267d-4e17-8dd5-0ce24f9887a2
