/* FinPulse app shell. Exports to window. */
const NAV_ITEMS = [
  { key: 'markets', label: 'Markets', icon: 'markets' },
  { key: 'stocks', label: 'Stocks', icon: 'stocks' },
  { key: 'screener', label: 'Screener', icon: 'screener' },
  { key: 'indices', label: 'Indices', icon: 'indices' },
  { key: 'funds', label: 'Mutual Funds', icon: 'funds' },
  { key: 'ipo', label: 'IPO', icon: 'ipo' },
  { key: 'news', label: 'News', icon: 'news' },
  { key: 'calc', label: 'Calculators', icon: 'calc' },
];

function TickerBar({ stocks, onOpenStock }) {
  const Item = ({ s }) => (
    <button className="ticker-item" onClick={() => onOpenStock(s)} tabIndex={-1}>
      <span className="ti-sym">{s.ticker}</span>
      <span className="ti-price">{fmt.stockPrice(s)}</span>
      <span className={`ti-chg ${s.chg >= 0 ? 'up' : 'down'}`}>{s.chg >= 0 ? '▲' : '▼'}{fmt.pct(s.chg)}</span>
    </button>
  );
  return (
    <div className="ticker-bar" aria-label="Live market ticker">
      <div className="ticker-track">
        {stocks.map((s) => <Item key={s.id} s={s} />)}
        {stocks.map((s) => <Item key={'dup' + s.id} s={s} />)}
      </div>
    </div>
  );
}

function Brand({ mobile, onHome }) {
  const B = window.CSP_BRAND || { name: 'Company Stock Price', shortName: 'CSP', domain: 'companystockprice.com' };
  const inner = (
    <>
      <div className="brand-mark" aria-hidden="true"><span className="brand-mark-text">{B.shortName}</span></div>
      <div className="brand-stack">
        <span className="brand-name">Company <span className="brand-accent">Stock Price</span></span>
        {!mobile && <span className="brand-domain">{B.domain}</span>}
      </div>
    </>
  );
  if (mobile) {
    return (
      <button type="button" className="brand-mobile" onClick={onHome} aria-label={B.name}>
        {inner}
      </button>
    );
  }
  return (
    <button type="button" className="sidebar-brand brand-home" onClick={onHome} aria-label={B.name}>
      {inner}
    </button>
  );
}

function Sidebar({ current, onNav, drawerOpen, onCloseDrawer, onHome }) {
  return (
    <aside className={`sidebar ${drawerOpen ? 'drawer-open' : ''}`}>
      <Brand onHome={onHome} />
      <nav className="sidebar-nav">
        {NAV_ITEMS.map((it) => (
          <button key={it.key} className={`nav-item ${current === it.key ? 'active' : ''}`}
            onClick={() => { onNav(it.key); onCloseDrawer && onCloseDrawer(); }}>
            <Icon name={it.icon} size={20} />
            <span className="nav-label">{it.label}</span>
            <span className="tip">{it.label}</span>
          </button>
        ))}
      </nav>
      <div className="sidebar-foot">
        <div className="muted" style={{ fontSize: 11 }}>NSE · 9:15–15:30 IST</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--up)' }}></span>
          <span style={{ fontSize: 12, color: 'var(--text-secondary)', fontWeight: 600 }}>India markets · live data</span>
        </div>
      </div>
    </aside>
  );
}

function userInitials(name) {
  const parts = String(name || '').trim().split(/\s+/).filter(Boolean);
  if (!parts.length) return null;
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}

function Topbar({ theme, onToggleTheme, onHamburger, onOpenSearch, onHome }) {
  const gate = typeof useUsageGate === 'function' ? useUsageGate() : null;
  const showProfile = gate && gate.signedIn;

  return (
    <header className="topbar">
      <button className="icon-btn hamburger" onClick={onHamburger} aria-label="Menu"><Icon name="menu" /></button>
      <div className="brand-mobile"><Brand mobile onHome={onHome} /></div>

      <div className="search-bar" onClick={onOpenSearch}>
        <Icon name="search" size={17} />
        <input placeholder="Search stocks, indices, news…" onFocus={(e) => { e.target.blur(); onOpenSearch(); }} readOnly />
        <span className="kbd">⌘K</span>
      </div>

      <div className="topbar-actions">
        <button className="icon-btn search-trigger" onClick={onOpenSearch} aria-label="Search" style={{ display: 'none' }}><Icon name="search" /></button>
        <button className="icon-btn" onClick={onToggleTheme} aria-label="Toggle theme">
          <Icon name={theme === 'dark' ? 'sun' : 'moon'} />
        </button>
        {showProfile && (
          <div className="avatar" title={gate.userName || 'Signed in'} aria-label="Signed in">
            {userInitials(gate.userName) || <Icon name="user" size={18} />}
          </div>
        )}
      </div>
    </header>
  );
}

const BOTTOM_ITEMS = [
  { key: 'markets', label: 'Markets', icon: 'markets' },
  { key: 'stocks', label: 'Stocks', icon: 'stocks' },
  { key: 'news', label: 'News', icon: 'news' },
  { key: 'more', label: 'More', icon: 'more' },
];
function BottomNav({ current, onNav }) {
  return (
    <nav className="bottom-nav">
      {BOTTOM_ITEMS.map((it) => (
        <button key={it.key} className={`bn-item ${current === it.key ? 'active' : ''}`} onClick={() => onNav(it.key)}>
          <Icon name={it.icon} size={22} fill={current === it.key} />
          <span>{it.label}</span>
        </button>
      ))}
    </nav>
  );
}

function SearchOverlay({ open, onClose, onOpenStock }) {
  const L = useLive();
  const MD = useMarketData();
  const [q, setQ] = useState('');
  const [results, setResults] = useState([]);
  const [busy, setBusy] = useState(false);
  const [loadingSym, setLoadingSym] = useState(null);
  const [err, setErr] = useState('');
  useEffect(() => { if (open) { setQ(''); setResults([]); setErr(''); } }, [open]);

  useEffect(() => {
    if (!q.trim()) { setResults([]); return; }
    setBusy(true); setErr('');
    const id = setTimeout(async () => {
      try {
        const local = L.market.searchLocal(q.trim(), MD.stocks, 8);
        if (L.hasKey) {
          const remote = await L.market.searchSymbols(q.trim(), 6, MD.stocks);
          const seen = new Set(local.map((r) => r.symbol));
          setResults([...local, ...remote.filter((r) => !seen.has(r.symbol))]);
          L.refreshRateLimit();
        } else {
          setResults(local);
        }
      } catch (e) {
        setResults(L.market.searchLocal(q.trim(), MD.stocks, 12));
      } finally { setBusy(false); }
    }, 300);
    return () => clearTimeout(id);
  }, [q, L.hasKey, MD.stocks]);

  async function openLive(symbol) {
    setLoadingSym(symbol); setErr('');
    try {
      const sym = String(symbol || '');
      const local = MD.stocks.find((s) => s.symbol === sym || s.ticker === sym.replace(/\.NS$/i, ''));
      if (local) {
        onOpenStock(local);
        onClose();
        return;
      }
      onOpenStock(await L.market.getStock(symbol));
      L.refreshRateLimit();
      onClose();
    } catch (e) {
      setErr(e.code === 'RATE_LIMIT' ? 'Rate limit — wait a moment' : apiErrorMessage(e));
    } finally { setLoadingSym(null); }
  }

  if (!open) return null;
  const recent = [...MD.stocks].sort((a, b) => Math.abs(b.chg) - Math.abs(a.chg)).slice(0, 10).map((s) => s.ticker);

  return (
    <div className="search-overlay">
      <div className="search-overlay-head">
        <Icon name="search" size={20} style={{ color: 'var(--text-muted)' }} />
        <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search NSE stocks (Reliance, TCS…) or US symbols" />
        <LiveBadge live={MD.ready} small />
        <button className="icon-btn" onClick={onClose}><Icon name="x" /></button>
      </div>
      <div className="recent-list">
        {err && <div style={{ color: 'var(--down)', fontSize: 13, padding: '8px 0' }}>{err}</div>}
        {q ? (
          busy ? (
            <div style={{ padding: '8px 0' }}>
              {[0, 1, 2, 3].map((i) => (
                <div key={i} className="sk-mover-row">
                  <Shimmer w={52} h={13} r={4} />
                  <Shimmer w="60%" h={13} r={4} style={{ flex: 1 }} />
                </div>
              ))}
            </div>
          )
          : results.length ? results.map((r) => (
            <div key={r.symbol} className="recent-row" style={{ cursor: 'pointer' }} onClick={() => openLive(r.symbol)}>
              <span className="mono" style={{ width: 70, fontWeight: 600, fontSize: 13, color: 'var(--accent)' }}>{r.displaySymbol || r.symbol}</span>
              <span style={{ flex: 1, fontSize: 14, color: 'var(--text-secondary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.description}</span>
              {loadingSym === r.symbol ? <span className="muted">loading…</span> : <Icon name="chevright" size={16} style={{ color: 'var(--text-muted)' }} />}
            </div>
          )) : <div className="muted" style={{ padding: '12px 0' }}>No matches for "{q}"</div>
        ) : (
          <>
            <div className="label-up" style={{ marginBottom: 8 }}>Popular symbols</div>
            {recent.map((r, i) => (
              <div key={i} className="recent-row" onClick={() => openLive(r)} style={{ cursor: 'pointer' }}>
                <Icon name="trend" size={16} style={{ color: 'var(--text-muted)' }} />
                <span style={{ flex: 1 }} className="mono">{r}</span>
                {loadingSym === r ? <span className="muted">loading…</span> : <Icon name="chevright" size={16} style={{ color: 'var(--text-muted)' }} />}
              </div>
            ))}
          </>
        )}
      </div>
    </div>
  );
}

function Footer({ onNav }) {
  const B = window.CSP_BRAND || { legalName: 'Company Stock Price', copyrightYear: 2026, domain: 'companystockprice.com' };
  const links = [
    { key: 'about', label: 'About' },
    { key: 'terms', label: 'Terms' },
    { key: 'privacy', label: 'Privacy' },
    { key: 'disclaimer', label: 'Disclaimer' },
  ];
  return (
    <footer className="footer">
      <span>© {B.copyrightYear} {B.legalName} · {B.domain} · For informational use only.</span>
      <div className="footer-links">
        {links.map((l) => (
          <button key={l.key} type="button" onClick={() => onNav && onNav(l.key)}>{l.label}</button>
        ))}
      </div>
    </footer>
  );
}

Object.assign(window, { NAV_ITEMS, TickerBar, Sidebar, Topbar, BottomNav, SearchOverlay, Footer });
