// SPDX-License-Identifier: Apache-2.0
//! Photo Viewer — full-screen single photo view with prev/next navigation.

use leptos::ev::KeyboardEvent;
use leptos::prelude::*;
use leptos_router::hooks::{use_navigate, use_params_map};

use crate::components::icons::{IconChevronLeft, IconChevronRight, IconClose, IconInfo};
use crate::state::AppState;

#[component]
pub fn PhotoViewerPage() -> impl IntoView {
    let params = use_params_map();
    let photo_id = Memo::new(move |_| params.with(|p| p.get("photo_id").unwrap_or_default()));
    let navigate = use_navigate();

    let st = AppState::get();
    let photos = st.photos;

    let current_idx = Memo::new(move |_| {
        let id = photo_id.get();
        photos.with(|all| all.iter().position(|p| p.id == id))
    });

    let current = Memo::new(move |_| {
        current_idx
            .get()
            .and_then(|i| photos.with(|all| all.get(i).cloned()))
    });

    let total = move || photos.with(Vec::len);

    let nav_to_offset = {
        let navigate = navigate.clone();
        move |offset: i32| {
            if let Some(i) = current_idx.get() {
                let total_count = total();
                if total_count == 0 {
                    return;
                }
                let new_i = (i as i32 + offset).rem_euclid(total_count as i32) as usize;
                if let Some(next) = photos.with(|all| all.get(new_i).cloned()) {
                    navigate(&format!("/photos/{}", next.id), Default::default());
                }
            }
        }
    };

    let nav_close = {
        let navigate = navigate.clone();
        move |_| {
            navigate("/albums", Default::default());
        }
    };

    let on_key = {
        let nav = nav_to_offset.clone();
        let close = nav_close.clone();
        move |ev: KeyboardEvent| match ev.key().as_str() {
            "ArrowLeft" => nav(-1),
            "ArrowRight" => nav(1),
            "Escape" => close(web_sys::MouseEvent::new("click").unwrap()),
            _ => {}
        }
    };

    let info_open = RwSignal::new(false);
    let nav_prev = nav_to_offset.clone();
    let nav_next = nav_to_offset.clone();

    view! {
        <div class="viewer" tabindex="-1" on:keydown=on_key autofocus>
            <div class="viewer__top">
                <button class="viewer__close" on:click=nav_close.clone() aria-label="Close viewer">
                    <IconClose size=16 />
                    " Close"
                </button>
                <div style="margin-left: auto; opacity: 0.85; font-size: 0.9rem;">
                    {move || current_idx.get().map(|i| format!("{} of {}", i + 1, total())).unwrap_or_default()}
                </div>
                <button class="viewer__close" on:click=move |_| info_open.update(|v| *v = !*v) aria-label="Privacy details">
                    <IconInfo size=16 />
                    " Privacy"
                </button>
            </div>

            <div class="viewer__stage">
                {move || current.get().map_or_else(
                    || view! {
                        <div style="color: #c2bbac;">"This photo is not here."</div>
                    }.into_any(),
                    |p| {
                        let style = format!("--cell-a: {}; --cell-b: {};", p.palette.0, p.palette.1);
                        view! { <div class="viewer__photo" style=style aria-label=format!("Photo from {}", p.uploaded_at)></div> }.into_any()
                    }
                )}
                <button class="viewer__nav viewer__nav--prev" on:click=move |_| nav_prev(-1) aria-label="Previous photo">
                    <IconChevronLeft size=22 />
                </button>
                <button class="viewer__nav viewer__nav--next" on:click=move |_| nav_next(1) aria-label="Next photo">
                    <IconChevronRight size=22 />
                </button>
            </div>

            <div class="viewer__bottom">
                {move || current.get().map(|p| {
                    // Plain-prose bottom bar: "Taken Aug 12 · Standard cleaning applied"
                    let date_phrase = p.captured_at.clone()
                        .map(|d| format!("Taken {d}"))
                        .unwrap_or_else(|| "Date removed".to_string());
                    let cleaning_phrase = match p.cleaning_level.as_str() {
                        "privacy"  => "Date, location, and device info removed",
                        "detailed" => "Date and location kept · device info removed",
                        _          => "Date kept · location and device info removed",
                    };
                    view! {
                        <div class="row" style="gap: 1.5rem; flex-wrap: wrap; font-size: 0.9rem; color: var(--ink-3);">
                            <span>{date_phrase}</span>
                            <span>"·"</span>
                            <span>{cleaning_phrase}</span>
                            <span style="margin-left: auto; font-size: 0.8rem;">"← → to navigate · Esc to close"</span>
                        </div>
                    }
                })}
            </div>

            <Show when=move || info_open.get() fallback=|| ()>
                <div class="modal-backdrop" on:click=move |_| info_open.set(false)>
                    <div class="modal" on:click=|ev| ev.stop_propagation()>
                        <h2 class="modal__title">"What happened to this photo"</h2>
                        {move || current.get().map(|p| {
                            // Derive human-readable sentences from the photo's actual fields
                            let date_line = match &p.captured_at {
                                Some(d) => format!("The date it was taken — {d} — was kept."),
                                None    => "The date it was taken was removed before upload.".to_string(),
                            };
                            let location_line = if p.has_location {
                                "Location information was kept (Detailed record level was selected)."
                            } else {
                                "Location information was removed before upload. \
                                 The place where this photo was taken is not stored."
                            };
                            let device_line = if p.has_device_info {
                                "Device information was kept."
                            } else {
                                "Device identifiers — camera serial number, model — \
                                 were removed before upload."
                            };
                            let filename_line = "The original filename was replaced with a \
                                                 random identifier. The original name is not stored.";
                            view! {
                                <div class="prose-list">
                                    <div class="prose-item">
                                        <span class="prose-item__dot" aria-hidden="true"></span>
                                        {date_line}
                                    </div>
                                    <div class="prose-item">
                                        <span class="prose-item__dot" aria-hidden="true"></span>
                                        {location_line}
                                    </div>
                                    <div class="prose-item">
                                        <span class="prose-item__dot" aria-hidden="true"></span>
                                        {device_line}
                                    </div>
                                    <div class="prose-item">
                                        <span class="prose-item__dot" aria-hidden="true"></span>
                                        {filename_line}
                                    </div>
                                </div>
                                <p class="text-mute" style="margin-top: 1rem; font-size: 0.88rem;">
                                    "All of the above happened on your device, before the photo
                                     left your browser. hejpics never received the removed data."
                                </p>
                            }
                        })}
                        <div class="action-bar">
                            <button class="btn" on:click=move |_| info_open.set(false)>"Close"</button>
                        </div>
                    </div>
                </div>
            </Show>
        </div>
    }
}
