using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
///
/// Полнофункциональный интерактивный смартфон игрока с приложением АвтоБазар,
/// просмотром объявлений, фото, характеристик, договоренностью о встрече и GPS-навигацией.
///
public class SmartphoneUI : MonoBehaviour
{
public enum PhoneView
{
Home,
AutoBazarFeed,
AutoBazarDetail,
GpsApp
}
[Header("Клавиши управления")]
[SerializeField] private KeyCode primaryToggleKey = KeyCode.P;
[SerializeField] private KeyCode secondaryToggleKey = KeyCode.M;
[Header("Ссылки")]
[SerializeField] private CarMarketManager marketManager;
// Состояния
public bool IsOpen { get; private set; } = false;
private PhoneView currentView = PhoneView.Home;
private CarListing selectedListing;
private string activeFilter = "Все";
// Ссылки на внешние скрипты управления
private PlayerLook playerLook;
// Canvas и корневой интерфейс
private Canvas phoneCanvas;
private RectTransform phoneRoot;
private CanvasGroup phoneGroup;
private Vector2 closedPos = new Vector2(-40f, -950f);
private Vector2 openedPos = new Vector2(-40f, 40f);
// Dynamic Island
private RectTransform dynamicIslandRect;
private TextMeshProUGUI dynamicIslandText;
private float dynamicIslandExpandTimer = 0f;
// Статус-бар
private TextMeshProUGUI clockText;
private CanvasGroup statusBarGroup;
// Экраны
private GameObject homeScreenObj;
private GameObject autoBazarFeedObj;
private GameObject autoBazarDetailObj;
private GameObject gpsAppObj;
// Элементы ленты АвтоБазара
private RectTransform feedContentRect;
private TextMeshProUGUI feedSubtitleText;
private readonly List spawnedFeedCards = new List();
// Элементы детального просмотра объявления
private Image detailPhotoImage;
private TextMeshProUGUI detailTitleText;
private TextMeshProUGUI detailPriceText;
private TextMeshProUGUI detailSpecsText;
private TextMeshProUGUI detailSellerNameText;
private TextMeshProUGUI detailSellerRatingText;
private TextMeshProUGUI detailSellerDescText;
private Button detailArrangeBtn;
private TextMeshProUGUI detailArrangeBtnText;
// GPS приложение
private TextMeshProUGUI gpsStatusText;
private TextMeshProUGUI gpsDistanceText;
// HUD Мини-кнопка открытия телефона
private GameObject hudPhoneButtonObj;
private TextMeshProUGUI hudBadgeText;
private void Awake()
{
if (marketManager == null)
marketManager = FindAnyObjectByType();
playerLook = FindAnyObjectByType();
BuildPhoneCanvas();
BuildHudPhoneButton();
}
private void Start()
{
if (marketManager != null)
{
marketManager.OnListingsUpdated += RefreshCurrentView;
marketManager.OnMeetingArranged += (listing) =>
{
TriggerDynamicIslandNotification($"💬 {listing.sellerName}: Договорились! Жду вас на локации. Метка в GPS!");
RefreshCurrentView();
};
}
SwitchView(PhoneView.Home);
phoneRoot.anchoredPosition = closedPos;
phoneGroup.alpha = 0f;
phoneRoot.gameObject.SetActive(false);
}
private void Update()
{
// В главном меню и на экране загрузки кнопка телефона скрыта
MainMenuAndBootManager menu = MainMenuAndBootManager.Instance;
bool inMenu = menu != null && !menu.IsPlaying;
if (hudPhoneButtonObj != null && hudPhoneButtonObj.activeSelf == inMenu && !IsOpen)
hudPhoneButtonObj.SetActive(!inMenu);
if (inMenu && !IsOpen) return;
// Открытие/закрытие по кнопке P или M
if ((Input.GetKeyDown(primaryToggleKey) || Input.GetKeyDown(secondaryToggleKey))
&& (IsOpen || !GameInputLock.IsLockedByOther(this)))
{
TogglePhone(!IsOpen);
}
else if (IsOpen && Input.GetKeyDown(KeyCode.Escape))
{
if (currentView == PhoneView.AutoBazarDetail)
SwitchView(PhoneView.AutoBazarFeed);
else if (currentView != PhoneView.Home)
SwitchView(PhoneView.Home);
else
TogglePhone(false);
}
// Анимация скольжения телефона
Vector2 targetPos = IsOpen ? openedPos : closedPos;
float targetAlpha = IsOpen ? 1f : 0f;
phoneRoot.anchoredPosition = Vector2.Lerp(phoneRoot.anchoredPosition, targetPos, Time.deltaTime * 14f);
phoneGroup.alpha = Mathf.MoveTowards(phoneGroup.alpha, targetAlpha, Time.deltaTime * 8f);
if (!IsOpen && phoneGroup.alpha <= 0.01f && phoneRoot.gameObject.activeSelf)
{
phoneRoot.gameObject.SetActive(false);
}
// Обновление часов
if (clockText != null)
{
DateTime now = DateTime.Now;
clockText.text = $"{now.Hour:D2}:{now.Minute:D2}";
}
// Обновление Dynamic Island и Статус-бара
if (dynamicIslandExpandTimer > 0f)
{
dynamicIslandExpandTimer -= Time.deltaTime;
dynamicIslandRect.sizeDelta = Vector2.Lerp(dynamicIslandRect.sizeDelta, new Vector2(330f, 54f), Time.deltaTime * 14f);
if (dynamicIslandText != null) dynamicIslandText.gameObject.SetActive(true);
if (statusBarGroup != null) statusBarGroup.alpha = Mathf.MoveTowards(statusBarGroup.alpha, 0f, Time.deltaTime * 12f);
}
else
{
dynamicIslandRect.sizeDelta = Vector2.Lerp(dynamicIslandRect.sizeDelta, new Vector2(120f, 28f), Time.deltaTime * 10f);
if (dynamicIslandText != null && dynamicIslandRect.sizeDelta.x < 140f)
dynamicIslandText.gameObject.SetActive(false);
if (statusBarGroup != null) statusBarGroup.alpha = Mathf.MoveTowards(statusBarGroup.alpha, 1f, Time.deltaTime * 8f);
}
// Обновление GPS приложения
if (currentView == PhoneView.GpsApp && gpsDistanceText != null)
{
UpdateGpsViewData();
}
}
public void TogglePhone(bool open)
{
IsOpen = open;
if (IsOpen)
{
if (marketManager != null)
marketManager.EnsureListingsGenerated();
phoneRoot.gameObject.SetActive(true);
PhoneAudioFeedback.Instance.PlayUnlock();
RefreshCurrentView();
}
GameInputLock.Set(this, IsOpen);
if (playerLook != null)
playerLook.enabled = !IsOpen;
if (hudPhoneButtonObj != null)
hudPhoneButtonObj.SetActive(!IsOpen);
}
public void SwitchView(PhoneView newView)
{
currentView = newView;
PhoneAudioFeedback.Instance.PlayTap();
if (homeScreenObj != null) homeScreenObj.SetActive(newView == PhoneView.Home);
if (autoBazarFeedObj != null) autoBazarFeedObj.SetActive(newView == PhoneView.AutoBazarFeed);
if (autoBazarDetailObj != null) autoBazarDetailObj.SetActive(newView == PhoneView.AutoBazarDetail);
if (gpsAppObj != null) gpsAppObj.SetActive(newView == PhoneView.GpsApp);
RefreshCurrentView();
}
private void RefreshCurrentView()
{
switch (currentView)
{
case PhoneView.Home:
break;
case PhoneView.AutoBazarFeed:
PopulateFeedCards();
break;
case PhoneView.AutoBazarDetail:
PopulateDetailData();
break;
case PhoneView.GpsApp:
UpdateGpsViewData();
break;
}
if (hudBadgeText != null && marketManager != null)
{
hudBadgeText.text = $"{marketManager.Listings.Count}";
}
}
public void TriggerDynamicIslandNotification(string text)
{
if (dynamicIslandText != null)
dynamicIslandText.text = text;
dynamicIslandExpandTimer = 4.5f;
PhoneAudioFeedback.Instance.PlayNotification();
}
// =========================================================================
// ЛЕНТА ОБЪЯВЛЕНИЙ АВТОБАЗАРА
// =========================================================================
private void PopulateFeedCards()
{
if (feedContentRect == null || marketManager == null) return;
foreach (var c in spawnedFeedCards)
{
if (c != null) Destroy(c);
}
spawnedFeedCards.Clear();
List list = marketManager.Listings;
int matchCount = 0;
for (int i = 0; i < list.Count; i++)
{
CarListing item = list[i];
// Фильтрация
if (activeFilter == "До $4,000" && item.price > 4000) continue;
if (activeFilter == "Полный привод" && item.driveType != DriveType.AWD) continue;
if (activeFilter == "Без дефектов" && (item.defectsSummary.rustedPartsCount > 0 || item.defectsSummary.missingBodyPartsCount > 0)) continue;
if (activeFilter == "Проекты" && (item.defectsSummary.rustedPartsCount == 0 && item.defectsSummary.missingBodyPartsCount == 0)) continue;
matchCount++;
CreateFeedCard(item, i);
}
if (feedSubtitleText != null)
feedSubtitleText.text = $"Найдено {matchCount} предложений от частников";
}
private void CreateFeedCard(CarListing item, int index)
{
GameObject cardObj = new GameObject($"ListingCard_{item.id}");
cardObj.transform.SetParent(feedContentRect, false);
spawnedFeedCards.Add(cardObj);
RectTransform cardRt = cardObj.AddComponent();
cardRt.sizeDelta = new Vector2(334f, 130f);
Image cardBg = cardObj.AddComponent();
cardBg.sprite = ProceduralUISprites.GetSlicedRoundedRect(new Color(0.12f, 0.14f, 0.18f, 0.95f), new Color(0.22f, 0.26f, 0.33f), 1.5f, 16);
cardBg.type = Image.Type.Sliced;
Button cardBtn = cardObj.AddComponent