// Shell: left nav + layout. Nav locked until authenticated.

function groupBy(arr, key) {
  const out = {};
  arr.forEach(x => { (out[x[key]] = out[x[key]] || []).push(x); });
  return out;
}

const NAV_ITEMS = [
  { id: 'landing',      label: 'Overview',              group: 'Public'     },
  // [EDIT 2026-05-11] Onboarding removed as standalone tab — now built into Assessment pre-flight
  { id: 'science',      label: 'The science',           group: 'About'      },
  { id: 'pricing',      label: 'Pricing',               group: 'About'      },
  { id: 'assessment',   label: 'Assessment',            group: 'Assessment' },
  { id: 'completion',   label: 'Quality check',         group: 'Assessment' },
  { id: 'profile',      label: 'Profile & blind spots', group: 'Reports'    },
  { id: 'constitution', label: 'AI constitution',       group: 'Reports'    },
  { id: 'pair-invite',  label: 'Pair invite',           group: 'Pairing'    },
  { id: 'pair-report',  label: 'Pair report',           group: 'Pairing'    },
  { id: 'settings',     label: 'Settings',              group: 'Account'    },
];

// Science and pricing are accessible without auth
const PUBLIC_IDS = ['landing', 'science', 'pricing', 'tos', 'privacy'];
const GROUPED_NAV_ITEMS = groupBy(NAV_ITEMS, 'group');

function Shell({ isAuthed, screen, setScreen, onSignOut, children, rightRail }) {
  const [authModal, setAuthModal] = React.useState(null);

  const handleAuth = () => {
    setAuthModal(null);
    // This will be passed down from the app level
    if (window.kalibrHandleAuth) window.kalibrHandleAuth();
  };

  // Expose function to open auth modal globally
  React.useEffect(() => {
    window.kalibrOpenAuthModal = setAuthModal;
  }, []);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', minHeight: '100vh', background: 'var(--k-bg)' }}>

      {/* Auth Modal */}
      {authModal && <AuthModal mode={authModal} onClose={() => setAuthModal(null)} onAuth={handleAuth} />}

      {/* Left nav */}
      <aside style={{
        borderRight: '1px solid var(--k-line)', background: 'var(--k-bg-2)',
        padding: '20px 14px 20px 20px', display: 'flex', flexDirection: 'column', gap: 20,
        position: 'sticky', top: 0, height: '100vh', overflowY: 'auto',
      }} className="k-scroll">

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <KalibrWordmark size={18} color="var(--k-ink)" />
          <span style={{ fontSize: 10, fontFamily: 'var(--k-mono)', color: 'var(--k-ink-4)', padding: '2px 6px', borderRadius: 4, background: 'var(--k-bg-3)' }}>v1.0</span>
        </div>

        <nav style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {Object.entries(GROUPED_NAV_ITEMS).map(([group, items]) => (
            <div key={group}>
              <div className="k-label" style={{ marginBottom: 8, padding: '0 8px' }}>{group}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                {items.map(item => {
                  const clickable = isAuthed || PUBLIC_IDS.includes(item.id);
                  return (
                    <button key={item.id}
                      onClick={() => { if (clickable) setScreen(item.id); }}
                      style={{
                        textAlign: 'left', padding: '7px 10px', border: 'none', borderRadius: 6,
                        background: screen === item.id ? 'var(--k-surface)' : 'transparent',
                        color: screen === item.id ? 'var(--k-ink)' : 'var(--k-ink-3)',
                        fontWeight: screen === item.id ? 500 : 400,
                        fontSize: 13.5,
                        cursor: clickable ? 'pointer' : 'default',
                        boxShadow: screen === item.id ? 'var(--sh-1)' : 'none',
                      }}>
                      {item.label}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        <div style={{ flex: 1 }} />

        {/* [EDIT 2026-05-11] Sign in when logged out, sign out when logged in */}
        {isAuthed ? (
          <button className="k-btn k-btn--ghost" onClick={onSignOut}
            style={{ width: '100%', marginBottom: 8 }}>
            Sign out
          </button>
        ) : (
          <button className="k-btn k-btn--primary" onClick={() => setAuthModal('signin')}
            style={{ width: '100%', marginBottom: 8 }}>
            Sign in / Sign up
          </button>
        )}

        <div style={{ padding: 12, borderRadius: 10, background: 'var(--k-bg-3)', fontSize: 12, color: 'var(--k-ink-3)', lineHeight: 1.5 }}>
          <div style={{ fontWeight: 600, color: 'var(--k-ink-2)', marginBottom: 4 }}>Pilot build</div>
          Identical inputs always produce identical outputs.
        </div>
      </aside>

      {/* Main */}
      <main style={{
        display: 'grid',
        gridTemplateColumns: rightRail ? '1fr 320px' : '1fr',
        minHeight: '100vh',
        marginTop: 0,
      }}>
        <div data-screen-label={screen} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
          <div style={{ flex: 1 }}>
            {children}
          </div>
          <SiteFooter onEnter={setScreen} />
        </div>
        {rightRail && (
          <aside style={{ borderLeft: '1px solid var(--k-line)', background: 'var(--k-bg)', padding: 24, position: 'sticky', top: 0, height: '100vh', overflowY: 'auto' }} className="k-scroll">
            {rightRail}
          </aside>
        )}
      </main>
    </div>
  );
}

function SiteFooter({ onEnter }) {
  return (
    <footer style={{
      borderTop: '1px solid var(--k-line)',
      padding: '18px 48px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      background: 'var(--k-bg-2)',
    }}>
      <span style={{ fontSize: 12, color: 'var(--k-ink-4)', fontFamily: 'var(--k-mono)' }}>
        © {new Date().getFullYear()} Kalibr
      </span>
      <div style={{ display: 'flex', gap: 24, alignItems: 'center' }}>
        {[
          { label: 'Terms of Use', id: 'tos' },
          { label: 'Privacy Policy', id: 'privacy' },
        ].map(({ label, id }) => (
          <button key={id} onClick={() => onEnter(id)}
            style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', fontSize: 12, color: 'var(--k-ink-3)', fontFamily: 'var(--k-sans)' }}>
            {label}
          </button>
        ))}
        <a href="mailto:hello@kalibr.ai"
          style={{ fontSize: 12, color: 'var(--k-ink-3)', textDecoration: 'none', fontFamily: 'var(--k-sans)' }}>
          Contact
        </a>
      </div>
    </footer>
  );
}

Object.assign(window, { Shell });