//! Inventory popup component.

use leptos::prelude::*;
use leptos::reactive::owner::LocalStorage;
use uuid::Uuid;

use chattyness_db::models::{InventoryItem, PropAcquisitionInfo};
#[cfg(feature = "hydrate")]
use chattyness_db::ws_messages::ClientMessage;

use super::modals::{ConfirmModal, GuestLockedOverlay, Modal};
use super::tabs::{Tab, TabBar};
use super::ws_client::WsSender;

/// Inventory popup component.
///
/// Shows a tabbed interface with:
/// - My Inventory: User-owned props with drop functionality
/// - Server: Public server-wide props
/// - Realm: Public realm-specific props
///
/// Props:
/// - `open`: Signal controlling visibility
/// - `on_close`: Callback when popup should close
/// - `ws_sender`: WebSocket sender for dropping props
/// - `realm_slug`: Current realm slug for fetching realm props
/// - `is_guest`: Whether the current user is a guest (shows locked overlay)
#[component]
pub fn InventoryPopup(
    #[prop(into)] open: Signal<bool>,
    on_close: Callback<()>,
    ws_sender: StoredValue<Option<WsSender>, LocalStorage>,
    #[prop(into)] realm_slug: Signal<String>,
    /// Whether the current user is a guest. Guests see a locked overlay.
    #[prop(optional, into)]
    is_guest: Option<Signal<bool>>,
) -> impl IntoView {
    let is_guest = is_guest.unwrap_or_else(|| Signal::derive(|| false));
    // Tab state
    let (active_tab, set_active_tab) = signal("my_inventory");

    // My Inventory state
    let (items, set_items) = signal(Vec::<InventoryItem>::new());
    let (loading, set_loading) = signal(false);
    let (error, set_error) = signal(Option::<String>::None);
    let (selected_item, set_selected_item) = signal(Option::<Uuid>::None);
    let (dropping, set_dropping) = signal(false);
    let (deleting, set_deleting) = signal(false);
    let (delete_confirm_item, set_delete_confirm_item) = signal(Option::<(Uuid, String)>::None);

    // Server props state (with acquisition info for authenticated users)
    let (server_props, set_server_props) = signal(Vec::<PropAcquisitionInfo>::new());
    let (server_loading, set_server_loading) = signal(false);
    let (server_error, set_server_error) = signal(Option::<String>::None);

    // Realm props state (with acquisition info for authenticated users)
    let (realm_props, set_realm_props) = signal(Vec::<PropAcquisitionInfo>::new());
    let (realm_loading, set_realm_loading) = signal(false);
    let (realm_error, set_realm_error) = signal(Option::<String>::None);

    // Track if tabs have been loaded (to avoid re-fetching)
    let (my_inventory_loaded, set_my_inventory_loaded) = signal(false);
    let (server_loaded, set_server_loaded) = signal(false);
    let (realm_loaded, set_realm_loaded) = signal(false);

    // Trigger to refresh my inventory after acquisition
    let (inventory_refresh_trigger, set_inventory_refresh_trigger) = signal(0u32);

    // Fetch my inventory when popup opens or tab is selected
    #[cfg(feature = "hydrate")]
    {
        use gloo_net::http::Request;
        use leptos::task::spawn_local;

        Effect::new(move |_| {
            // Track refresh trigger to refetch after acquisition
            let _refresh = inventory_refresh_trigger.get();

            if !open.get() {
                // Reset state when closing
                set_selected_item.set(None);
                set_my_inventory_loaded.set(false);
                set_server_loaded.set(false);
                set_realm_loaded.set(false);
                return;
            }

            // Only fetch if on my_inventory tab and not already loaded
            if active_tab.get() != "my_inventory" || my_inventory_loaded.get() {
                return;
            }

            set_loading.set(true);
            set_error.set(None);

            spawn_local(async move {
                let response = Request::get("/api/user/me/inventory").send().await;
                match response {
                    Ok(resp) if resp.ok() => {
                        if let Ok(data) = resp
                            .json::<chattyness_db::models::InventoryResponse>()
                            .await
                        {
                            set_items.set(data.items);
                            set_my_inventory_loaded.set(true);
                        } else {
                            set_error.set(Some("Failed to parse inventory data".to_string()));
                        }
                    }
                    Ok(resp) => {
                        set_error.set(Some(format!("Failed to load inventory: {}", resp.status())));
                    }
                    Err(e) => {
                        set_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_loading.set(false);
            });
        });
    }

    // Fetch server props when server tab is selected
    // Uses status endpoint if authenticated (non-guest), otherwise basic endpoint
    #[cfg(feature = "hydrate")]
    {
        use gloo_net::http::Request;
        use leptos::task::spawn_local;

        Effect::new(move |_| {
            if !open.get() || active_tab.get() != "server" || server_loaded.get() {
                return;
            }

            set_server_loading.set(true);
            set_server_error.set(None);

            spawn_local(async move {
                // Single endpoint returns enriched data if authenticated
                let response = Request::get("/api/server/inventory").send().await;
                match response {
                    Ok(resp) if resp.ok() => {
                        if let Ok(data) = resp
                            .json::<chattyness_db::models::PropAcquisitionListResponse>()
                            .await
                        {
                            set_server_props.set(data.props);
                            set_server_loaded.set(true);
                        } else {
                            set_server_error
                                .set(Some("Failed to parse server props".to_string()));
                        }
                    }
                    Ok(resp) => {
                        set_server_error.set(Some(format!(
                            "Failed to load server props: {}",
                            resp.status()
                        )));
                    }
                    Err(e) => {
                        set_server_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_server_loading.set(false);
            });
        });
    }

    // Fetch realm props when realm tab is selected
    #[cfg(feature = "hydrate")]
    {
        use gloo_net::http::Request;
        use leptos::task::spawn_local;

        Effect::new(move |_| {
            if !open.get() || active_tab.get() != "realm" || realm_loaded.get() {
                return;
            }

            let slug = realm_slug.get();
            if slug.is_empty() {
                set_realm_error.set(Some("No realm selected".to_string()));
                return;
            }

            set_realm_loading.set(true);
            set_realm_error.set(None);

            spawn_local(async move {
                // Single endpoint returns enriched data if authenticated
                let endpoint = format!("/api/realms/{}/inventory", slug);
                let response = Request::get(&endpoint).send().await;
                match response {
                    Ok(resp) if resp.ok() => {
                        if let Ok(data) = resp
                            .json::<chattyness_db::models::PropAcquisitionListResponse>()
                            .await
                        {
                            set_realm_props.set(data.props);
                            set_realm_loaded.set(true);
                        } else {
                            set_realm_error
                                .set(Some("Failed to parse realm props".to_string()));
                        }
                    }
                    Ok(resp) => {
                        set_realm_error.set(Some(format!(
                            "Failed to load realm props: {}",
                            resp.status()
                        )));
                    }
                    Err(e) => {
                        set_realm_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_realm_loading.set(false);
            });
        });
    }

    // Helper to update ownership status in server/realm props when an item is removed
    let update_prop_ownership = move |item: &InventoryItem| {
        use chattyness_db::models::PropOrigin;

        if let Some(prop_id) = item.prop_id {
            match item.origin {
                PropOrigin::ServerLibrary => {
                    set_server_props.update(|props| {
                        if let Some(prop) = props.iter_mut().find(|p| p.id == prop_id) {
                            prop.user_owns = false;
                        }
                    });
                }
                PropOrigin::RealmLibrary => {
                    set_realm_props.update(|props| {
                        if let Some(prop) = props.iter_mut().find(|p| p.id == prop_id) {
                            prop.user_owns = false;
                        }
                    });
                }
                PropOrigin::UserUpload => {
                    // User uploads don't appear in server/realm catalogs
                }
            }
        }
    };

    // Handle drop action via WebSocket
    #[cfg(feature = "hydrate")]
    let handle_drop = {
        move |item_id: Uuid| {
            set_dropping.set(true);

            // Send drop command via WebSocket
            ws_sender.with_value(|sender| {
                if let Some(send_fn) = sender {
                    send_fn(ClientMessage::DropProp {
                        inventory_item_id: item_id,
                    });
                    // Find item index and update ownership before removing
                    let current_items = items.get();
                    let removed_index = current_items.iter().position(|i| i.id == item_id);
                    if let Some(item) = current_items.iter().find(|i| i.id == item_id).cloned() {
                        update_prop_ownership(&item);
                    }
                    // Optimistically remove from local list
                    set_items.update(|items| {
                        items.retain(|i| i.id != item_id);
                    });
                    // Select the next item (or previous if at end)
                    let updated_items = items.get();
                    if let Some(idx) = removed_index {
                        if !updated_items.is_empty() {
                            let next_idx = idx.min(updated_items.len() - 1);
                            set_selected_item.set(Some(updated_items[next_idx].id));
                        } else {
                            set_selected_item.set(None);
                        }
                    } else {
                        set_selected_item.set(None);
                    }
                } else {
                    set_error.set(Some("Not connected to server".to_string()));
                }
            });

            set_dropping.set(false);
        }
    };

    #[cfg(not(feature = "hydrate"))]
    let handle_drop = |_item_id: Uuid| {};

    // Handle delete action via WebSocket (permanent deletion)
    #[cfg(feature = "hydrate")]
    let handle_delete = {
        move |item_id: Uuid| {
            set_deleting.set(true);
            ws_sender.with_value(|sender| {
                if let Some(send_fn) = sender {
                    send_fn(ClientMessage::DeleteProp {
                        inventory_item_id: item_id,
                    });
                    // Find item index and update ownership before removing
                    let current_items = items.get();
                    let removed_index = current_items.iter().position(|i| i.id == item_id);
                    if let Some(item) = current_items.iter().find(|i| i.id == item_id).cloned() {
                        update_prop_ownership(&item);
                    }
                    // Optimistically remove from local list
                    set_items.update(|items| {
                        items.retain(|i| i.id != item_id);
                    });
                    // Select the next item (or previous if at end)
                    let updated_items = items.get();
                    if let Some(idx) = removed_index {
                        if !updated_items.is_empty() {
                            let next_idx = idx.min(updated_items.len() - 1);
                            set_selected_item.set(Some(updated_items[next_idx].id));
                        } else {
                            set_selected_item.set(None);
                        }
                    } else {
                        set_selected_item.set(None);
                    }
                    set_delete_confirm_item.set(None);
                } else {
                    set_error.set(Some("Not connected to server".to_string()));
                }
            });
            set_deleting.set(false);
        }
    };

    #[cfg(not(feature = "hydrate"))]
    let handle_delete = |_item_id: Uuid| {};

    view! {
        <Modal
            open=open
            on_close=on_close
            title="Inventory"
            title_id="inventory-modal-title"
            max_width="max-w-2xl"
            class="max-h-[80vh] flex flex-col"
        >
            <div class="relative flex-1 flex flex-col">
                // Tab bar
                <TabBar
                    tabs=vec![
                        Tab::new("my_inventory", "My Inventory"),
                        Tab::new("server", "Server"),
                        Tab::new("realm", "Realm"),
                    ]
                    active=Signal::derive(move || active_tab.get())
                    on_select=Callback::new(move |id| set_active_tab.set(id))
                />

                // Tab content
                <div class="flex-1 overflow-y-auto min-h-[300px]">
                    // My Inventory tab
                    <Show when=move || active_tab.get() == "my_inventory">
                        <MyInventoryTab
                            items=items
                            loading=loading
                            error=error
                            selected_item=selected_item
                            set_selected_item=set_selected_item
                            dropping=dropping
                            on_drop=Callback::new(handle_drop)
                            deleting=deleting
                            on_delete_request=Callback::new(move |(id, name)| {
                                set_delete_confirm_item.set(Some((id, name)));
                            })
                            on_delete_immediate=Callback::new(handle_delete)
                        />
                    </Show>

                    // Server tab
                    <Show when=move || active_tab.get() == "server">
                        <AcquisitionPropsTab
                            props=server_props
                            set_props=set_server_props
                            loading=server_loading
                            error=server_error
                            tab_name="Server"
                            empty_message="No public server props available"
                            is_guest=is_guest
                            acquire_endpoint="/api/server/inventory/request"
                            on_acquired=Callback::new(move |_| {
                                // Trigger inventory refresh
                                set_my_inventory_loaded.set(false);
                                set_inventory_refresh_trigger.update(|n| *n += 1);
                            })
                        />
                    </Show>

                    // Realm tab
                    <Show when=move || active_tab.get() == "realm">
                        <AcquisitionPropsTab
                            props=realm_props
                            set_props=set_realm_props
                            loading=realm_loading
                            error=realm_error
                            tab_name="Realm"
                            empty_message="No public realm props available"
                            is_guest=is_guest
                            acquire_endpoint_is_realm=true
                            realm_slug=realm_slug
                            on_acquired=Callback::new(move |_| {
                                // Trigger inventory refresh
                                set_my_inventory_loaded.set(false);
                                set_inventory_refresh_trigger.update(|n| *n += 1);
                            })
                        />
                    </Show>
                </div>

                // Guest locked overlay
                <Show when=move || is_guest.get()>
                    <GuestLockedOverlay />
                </Show>

                // Delete confirmation modal
                {move || {
                    delete_confirm_item.get().map(|(item_id, item_name)| {
                        view! {
                            <ConfirmModal
                                open=Signal::derive(|| true)
                                title="Delete Prop?"
                                message=format!("Permanently delete '{}'? This cannot be undone.", item_name)
                                confirm_text="Delete"
                                cancel_text="Cancel"
                                destructive=true
                                pending=Signal::derive(move || deleting.get())
                                on_confirm=Callback::new(move |_| handle_delete(item_id))
                                on_cancel=Callback::new(move |_| set_delete_confirm_item.set(None))
                            />
                        }
                    })
                }}
            </div>
        </Modal>
    }
}

/// My Inventory tab content with drop functionality.
#[component]
fn MyInventoryTab(
    #[prop(into)] items: Signal<Vec<InventoryItem>>,
    #[prop(into)] loading: Signal<bool>,
    #[prop(into)] error: Signal<Option<String>>,
    #[prop(into)] selected_item: Signal<Option<Uuid>>,
    set_selected_item: WriteSignal<Option<Uuid>>,
    #[prop(into)] dropping: Signal<bool>,
    #[prop(into)] on_drop: Callback<Uuid>,
    #[prop(into)] deleting: Signal<bool>,
    #[prop(into)] on_delete_request: Callback<(Uuid, String)>,
    /// Callback for immediate delete (Shift+Delete, no confirmation)
    #[prop(into)] on_delete_immediate: Callback<Uuid>,
) -> impl IntoView {
    // NodeRef to maintain focus on container after item removal
    let container_ref = NodeRef::<leptos::html::Div>::new();

    // Refocus container when selected item changes (after drop/delete)
    #[cfg(feature = "hydrate")]
    Effect::new(move |prev_selected: Option<Option<Uuid>>| {
        let current = selected_item.get();
        // If selection changed and we have a new selection, refocus container
        if prev_selected.is_some() && current.is_some() {
            if let Some(el) = container_ref.get() {
                let _ = el.focus();
            }
        }
        current
    });

    // Keyboard shortcut handler
    let handle_keydown = move |ev: leptos::web_sys::KeyboardEvent| {
        // Don't handle if in an input field
        #[cfg(feature = "hydrate")]
        {
            use wasm_bindgen::JsCast;
            if let Some(target) = ev.target() {
                if let Ok(element) = target.dyn_into::<leptos::web_sys::HtmlElement>() {
                    let tag = element.tag_name().to_lowercase();
                    if tag == "input" || tag == "textarea" {
                        return;
                    }
                }
            }
        }

        // Get selected item info
        let Some(item_id) = selected_item.get() else { return };
        let Some(item) = items.get().into_iter().find(|i| i.id == item_id) else { return };

        // Only allow actions on droppable items
        if !item.is_droppable {
            return;
        }

        let key = ev.key();
        let shift = ev.shift_key();

        match key.as_str() {
            "d" | "D" => {
                ev.prevent_default();
                on_drop.run(item_id);
            }
            "Delete" => {
                ev.prevent_default();
                if shift {
                    // Shift+Delete: immediate delete without confirmation
                    on_delete_immediate.run(item_id);
                } else {
                    // Delete: delete with confirmation
                    on_delete_request.run((item_id, item.prop_name.clone()));
                }
            }
            _ => {}
        }
    };

    view! {
        <div
            node_ref=container_ref
            tabindex="0"
            on:keydown=handle_keydown
            class="outline-none"
        >
            // Loading state
            <Show when=move || loading.get()>
                <div class="flex items-center justify-center py-12">
                    <p class="text-gray-400">"Loading inventory..."</p>
                </div>
            </Show>

            // Error state
            <Show when=move || error.get().is_some()>
                <div class="bg-red-900/20 border border-red-600 rounded p-4 mb-4">
                    <p class="text-red-400">{move || error.get().unwrap_or_default()}</p>
                </div>
            </Show>

            // Empty state
            <Show when=move || !loading.get() && error.get().is_none() && items.get().is_empty()>
            <div class="flex flex-col items-center justify-center py-12 text-center">
                <div class="w-16 h-16 rounded-full bg-gray-700/50 flex items-center justify-center mb-4">
                    <svg class="w-8 h-8 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                    </svg>
                </div>
                <p class="text-gray-400">"Your inventory is empty"</p>
                <p class="text-gray-500 text-sm mt-1">"Collect props to see them here"</p>
            </div>
        </Show>

        // Grid of items
        <Show when=move || !loading.get() && !items.get().is_empty()>
            <div>
                <div
                    class="grid grid-cols-4 sm:grid-cols-6 gap-2"
                    role="listbox"
                    aria-label="Inventory items"
                >
                    <For
                        each=move || items.get()
                        key=|item| item.id
                        children=move |item: InventoryItem| {
                            let item_id = item.id;
                            let item_name = item.prop_name.clone();
                            let is_selected = move || selected_item.get() == Some(item_id);
                            let asset_path = if item.prop_asset_path.starts_with('/') {
                                item.prop_asset_path.clone()
                            } else {
                                format!("/static/{}", item.prop_asset_path)
                            };

                            view! {
                                <button
                                    type="button"
                                    class=move || format!(
                                        "aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 {}",
                                        if is_selected() {
                                            "border-blue-500 bg-blue-900/30"
                                        } else {
                                            "border-gray-600 hover:border-gray-500 bg-gray-700/50"
                                        }
                                    )
                                    on:click=move |_| {
                                        set_selected_item.set(Some(item_id));
                                    }
                                    role="option"
                                    aria-selected=is_selected
                                    aria-label=item_name
                                >
                                    <img
                                        src=asset_path
                                        alt=""
                                        class="w-full h-full object-contain"
                                    />
                                </button>
                            }
                        }
                    />
                </div>

                // Selected item details and actions
                {move || {
                    let item_id = selected_item.get()?;
                    let item = items.get().into_iter().find(|i| i.id == item_id)?;
                    let on_drop = on_drop.clone();
                    let on_delete_request = on_delete_request.clone();
                    let is_dropping = dropping.get();
                    let is_deleting = deleting.get();
                    let is_droppable = item.is_droppable;
                    let item_name = item.prop_name.clone();

                    Some(view! {
                        <div class="mt-4 pt-4 border-t border-gray-700">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3 class="text-white font-medium">{item.prop_name.clone()}</h3>
                                    <p class="text-gray-400 text-sm">
                                        {if item.is_transferable { "Transferable" } else { "Not transferable" }}
                                        {if item.is_portable { " \u{2022} Portable" } else { "" }}
                                        {if is_droppable { " \u{2022} Droppable" } else { " \u{2022} Essential" }}
                                    </p>
                                </div>
                                <div class="flex gap-2">
                                    // Drop button - disabled for non-droppable (essential) props
                                    <button
                                        type="button"
                                        class=if is_droppable {
                                            "px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50"
                                        } else {
                                            "px-4 py-2 bg-gray-600 text-gray-400 rounded-lg cursor-not-allowed"
                                        }
                                        on:click=move |_| {
                                            if is_droppable {
                                                on_drop.run(item_id);
                                            }
                                        }
                                        disabled=is_dropping || !is_droppable
                                        title=if is_droppable { "Drop prop to scene canvas" } else { "Essential prop cannot be dropped" }
                                    >
                                        {if is_dropping {
                                            view! { "Dropping..." }.into_any()
                                        } else {
                                            view! { <span><u>"D"</u>"rop"</span> }.into_any()
                                        }}
                                    </button>
                                    // Delete button - only shown for droppable props
                                    <Show when=move || is_droppable>
                                        <button
                                            type="button"
                                            class="px-4 py-2 bg-red-800 hover:bg-red-900 text-white rounded-lg transition-colors disabled:opacity-50"
                                            on:click={
                                                let name = item_name.clone();
                                                move |_| on_delete_request.run((item_id, name.clone()))
                                            }
                                            disabled=is_dropping || is_deleting
                                            title="Permanently delete this prop"
                                        >
                                            "Delete"
                                        </button>
                                    </Show>
                                    // Transfer button (disabled for now)
                                    <Show when=move || item.is_transferable>
                                        <button
                                            type="button"
                                            class="px-4 py-2 bg-gray-600 text-gray-400 rounded-lg cursor-not-allowed"
                                            disabled=true
                                            title="Transfer functionality coming soon"
                                        >
                                            "Transfer"
                                        </button>
                                    </Show>
                                </div>
                            </div>
                        </div>
                    })
                }}
            </div>
        </Show>
        </div>
    }
}

/// Acquisition props tab content with acquire functionality.
#[component]
fn AcquisitionPropsTab(
    #[prop(into)] props: Signal<Vec<PropAcquisitionInfo>>,
    set_props: WriteSignal<Vec<PropAcquisitionInfo>>,
    #[prop(into)] loading: Signal<bool>,
    #[prop(into)] error: Signal<Option<String>>,
    tab_name: &'static str,
    empty_message: &'static str,
    #[prop(into)] is_guest: Signal<bool>,
    /// Static endpoint for server props (e.g., "/api/server/inventory/request")
    #[prop(optional)]
    acquire_endpoint: Option<&'static str>,
    /// Whether this is a realm props tab (uses dynamic endpoint with slug)
    #[prop(optional, default = false)]
    acquire_endpoint_is_realm: bool,
    /// Realm slug for realm prop acquisition (required if acquire_endpoint_is_realm is true)
    #[prop(optional, into)]
    realm_slug: Signal<String>,
    #[prop(into)] on_acquired: Callback<()>,
) -> impl IntoView {
    // Selected prop for showing details
    let (selected_prop, set_selected_prop) = signal(Option::<Uuid>::None);
    let (acquiring, set_acquiring) = signal(false);
    let (acquire_error, set_acquire_error) = signal(Option::<String>::None);

    // Handle acquire action
    let acquire_endpoint_opt = acquire_endpoint.map(|s| s.to_string());
    let do_acquire = Callback::new(move |prop_id: Uuid| {
        #[cfg(feature = "hydrate")]
        {
            set_acquiring.set(true);
            set_acquire_error.set(None);

            let endpoint = if acquire_endpoint_is_realm {
                let slug = realm_slug.get();
                if slug.is_empty() {
                    set_acquire_error.set(Some("No realm selected".to_string()));
                    set_acquiring.set(false);
                    return;
                }
                format!("/api/realms/{}/inventory/request", slug)
            } else {
                acquire_endpoint_opt.clone().unwrap_or_default()
            };

            let on_acquired = on_acquired.clone();

            leptos::task::spawn_local(async move {
                use gloo_net::http::Request;

                // Simple body with just prop_id - realm_id comes from URL for realm props
                let body = serde_json::json!({
                    "prop_id": prop_id
                });

                let response = Request::post(&endpoint)
                    .header("Content-Type", "application/json")
                    .body(body.to_string())
                    .unwrap()
                    .send()
                    .await;

                match response {
                    Ok(resp) if resp.ok() => {
                        // Find the index of the acquired prop before updating
                        let current_props = props.get();
                        let acquired_index = current_props.iter().position(|p| p.id == prop_id);

                        // Update local state to mark prop as owned (shows green border)
                        set_props.update(|props| {
                            if let Some(prop) = props.iter_mut().find(|p| p.id == prop_id) {
                                prop.user_owns = true;
                            }
                        });

                        // Select the next available (non-owned) prop
                        let updated_props = props.get();
                        if let Some(idx) = acquired_index {
                            // Look for next non-owned prop starting from current position
                            let next_available = updated_props.iter()
                                .skip(idx + 1)
                                .find(|p| !p.user_owns && p.is_available && !(p.is_unique && p.is_claimed))
                                .or_else(|| {
                                    // If none after, look from the beginning
                                    updated_props.iter()
                                        .take(idx)
                                        .find(|p| !p.user_owns && p.is_available && !(p.is_unique && p.is_claimed))
                                });

                            if let Some(next_prop) = next_available {
                                set_selected_prop.set(Some(next_prop.id));
                            }
                            // If no more available props, keep current selection (now shows as owned)
                        }

                        // Notify parent to refresh inventory
                        on_acquired.run(());
                    }
                    Ok(resp) => {
                        // Try to parse error message from response
                        if let Ok(error_json) = resp.json::<serde_json::Value>().await {
                            let error_msg = error_json
                                .get("error")
                                .and_then(|e| e.as_str())
                                .unwrap_or("Unknown error");
                            set_acquire_error.set(Some(error_msg.to_string()));
                        } else {
                            set_acquire_error.set(Some(format!(
                                "Failed to acquire prop: {}",
                                resp.status()
                            )));
                        }
                    }
                    Err(e) => {
                        set_acquire_error.set(Some(format!("Network error: {}", e)));
                    }
                }
                set_acquiring.set(false);
            });
        }
    });

    // Keyboard shortcut handler for Enter to acquire
    let handle_keydown = {
        let do_acquire = do_acquire.clone();
        move |ev: leptos::web_sys::KeyboardEvent| {
            let key = ev.key();
            if key == "Enter" {
                // Get selected prop info
                let Some(prop_id) = selected_prop.get() else { return };
                let Some(prop) = props.get().into_iter().find(|p| p.id == prop_id) else { return };

                // Only acquire if not already owned, not claimed (if unique), available, and not a guest
                if !is_guest.get() && !prop.user_owns && prop.is_available && !(prop.is_unique && prop.is_claimed) {
                    ev.prevent_default();
                    do_acquire.run(prop_id);
                }
            }
        }
    };

    view! {
        <div
            tabindex="0"
            on:keydown=handle_keydown
            class="outline-none"
        >
        // Loading state
        <Show when=move || loading.get()>
            <div class="flex items-center justify-center py-12">
                <p class="text-gray-400">{format!("Loading {} props...", tab_name.to_lowercase())}</p>
            </div>
        </Show>

        // Error state
        <Show when=move || error.get().is_some()>
            <div class="bg-red-900/20 border border-red-600 rounded p-4 mb-4">
                <p class="text-red-400">{move || error.get().unwrap_or_default()}</p>
            </div>
        </Show>

        // Acquire error state
        <Show when=move || acquire_error.get().is_some()>
            <div class="bg-red-900/20 border border-red-600 rounded p-4 mb-4">
                <p class="text-red-400">{move || acquire_error.get().unwrap_or_default()}</p>
            </div>
        </Show>

        // Empty state
        <Show when=move || !loading.get() && error.get().is_none() && props.get().is_empty()>
            <div class="flex flex-col items-center justify-center py-12 text-center">
                <div class="w-16 h-16 rounded-full bg-gray-700/50 flex items-center justify-center mb-4">
                    <svg class="w-8 h-8 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                    </svg>
                </div>
                <p class="text-gray-400">{empty_message}</p>
                <p class="text-gray-500 text-sm mt-1">"Public props will appear here when available"</p>
            </div>
        </Show>

        // Grid of props
        <Show when=move || !loading.get() && !props.get().is_empty()>
            <div>
                <div
                    class="grid grid-cols-4 sm:grid-cols-6 gap-2"
                    role="listbox"
                    aria-label=format!("{} props", tab_name)
                >
                    <For
                        each=move || props.get()
                        key=|prop| prop.id
                        children=move |prop: PropAcquisitionInfo| {
                            let prop_id = prop.id;
                            let prop_name = prop.name.clone();
                            let is_selected = move || selected_prop.get() == Some(prop_id);
                            let asset_path = if prop.asset_path.starts_with('/') {
                                prop.asset_path.clone()
                            } else {
                                format!("/static/{}", prop.asset_path)
                            };

                            // Reactive lookup for ownership status (updates when props signal changes)
                            let user_owns = move || {
                                props.get().iter().find(|p| p.id == prop_id).map(|p| p.user_owns).unwrap_or(false)
                            };
                            let is_claimed = prop.is_claimed;

                            view! {
                                <button
                                    type="button"
                                    class=move || format!(
                                        "aspect-square rounded-lg border-2 transition-all p-1 focus:outline-none focus:ring-2 focus:ring-blue-500 relative overflow-hidden {}",
                                        if is_selected() {
                                            "border-blue-500 bg-blue-900/30"
                                        } else if user_owns() {
                                            "border-green-500/50 bg-green-900/20"
                                        } else if is_claimed {
                                            "border-red-500/50 bg-red-900/20 opacity-50"
                                        } else {
                                            "border-gray-600 hover:border-gray-500 bg-gray-700/50"
                                        }
                                    )
                                    on:click=move |_| {
                                        set_selected_prop.set(Some(prop_id));
                                    }
                                    role="option"
                                    aria-selected=is_selected
                                    aria-label=prop_name
                                >
                                    <img
                                        src=asset_path
                                        alt=""
                                        class="w-full h-full object-contain"
                                    />
                                    // Ownership badge
                                    <Show when=user_owns>
                                        <span class="absolute top-0 right-0 w-3 h-3 bg-green-500 rounded-full transform translate-x-1 -translate-y-1" title="Owned" />
                                    </Show>
                                </button>
                            }
                        }
                    />
                </div>

                // Selected prop details with acquire button
                {move || {
                    let prop_id = selected_prop.get()?;
                    let prop = props.get().into_iter().find(|p| p.id == prop_id)?;
                    let guest = is_guest.get();
                    let is_acquiring = acquiring.get();

                    // Determine button state
                    let (button_text, button_class, button_disabled, button_title) = if guest {
                        ("Sign in to Acquire", "bg-gray-600 text-gray-400 cursor-not-allowed", true, "Guests cannot acquire props")
                    } else if prop.user_owns {
                        ("Already Owned", "bg-green-700 text-white cursor-default", true, "You already own this prop")
                    } else if prop.is_claimed && prop.is_unique {
                        ("Claimed", "bg-red-700 text-white cursor-not-allowed", true, "This unique prop has been claimed by another user")
                    } else if !prop.is_available {
                        ("Unavailable", "bg-gray-600 text-gray-400 cursor-not-allowed", true, "This prop is not currently available")
                    } else if is_acquiring {
                        ("Acquiring...", "bg-blue-600 text-white opacity-50", true, "")
                    } else {
                        ("Acquire", "bg-blue-600 hover:bg-blue-700 text-white", false, "Add this prop to your inventory")
                    };

                    let prop_name = prop.name.clone();
                    let prop_description = prop.description.clone();

                    Some(view! {
                        <div class="mt-4 pt-4 border-t border-gray-700">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h3 class="text-white font-medium">{prop_name}</h3>
                                    {prop_description.map(|desc| view! {
                                        <p class="text-gray-400 text-sm">{desc}</p>
                                    })}
                                </div>
                                <button
                                    type="button"
                                    class=format!("px-4 py-2 rounded-lg transition-colors {}", button_class)
                                    on:click=move |_| {
                                        if !button_disabled {
                                            do_acquire.run(prop_id);
                                        }
                                    }
                                    disabled=button_disabled
                                    title=button_title
                                >
                                    {button_text}
                                </button>
                            </div>
                        </div>
                    })
                }}
            </div>
        </Show>
        </div>
    }
}

