// Healify Web — desktop shell: left sidebar + top utility bar + content router.
// Tier-A routes render bespoke desktop pages; every other route renders the
// canonical mobile screen in a centered app column (so all pages are reachable).

const { useState: useStateSH, useEffect: useEffectSH, useMemo: useMemoSH, useRef: useRefSH } = React;

// ── sidebar icons (line style, matches kit) ───────────────────────────────
const SIDE_ICON = {
  home:    'M3.5 10.5 12 3l8.5 7.5V20a1 1 0 0 1-1 1h-5v-6h-5v6H4.5a1 1 0 0 1-1-1Z',
  health:  'M4 12h3l2-5 4 10 2-6 2 3h4',
  nutrition: 'M12 3c4 0 6 3 6 7s-3 11-6 11-6-7-6-11 2-7 6-7Z M12 3v18',
  fitness: 'M6.5 6.5 17.5 17.5 M4 9l2-2 2 2-2 2Z M16 17l2-2 2 2-2 2Z M9 15l6-6',
  wall:    'M4 5h16v6H4Z M4 13h16v6H4Z',
  chat:    'M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H9l-4 3v-3H6a2 2 0 0 1-2-2Z',
  picks:   'M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5Z',
  habits:  'M9 11l3 3L22 4 M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11',
  notifications: 'M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9 M13.7 21a2 2 0 0 1-3.4 0',
  account: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z M4 21c0-4 4-6 8-6s8 2 8 6',
  help:    'M9.1 9a3 3 0 1 1 4 2.8c-.9.4-1.6 1.2-1.6 2.2 M12 17v.01 M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18Z',
};
function SideIcon({ k, active }) {
  return (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={active ? 'var(--brand-orange-vibey)' : H.fg2} strokeWidth={active ? 2.1 : 1.8} strokeLinecap="round" strokeLinejoin="round">
      <path d={SIDE_ICON[k] || SIDE_ICON.home} />
    </svg>
  );
}

function DeskNavRow({ k, label, active, badge, onClick }) {
  return (
    <button onClick={onClick} title={label} className={'desk-nav-row' + (active ? ' is-active' : '')} style={{
      display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left',
      padding: '10px 12px', borderRadius: 12, cursor: 'pointer', border: 0,
    }}>
      <SideIcon k={k} active={active} />
      <span className="dk-navlabel" style={{ flex: 1, fontFamily: H.body, fontWeight: active ? 600 : 400, fontSize: 14.5, color: active ? H.fg1 : H.fg2, letterSpacing: -0.2 }}>{label}</span>
      {badge > 0 && <span className="dk-navbadge" style={{ fontFamily: H.body, fontWeight: 600, fontSize: 11, color: '#fff', background: 'var(--brand-orange-vibey)', minWidth: 18, height: 18, padding: '0 5px', boxSizing: 'border-box', borderRadius: 999, display: 'grid', placeItems: 'center' }}>{badge}</span>}
    </button>
  );
}

function DeskSidebar({ screen, activeTab, nav, wallUnread }) {
  const isActive = (r, isTab) => screen === r || (isTab && activeTab === r && APP_TABS.some(t => t.k === screen));
  const primary = [
    { k: 'home', label: 'Home', tab: true }, { k: 'health', label: 'Health', tab: true },
    { k: 'nutrition', label: 'Nutrition', tab: true }, { k: 'fitness', label: 'Fitness', tab: true },
    { k: 'wall', label: 'Your Wall' }, { k: 'chat', label: 'Anna' }, { k: 'habits', label: 'Habits' },
  ];
  const secondary = [
    { k: 'picks', label: 'AI Tools' },
  ];
  const footer = [{ k: 'notifications', label: 'Notifications' }, { k: 'account', label: 'Account & Settings' }, { k: 'help', label: 'Help' }];
  return (
    <aside className="dk-sidebar" style={{ width: 250, flexShrink: 0, height: '100%', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', background: '#fff', borderRight: '1px solid var(--border-subtle)', padding: '20px 14px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 8px 18px' }}>
        <HealifyMark size={32} />
        <span className="dk-brandword" style={{ fontFamily: H.display, fontWeight: 600, fontSize: 20, letterSpacing: -0.4, color: H.fg1 }}>Healify</span>
      </div>
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {primary.map(it => <DeskNavRow key={it.k} k={it.k} label={it.label} active={isActive(it.k, it.tab)} badge={it.k === 'wall' ? wallUnread : 0} onClick={() => nav(it.tab ? 'tab:' + it.k : it.k)} />)}
      </nav>
      <div style={{ height: 1, background: 'var(--border-subtle)', margin: '14px 8px' }} />
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {secondary.map(it => <DeskNavRow key={it.k} k={it.k} label={it.label} active={isActive(it.k)} onClick={() => nav(it.k)} />)}
      </nav>
      <div style={{ flex: 1 }} />
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        {footer.map(it => <DeskNavRow key={it.k} k={it.k} label={it.label} active={isActive(it.k)} onClick={() => nav(it.k)} />)}
      </nav>
      {/* upgrade card */}
      <div onClick={() => nav('plans')} className="dk-upgrade" style={{ marginTop: 12, padding: 14, borderRadius: 16, cursor: 'pointer', background: 'var(--grad-ink-veil, #1a1622)', color: '#fff' }}>
        <div style={{ fontFamily: H.body, fontWeight: 600, fontSize: 13.5 }}>Healify Plus</div>
        <div style={{ fontFamily: H.body, fontSize: 12, color: 'rgba(255,255,255,0.7)', marginTop: 2, lineHeight: 1.35 }}>Unlock unlimited Anna, plans & reports.</div>
      </div>
    </aside>
  );
}

// ── top utility bar ─────────────────────────────────────────────────────
const PAGE_TITLES = {
  home: 'Home', health: 'Your Health', nutrition: 'Nutrition', fitness: 'Fitness',
  wall: 'Your Wall', chat: 'Anna', picks: 'AI Tools', habits: 'Habits',
  notifications: 'Notifications', account: 'Account & Settings', help: 'Help',
};
function DeskTopUtil({ screen, nav, onOpenSearch }) {
  const title = PAGE_TITLES[screen] || '';
  const isMac = typeof navigator !== 'undefined' && /Mac/.test(navigator.platform);
  return (
    <header style={{ height: 64, flexShrink: 0, display: 'flex', alignItems: 'center', gap: 16, padding: '0 28px', borderBottom: '1px solid var(--border-subtle)', background: 'var(--surface-80, rgba(255,255,255,0.85))', backdropFilter: 'blur(16px) saturate(1.4)', WebkitBackdropFilter: 'blur(16px) saturate(1.4)' }}>
      <div style={{ fontFamily: H.display, fontWeight: 600, fontSize: 17, color: H.fg1, letterSpacing: -0.3, whiteSpace: 'nowrap' }}>{title}</div>
      <div style={{ flex: 1 }} />
      <button onClick={onOpenSearch} aria-label="Search" className="dk-search-trigger" style={{ display: 'flex', alignItems: 'center', gap: 8, height: 38, padding: '0 10px 0 14px', background: H.bg, border: '1px solid transparent', borderRadius: 999, minWidth: 220, color: H.fg3, cursor: 'pointer' }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.2-3.2" /></svg>
        <span style={{ fontFamily: H.body, fontSize: 13.5, flex: 1, textAlign: 'left' }}>Search Healify…</span>
        <span style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, background: '#fff', border: '1px solid var(--border-subtle)', borderRadius: 6, padding: '2px 6px', lineHeight: 1 }}>{isMac ? '⌘K' : 'Ctrl K'}</span>
      </button>
      <button onClick={() => nav('notifications')} aria-label="Notifications" style={{ position: 'relative', width: 40, height: 40, borderRadius: 999, border: 0, background: 'transparent', display: 'grid', placeItems: 'center', cursor: 'pointer' }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={H.fg1} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" /><path d="M13.7 21a2 2 0 0 1-3.4 0" /></svg>
      </button>
      <button onClick={() => nav('account')} aria-label="Account" style={{ width: 38, height: 38, borderRadius: 999, border: 0, background: H.black, color: '#fff', fontFamily: H.body, fontWeight: 600, fontSize: 14, cursor: 'pointer' }}>K</button>
    </header>
  );
}

// ── Wall two-pane desktop page ─────────────────────────────────────────────
function DeskWallPage({ wallStore, wallSettings, nav, postId }) {
  const [selectedId, setSelectedId] = useStateSH(null);
  useEffectSH(() => {
    if (!wallStore.loading && !wallStore.error && wallStore.posts.length > 0) {
      if (postId && wallStore.posts.some(p => p.id === postId)) {
        setSelectedId(postId);
      } else {
        setSelectedId(prev => (prev && wallStore.posts.some(p => p.id === prev)) ? prev : wallStore.posts[0].id);
      }
    }
    if (wallStore.posts.length === 0) setSelectedId(null);
  }, [wallStore.loading, wallStore.error, wallStore.posts, postId]);
  useEffectSH(() => {
    const onKey = (e) => {
      const tag = e.target && e.target.tagName;
      if (tag && /INPUT|TEXTAREA|SELECT/.test(tag)) return;
      const ids = wallStore.posts.map(p => p.id); if (!ids.length) return;
      const i = ids.indexOf(selectedId);
      if (e.key === 'ArrowDown' || e.key === 'j') { e.preventDefault(); setSelectedId(ids[Math.min(ids.length - 1, i + 1)]); }
      else if (e.key === 'ArrowUp' || e.key === 'k') { e.preventDefault(); setSelectedId(ids[Math.max(0, i - 1)]); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [wallStore.posts, selectedId]);
  const selectedPost = wallStore.posts.find(p => p.id === selectedId) || null;
  return (
    <div style={{ display: 'flex', height: '100%', minHeight: 0, background: H.bg }}>
      <DeskListPane store={wallStore} settings={wallSettings} selectedId={selectedId} onSelect={setSelectedId} />
      <DeskDetailPane post={selectedPost} store={wallStore} onAskAnna={() => nav('chat', { topic: 'sleep-checkin' })} />
    </div>
  );
}

// ── Tier-B: render a mobile screen centered in an app column ───────────────
function DeskCenteredScreen({ screen, params, ctx }) {
  return (
    <div style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', padding: '28px 24px' }} className="no-scrollbar">
      <div style={{ width: 468, maxWidth: '100%', height: 'min(840px, calc(100vh - 64px - 56px))', background: H.bg, borderRadius: 28, overflow: 'hidden', position: 'relative', boxShadow: '0 12px 44px rgba(3,4,13,0.12), 0 0 0 1px var(--border-subtle)' }}>
        <div style={{ position: 'absolute', inset: 0, overflowY: 'auto' }} className="no-scrollbar">
          {renderMobileScreen(screen, params, ctx)}
        </div>
      </div>
    </div>
  );
}

const TIER_A = new Set(['home', 'health', 'nutrition', 'fitness', 'chat']);

// ── Search command palette ────────────────────────────────────────────────
const SEARCH_INDEX = [
  { label: 'Home', sub: 'Dashboard & health score', route: 'home', group: 'Pages', kw: 'dashboard score overview' },
  { label: 'Your Health', sub: 'Score breakdown & vitals', route: 'health', group: 'Pages', kw: 'vitals blood pressure heart rate score' },
  { label: 'Nutrition', sub: 'Calories, macros & meals', route: 'nutrition', group: 'Pages', kw: 'food calories macros protein meals diet' },
  { label: 'Fitness', sub: 'Workouts & activity', route: 'fitness', group: 'Pages', kw: 'exercise workout steps activity training' },
  { label: 'Your Wall', sub: "Anna's insights feed", route: 'wall', group: 'Pages', kw: 'feed posts insights anna' },
  { label: 'Anna', sub: 'Chat with your coach', route: 'chat', group: 'Pages', kw: 'chat message coach talk ask' },
  { label: 'AI Tools', sub: 'Meal plans, reports & more', route: 'picks', group: 'Pages', kw: 'tools picks ai' },
  { label: 'Habits', sub: 'Streaks & routines', route: 'habits', group: 'Pages', kw: 'streak routine water habit' },
  { label: 'Notifications', sub: 'Alerts & reminders', route: 'notifications', group: 'Pages', kw: 'alerts reminders bell' },
  { label: 'Account & Settings', sub: 'Profile & preferences', route: 'account', group: 'Pages', kw: 'settings profile preferences privacy units appearance' },
  { label: 'Help', sub: 'Support & FAQ', route: 'help', group: 'Pages', kw: 'support faq contact problem' },
  { label: 'Meal plan', sub: 'Your weekly recipes', route: 'mealplan', group: 'Tools', kw: 'recipes food cooking week' },
  { label: 'Workouts', sub: 'Planned sessions', route: 'workout', group: 'Tools', kw: 'exercise training session' },
  { label: 'Meditation', sub: 'Guided sessions', route: 'meditation', group: 'Tools', kw: 'mindfulness breathe sleep calm' },
  { label: 'Blood report', sub: 'Upload & scan labs', route: 'blood', group: 'Tools', kw: 'lab bloodwork cholesterol upload pdf' },
  { label: 'DNA insights', sub: 'Genetic markers', route: 'dna', group: 'Tools', kw: 'genetics genome markers' },
  { label: 'Plans & billing', sub: 'Manage subscription', route: 'plans', group: 'Tools', kw: 'subscription upgrade plus payment billing receipts' },
];

function DeskSearchPalette({ open, onClose, nav, wallStore }) {
  const [q, setQ] = useStateSH('');
  const [active, setActive] = useStateSH(0);
  const inputRef = useRefSH(null);
  useEffectSH(() => { if (open) { setQ(''); setActive(0); setTimeout(() => inputRef.current && inputRef.current.focus(), 30); } }, [open]);

  const results = useMemoSH(() => {
    const base = SEARCH_INDEX.slice();
    const posts = (wallStore.posts || []).map(p => ({ label: p.caption, sub: 'Wall · ' + (PILLARS[p.pillarTag] ? PILLARS[p.pillarTag].label : 'insight'), route: 'post-detail', params: { postId: p.id }, group: 'Your Wall', kw: (p.annaCommentary || '') + ' ' + p.pillarTag }));
    const all = base.concat(posts);
    const term = q.trim().toLowerCase();
    if (!term) return base;
    return all.filter(it => (it.label + ' ' + (it.sub || '') + ' ' + (it.kw || '')).toLowerCase().includes(term)).slice(0, 9);
  }, [q, wallStore.posts]);

  useEffectSH(() => { setActive(0); }, [q]);
  useEffectSH(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') { e.preventDefault(); onClose(); }
      else if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(results.length - 1, a + 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      else if (e.key === 'Enter') { e.preventDefault(); const r = results[active]; if (r) { nav(r.route, r.params || {}); onClose(); } }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, results, active]);

  if (!open) return null;
  let lastGroup = null;
  return (
    <div onMouseDown={onClose} style={{ position: 'fixed', inset: 0, zIndex: 500, background: 'rgba(3,4,13,0.34)', backdropFilter: 'blur(2px)', display: 'flex', justifyContent: 'center', alignItems: 'flex-start', paddingTop: '12vh' }}>
      <div onMouseDown={e => e.stopPropagation()} style={{ width: 560, maxWidth: 'calc(100vw - 40px)', background: '#fff', borderRadius: 20, overflow: 'hidden', boxShadow: '0 24px 70px rgba(3,4,13,0.32)', animation: 'deskPop 160ms cubic-bezier(.22,.7,.3,1) both' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '14px 18px', borderBottom: '1px solid var(--border-subtle)' }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={H.fg3} strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="7" /><path d="m20 20-3.2-3.2" /></svg>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder="Search pages, tools, and Anna's insights…" style={{ flex: 1, border: 0, outline: 0, fontFamily: H.body, fontSize: 16, color: H.fg1, background: 'transparent' }} />
          <button onClick={onClose} aria-label="Close" style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, background: H.bg, border: '1px solid var(--border-subtle)', borderRadius: 6, padding: '3px 7px', cursor: 'pointer', lineHeight: 1 }}>Esc</button>
        </div>
        <div className="no-scrollbar" style={{ maxHeight: 380, overflowY: 'auto', padding: 8 }}>
          {results.length === 0 ? (
            <div style={{ padding: '34px 18px', textAlign: 'center', fontFamily: H.body, fontSize: 14, color: H.fg3 }}>No results for “{q}”. Try “sleep”, “meal plan”, or “billing”.</div>
          ) : results.map((r, i) => {
            const showGroup = r.group !== lastGroup; lastGroup = r.group;
            return (
              <React.Fragment key={r.route + i}>
                {showGroup && <div style={{ fontFamily: H.body, fontWeight: 500, fontSize: 11, letterSpacing: 1.1, textTransform: 'uppercase', color: H.fg3, padding: '10px 12px 5px' }}>{r.group}</div>}
                <button onMouseEnter={() => setActive(i)} onClick={() => { nav(r.route, r.params || {}); onClose(); }} style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left', border: 0, cursor: 'pointer', padding: '10px 12px', borderRadius: 12, background: i === active ? 'var(--quartz-soft-bg)' : 'transparent' }}>
                  <span style={{ width: 34, height: 34, borderRadius: 9, background: i === active ? '#fff' : H.bg, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={i === active ? H.orange : H.fg2} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d={SIDE_ICON[r.route] || 'M5 12h14M13 6l6 6-6 6'} /></svg>
                  </span>
                  <span style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ display: 'block', fontFamily: H.body, fontWeight: 500, fontSize: 14.5, color: H.fg1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.label}</span>
                    <span style={{ display: 'block', fontFamily: H.body, fontSize: 12.5, color: H.fg3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.sub}</span>
                  </span>
                  {i === active && <span style={{ fontFamily: H.body, fontSize: 11, color: H.fg3, flexShrink: 0 }}>↵</span>}
                </button>
              </React.Fragment>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function DesktopShell({ stack, nav, pop, resetTo, activeTab, wallStore, wallSettings }) {
  const [searchOpen, setSearchOpen] = useStateSH(false);
  useEffectSH(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) { e.preventDefault(); setSearchOpen(o => !o); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  const top = stack[stack.length - 1];
  const screen = top.name;
  const p = top.params || {};
  const wallUnread = wallStore.posts.filter(x => x.readAt === null).length;
  const ctx = { nav, pop, resetTo, stackLen: stack.length, wallStore, wallSettings };

  let content;
  if (screen === 'home') content = <DeskHome nav={nav} wallStore={wallStore} />;
  else if (screen === 'health') content = <DeskHealth nav={nav} />;
  else if (screen === 'nutrition') content = <DeskNutrition nav={nav} />;
  else if (screen === 'fitness') content = <DeskFitness nav={nav} />;
  else if (screen === 'chat') content = <DeskChat nav={nav} pop={pop} resetTo={resetTo} stackLen={stack.length} topic={p.topic} />;
  else if (screen === 'wall' || screen === 'post-detail') content = <DeskWallPage wallStore={wallStore} wallSettings={wallSettings} nav={nav} postId={p.postId} />;
  else content = <DeskCenteredScreen screen={screen} params={p} ctx={ctx} />;

  const flush = screen === 'wall' || screen === 'post-detail' || screen === 'chat';
  const scrolls = !flush && !TIER_A.has(screen) ? false : (screen !== 'chat' && screen !== 'wall' && screen !== 'post-detail');

  return (
    <div style={{ display: 'flex', height: '100vh', width: '100%', overflow: 'hidden', background: H.bg }} data-screen-label={screen}>
      <DeskSidebar screen={screen} activeTab={activeTab} nav={nav} wallUnread={wallUnread} />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <DeskTopUtil screen={screen} nav={nav} onOpenSearch={() => setSearchOpen(true)} />
        <main key={screen} className={flush ? '' : 'screen-enter'} style={{ flex: 1, minHeight: 0, overflowY: (flush ? 'hidden' : 'auto'), overflowX: 'hidden', padding: (flush ? 0 : '30px 32px 48px'), background: H.bg }} >
          {content}
        </main>
      </div>
      <DeskSearchPalette open={searchOpen} onClose={() => setSearchOpen(false)} nav={nav} wallStore={wallStore} />
    </div>
  );
}

Object.assign(window, { DesktopShell, DeskSidebar, DeskTopUtil, DeskWallPage, DeskCenteredScreen, DeskSearchPalette, SideIcon, PAGE_TITLES });
