// wci26_pwa/m-app.jsx — root mobile app
// Reads/writes localStorage keys shared with the desktop dashboard.

const SHARED_KEYS = {
  portfolio: 'wci26-portfolio',
  watchlist: 'wci26-monitored-team-codes',
  streak:    'wci26-streak',
  tier:      'wci26-tier',
};

// Empty until a wallet/portfolio reader is wired.
const DEFAULT_PORTFOLIO = {
  holdings: [],
};

const useSharedState = (key, fallback) => {
  const [v, setV] = React.useState(() => {
    try {
      const s = localStorage.getItem(key);
      return s ? JSON.parse(s) : fallback;
    } catch { return fallback; }
  });
  React.useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(v)); } catch {}
  }, [key, v]);
  // Listen for cross-window changes (desktop ↔ mobile)
  React.useEffect(() => {
    const onStorage = (e) => {
      if (e.key === key && e.newValue) {
        try { setV(JSON.parse(e.newValue)); } catch {}
      }
    };
    window.addEventListener('storage', onStorage);
    return () => window.removeEventListener('storage', onStorage);
  }, [key]);
  return [v, setV];
};

const computePortfolio = (rawHoldings, countries) => {
  const holdings = rawHoldings.map(h => {
    const c = countries.find(x => x.code === h.code);
    if (!c) return null;
    const value = h.tokens * c.price;
    const pnl = value - h.costBasis;
    return { ...h, value, pnl, pnlPct: (pnl / h.costBasis) * 100 };
  }).filter(Boolean).sort((a, b) => b.value - a.value);
  const totalValue = holdings.reduce((s, h) => s + h.value, 0);
  const totalCost = holdings.reduce((s, h) => s + h.costBasis, 0);
  const pnl = totalValue - totalCost;
  const pnlPct = totalCost > 0 ? (pnl / totalCost) * 100 : 0;
  return { holdings, totalValue, pnl, pnlPct };
};

const MobileApp = ({
  countries: sharedCountries,
  buybackPool: sharedBuybackPool,
  ticker: sharedTicker,
  wciMarket: sharedWciMarket,
  monitoredTeamCodes: sharedMonitoredTeamCodes,
  walletAddress,
  walletNickname,
  walletNicknameDraft,
  walletError,
  walletProfile,
  walletRows,
  onWalletConnect,
  onWalletNicknameChange,
  defaultTab = 'globe',
  onSelectCountry,
  onToggleTeamMonitor,
} = {}) => {
  const [tab, setTab] = React.useState(defaultTab);
  const [buyOpen, setBuyOpen] = React.useState(false);
  const [buyCountry, setBuyCountry] = React.useState(null);
  const [shareInfo, setShareInfo] = React.useState(null);
  const [installOpen, setInstallOpen] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  const countries = React.useMemo(
    () => (sharedCountries?.length ? sharedCountries : buildCountryTokens('live')),
    [sharedCountries],
  );
  const buybackPool = React.useMemo(
    () => (Number.isFinite(sharedBuybackPool) ? sharedBuybackPool : calcBuybackPool(countries)),
    [sharedBuybackPool, countries],
  );

  const [rawPortfolio, setRawPortfolio] = useSharedState(SHARED_KEYS.portfolio, DEFAULT_PORTFOLIO);
  const [localWatchlist, setLocalWatchlist] = useSharedState(SHARED_KEYS.watchlist, []);
  const watchlist = Array.isArray(sharedMonitoredTeamCodes) ? sharedMonitoredTeamCodes : localWatchlist;
  const [streak] = useSharedState(SHARED_KEYS.streak, 7);
  const [tier]   = useSharedState(SHARED_KEYS.tier, 'GOLD');

  const portfolio = React.useMemo(
    () => computePortfolio(rawPortfolio.holdings, countries),
    [rawPortfolio, countries],
  );

  // Build live ticker from countries
  const [ticker, setTicker] = React.useState(() => (
    sharedTicker?.length ? sharedTicker.slice(0, 20) : (
      typeof WCI_LIVE_ADAPTER !== 'undefined' && WCI_LIVE_ADAPTER.getTickerEvents
        ? WCI_LIVE_ADAPTER.getTickerEvents().slice(0, 20)
        : []
    )
  ));
  React.useEffect(() => {
    if (sharedTicker?.length) {
      setTicker(sharedTicker.slice(0, 20));
      return;
    }
    if (typeof WCI_LIVE_ADAPTER !== 'undefined' && WCI_LIVE_ADAPTER.getTickerEvents) {
      setTicker(WCI_LIVE_ADAPTER.getTickerEvents().slice(0, 20));
    }
  }, [countries, sharedTicker]);

  const openBuy = (country) => {
    onSelectCountry?.(country);
    setBuyCountry(country);
    setBuyOpen(true);
  };
  const confirmBuy = (country) => {
    setBuyOpen(false);
    if (typeof WCI_TRADE_LINKS !== 'undefined') {
      WCI_TRADE_LINKS.openUniswapSwap(country);
    }
  };
  const toggleWatch = (code) => {
    const country = countries.find((c) => c.code === code);
    if (country && typeof onToggleTeamMonitor === 'function') {
      onToggleTeamMonitor(country);
      return;
    }
    setLocalWatchlist(prev => prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]);
  };

  return (
    <div className="m-app" data-mobile-shell="wci26-pwa">
      {/* Brand glass background */}
      <div className="m-bg" />

      {/* Screen content (scrollable) */}
      <div className="m-scroll" style={{ position: 'relative', zIndex: 1 }}>
        {tab === 'live' && (
          <LiveScreen countries={countries} buybackPool={buybackPool} ticker={ticker}
                      portfolio={portfolio} watchlist={watchlist} wciMarket={sharedWciMarket}
                      onPick={openBuy} />
        )}
        {tab === 'globe' && (
          <GlobeScreen countries={countries} onPick={openBuy} />
        )}
        {tab === 'battle' && (
          <BattleScreen countries={countries} onPick={openBuy}
                        watchlist={watchlist} toggleWatch={toggleWatch} />
        )}
        {tab === 'rewards' && (
          <RewardsScreen />
        )}
        {tab === 'team' && (
          <TeamScreen countries={countries}
                      watchlist={watchlist}
                      toggleWatch={toggleWatch}
                      walletAddress={walletAddress}
                      walletNickname={walletNickname}
                      walletNicknameDraft={walletNicknameDraft}
                      walletError={walletError}
                      walletProfile={walletProfile}
                      walletRows={walletRows}
                      onWalletConnect={onWalletConnect}
                      onWalletNicknameChange={onWalletNicknameChange}
                      onPick={openBuy} />
        )}
      </div>

      {/* Notification toast */}
      <NotifToast visible={!!toast} country={toast?.country} amount={toast?.amount} />

      {/* Tab bar */}
      <TabBar tab={tab} setTab={setTab} />

      {/* Sheets */}
      <BuySheet open={buyOpen} country={buyCountry}
                onClose={() => setBuyOpen(false)}
                onConfirm={confirmBuy} />
      <ShareSheet open={!!shareInfo} country={shareInfo?.country} amount={shareInfo?.amount}
                  onClose={() => setShareInfo(null)} />
      <InstallSheet open={installOpen} onClose={() => setInstallOpen(false)} />
    </div>
  );
};

Object.assign(window, { MobileApp });
