// Hi-fi Home Hub — full clickable app shell.
// Persistent sidebar + routed content + overlays. Single-user.

const { useState } = React;
const { THEMES } = window.HIFI;

const HERO_ID = 'hifi-hero-sage';

function HomeHubApp() {
  const [themeId, setThemeId] = useState('lime');
  const [screen, setScreen] = useState('dashboard');
  const [notifOpen, setNotifOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [selectedAsset, setSelectedAsset] = useState(null);
  const [selectedContact, setSelectedContact] = useState(null);
  const [openRoutine, setOpenRoutine] = useState(null);
  const [modal, setModal] = useState(null);
  const [dataVersion, setDataVersion] = useState(0);
  const [toast, setToast] = useState(null); // { kind, title, sub }
  const scrollRef = React.useRef(null);
  const toastTimerRef = React.useRef(null);

  const t = THEMES[themeId] || THEMES.lime;
  const vp = useViewport();

  const toTop = () => { if (scrollRef.current) scrollRef.current.scrollTop = 0; };
  const bump = () => setDataVersion(v => v + 1);

  const showToast = (toastData) => {
    setToast(toastData);
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    toastTimerRef.current = setTimeout(() => setToast(null), 3200);
  };

  React.useEffect(() => () => { if (toastTimerRef.current) clearTimeout(toastTimerRef.current); }, []);

  const nav = {
    go: (s) => { setScreen(s); setOpenRoutine(null); setModal(null); setNotifOpen(false); toTop(); },
    openAsset:   (id) => { setSelectedAsset(id); setScreen('asset-detail'); setOpenRoutine(null); setModal(null); toTop(); },
    openContact: (id) => { setSelectedContact(id); setScreen('contact-detail'); setOpenRoutine(null); setModal(null); toTop(); },
    openRoutine: (id) => { setOpenRoutine(id); setNotifOpen(false); },
    openNotifications: () => setNotifOpen(true),
    closeNotifications: () => setNotifOpen(false),
    openSearch: () => setSearchOpen(true),
    closeSearch: () => setSearchOpen(false),
    openAdd:     (type, ctx) => setModal({ mode: 'add', type, ctx }),
    openEdit:    (type, record) => setModal({ mode: 'edit', type, record }),
    openPerson:  (contactId, personIndex) => setModal({ mode: 'person', contactId, personIndex }),
    openLink:    (contactId) => setModal({ mode: 'link', contactId }),
    openLinkContact: (assetId) => setModal({ mode: 'linkContact', assetId }),
    openSpec:    (assetId) => setModal({ mode: 'spec', assetId }),
    openModal:   (mode, ctx) => setModal({ mode, ctx }),
    closeOverlays: () => { setOpenRoutine(null); setModal(null); },

    refresh: bump,
    showToast,

    create: (kind, fields, ctx) => {
      const rec = window.Hub.create(kind, fields);
      setModal(null);
      setOpenRoutine(null);
      if (kind === 'asset') setScreen('assets');
      else if (kind === 'routine') {
        if (ctx && ctx.assetId) { setSelectedAsset(ctx.assetId); setScreen('asset-detail'); }
        else setScreen('routines');
      }
      else if (kind === 'contact') {
        if (ctx && ctx.assetId) { window.Hub.linkAsset(rec.id, ctx.assetId); setSelectedAsset(ctx.assetId); setScreen('asset-detail'); }
        else setScreen('contacts');
      }
      else if (kind === 'todo') {
        if (ctx && ctx.assetId) { setSelectedAsset(ctx.assetId); setScreen('asset-detail'); }
        else setScreen('todos');
      }
      bump();
      toTop();
    },
    update: (kind, id, fields) => {
      window.Hub.update(kind, id, fields);
      setModal(null);
      setOpenRoutine(null);
      bump();
    },
    addPerson: (contactId, person) => { window.Hub.addPerson(contactId, person); setModal(null); bump(); },
    updatePerson: (contactId, index, person) => { window.Hub.updatePerson(contactId, index, person); setModal(null); bump(); },
    removePerson: (contactId, index) => { window.Hub.removePerson(contactId, index); setModal(null); bump(); },
    addSpec:   (assetId, key, value) => { window.Hub.addSpec(assetId, key, value); setModal(null); bump(); },
    linkAsset: (contactId, assetId) => { window.Hub.linkAsset(contactId, assetId); bump(); },
    linkContact: (assetId, contactId) => { window.Hub.linkAsset(contactId, assetId); bump(); },
    toggleTodo: (id) => { window.Hub.toggleTodo(id); bump(); },
    completeRoutine: (id) => {
      const r = window.Hub.completeRoutine(id);
      setOpenRoutine(null);
      bump();
      if (r) {
        const nextBit = r.date ? ` · next ${r.nextLabel}` : '';
        showToast({ kind: 'ok', title: `Marked done: ${r.task}`, sub: `Logged for today${nextBit}` });
      }
    },
  };

  const renderScreen = () => {
    switch (screen) {
      case 'dashboard':      return <HifiDashboardBody theme={t} heroId={HERO_ID} nav={nav}/>;
      case 'assets':         return <HifiAssetsScreen t={t} nav={nav}/>;
      case 'asset-detail':   return <HifiAssetDetailScreen t={t} nav={nav} assetId={selectedAsset}/>;
      case 'routines':       return <HifiRoutinesScreen t={t} nav={nav}/>;
      case 'contacts':       return <HifiContactsScreen t={t} nav={nav}/>;
      case 'contact-detail': return <HifiContactDetailScreen t={t} nav={nav} contactId={selectedContact}/>;
      case 'todos':          return <HifiTodosScreen t={t} nav={nav}/>;
      case 'profile':
      case 'settings':       return <HifiProfileScreen t={t} nav={nav} themeId={themeId} onTheme={setThemeId}/>;
      default:               return <HifiDashboardBody theme={t} heroId={HERO_ID} nav={nav}/>;
    }
  };

  React.useEffect(() => {
    if (window.Hub && window.Hub.reconcileGaps) { window.Hub.reconcileGaps(); bump(); }
  }, []);

  // Cloud sync finished a fetch and replaced our in-memory arrays — re-render.
  React.useEffect(() => {
    const onLoaded = () => bump();
    window.addEventListener('homehub:cloud-loaded', onLoaded);
    return () => window.removeEventListener('homehub:cloud-loaded', onLoaded);
  }, []);

  React.useEffect(() => {
    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);
  }, []);

  return (
    <div style={{
      height: '100vh', width: '100vw',
      background: t.paper, color: t.ink,
      fontFamily: window.HIFI.FONT_BODY, fontSize: 14,
      display: 'flex', flexDirection: vp.isMobile ? 'column' : 'row',
      position: 'relative', overflow: 'hidden',
    }}>
      {vp.isMobile
        ? <MobileTopBar t={t} nav={nav}/>
        : <NavSidebar t={t} screen={screen} nav={nav} themeId={themeId} onTheme={setThemeId}/>}
      <div ref={scrollRef} style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', overflowY: 'auto', overflowX: 'hidden' }}>
        {renderScreen()}
      </div>
      {vp.isMobile && <MobileBottomNav t={t} screen={screen} nav={nav}/>}
      {openRoutine && <HifiRoutineSlideOver t={t} routineId={openRoutine} nav={nav}/>}
      {modal && (modal.mode === 'add' || modal.mode === 'edit') && <HifiAddModal t={t} modal={modal} nav={nav}/>}
      {modal && modal.mode === 'person' && <HifiPersonModal t={t} modal={modal} nav={nav}/>}
      {modal && modal.mode === 'link' && <HifiLinkAssetModal t={t} modal={modal} nav={nav}/>}
      {modal && modal.mode === 'linkContact' && <HifiLinkContactModal t={t} modal={modal} nav={nav}/>}
      {modal && modal.mode === 'spec' && <HifiSpecModal t={t} modal={modal} nav={nav}/>}
      {modal && modal.mode === 'password' && <HifiPasswordModal t={t} nav={nav}/>}
      {modal && modal.mode === 'calendar' && <HifiCalendarModal t={t} nav={nav} ctx={modal.ctx}/>}
      {modal && modal.mode === 'deleteRoutine' && <HifiDeleteRoutineModal t={t} nav={nav} ctx={modal.ctx}/>}
      {notifOpen && <NotificationsPanel t={t} nav={nav}/>}
      {searchOpen && <SearchOverlay t={t} nav={nav}/>}
      {toast && <Toast t={t} toast={toast} onClose={() => setToast(null)}/>}
    </div>
  );
}

// Small floating confirmation that fades in at the bottom of the viewport.
const Toast = ({ t, toast, onClose }) => (
  <div style={{
    position: 'absolute', bottom: 22, left: '50%',
    transform: 'translateX(-50%)', zIndex: 90,
    background: t.ink, color: t.paper,
    padding: '11px 14px 11px 12px', borderRadius: 12,
    boxShadow: '0 14px 38px rgba(20,18,12,0.28)',
    display: 'flex', alignItems: 'center', gap: 11,
    minWidth: 280, maxWidth: 460,
    animation: 'hh-toast-in 0.18s ease-out',
  }}>
    <span style={{
      width: 26, height: 26, borderRadius: '50%', flex: '0 0 auto',
      background: t.ok, color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}><HIcon kind="check" size={14}/></span>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.25, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{toast.title}</div>
      {toast.sub && <div style={{ fontSize: 12, opacity: 0.78, marginTop: 2 }}>{toast.sub}</div>}
    </div>
    <button onClick={onClose} style={{
      background: 'transparent', border: 'none', color: 'inherit', cursor: 'pointer',
      fontSize: 18, lineHeight: 1, padding: 4, opacity: 0.7, flex: '0 0 auto',
    }}>×</button>
    <style>{`@keyframes hh-toast-in { from { transform: translate(-50%, 12px); opacity: 0; } to { transform: translate(-50%, 0); opacity: 1; } }`}</style>
  </div>
);

ReactDOM.createRoot(document.getElementById('root')).render(
  window.AuthGate ? <AuthGate><HomeHubApp/></AuthGate> : <HomeHubApp/>
);
