// SPDX-License-Identifier: Apache-2.0
//! Upload Processing — runs through the per-photo step list. Dummy timer
//! advances the progress bar.

use leptos::prelude::*;
use leptos_router::hooks::use_navigate;

use crate::state::AppState;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;

const STEPS: &[(&str, &str)] = &[
    (
        "Checking photo information",
        "We look at what metadata each photo carries.",
    ),
    (
        "Removing private information",
        "We strip GPS, device identifiers, and original filenames.",
    ),
    (
        "Preparing display size",
        "We resize for fast loading on phones and tablets.",
    ),
    (
        "Saving in efficient format",
        "We convert to WebP/AVIF to save space and bandwidth.",
    ),
    (
        "Uploading safely",
        "We upload directly to private storage with a one-time signed URL.",
    ),
    (
        "Adding to your album",
        "We record the photo in your library.",
    ),
];

#[component]
pub fn UploadProcessingPage() -> impl IntoView {
    let st = AppState::get();
    let upload = st.upload;
    let total = upload.with(|u| u.selected_count.max(1));
    let navigate = use_navigate();

    let step_idx = RwSignal::new(0_usize);
    let percent = RwSignal::new(2_u32);

    // Animate the progress bar over ~6s.
    Effect::new(move |_| {
        let cb = Closure::wrap(Box::new(move || {
            percent.update(|p| {
                if *p < 100 {
                    *p = (*p + 7).min(100);
                }
            });
            step_idx.update(|i| {
                let target_step = ((percent.get_untracked() as usize) * STEPS.len()) / 101;
                *i = target_step.min(STEPS.len() - 1);
            });
        }) as Box<dyn FnMut()>);

        if let Some(w) = web_sys::window() {
            let _ = w.set_interval_with_callback_and_timeout_and_arguments_0(
                cb.as_ref().unchecked_ref(),
                380,
            );
        }
        cb.forget();
    });

    // When percent reaches 100, allow advancing
    let navigate_complete = navigate.clone();
    let ready = move || percent.get() >= 100;
    let advance = move |_| {
        navigate_complete("/upload/complete", Default::default());
    };

    view! {
        <header class="screen-head">
            <div class="screen-head__eyebrow">"Step 3 of 3 — on your device"</div>
            <h1 class="screen-head__title">"Preparing your photos."</h1>
            <p class="screen-head__lead">
                "Each step happens locally first. Photos only travel to storage after privacy cleaning is complete."
            </p>
        </header>

        <div class="card" style="margin-bottom: 1.5rem;">
            <div class="row-between" style="margin-bottom: 0.5rem;">
                <strong>{move || format!("Processing {} photos", total)}</strong>
                <span class="text-mono text-sm text-mute">
                    {move || format!("{}%", percent.get())}
                </span>
            </div>
            <div class="progress" role="progressbar"
                 aria-valuemin="0" aria-valuemax="100"
                 attr:aria-valuenow=move || percent.get().to_string()>
                <div class="progress__bar" style:width=move || format!("{}%", percent.get())></div>
            </div>
        </div>

        // Step list
        <div class="step-list" aria-live="polite">
            {(0..STEPS.len()).map(|i| {
                let (label, hint) = STEPS[i];
                view! {
                    <div
                        class="step-item"
                        class:step-item--done=move || { step_idx.get() > i }
                        class:step-item--active=move || step_idx.get() == i
                    >
                        <span class="step-item__dot">
                            {move || if step_idx.get() > i { "✓".to_string() } else { (i + 1).to_string() }}
                        </span>
                        <div>
                            <div class="step-item__label">{label}</div>
                            <div class="step-item__hint">{hint}</div>
                        </div>
                        <span class="text-mono text-xs text-mute">
                            {move || if step_idx.get() > i { "Done" } else if step_idx.get() == i { "Working…" } else { "Waiting" }}
                        </span>
                    </div>
                }
            }).collect::<Vec<_>>()}
        </div>

        <div class="action-bar">
            <a class="btn btn--ghost" href="/upload/privacy">"Cancel"</a>
            <button class="btn" disabled=move || !ready() on:click=advance>
                {move || if ready() { "Continue" } else { "Working…" }}
            </button>
        </div>
    }
}
