// atelier-shell.jsx — App shell: left rail nav, route container, tweaks wiring.

const { useState: useStateShell, useEffect: useEffectShell, useMemo: useMemoShell } = React;

// NAV_ROUTES: shown in the rail UI. Targets is here (it's a standalone study
// room) but hidden until a lesson is loaded; hero/tension still live in the
// Study tabs and are accessible via deep-link only.
const NAV_ROUTES = [
  { id: 'home',       num: '01', ...window.COPY.nav.routes.home       },
  { id: 'onboarding', num: '02', ...window.COPY.nav.routes.onboarding },
  { id: 'lesson',     num: '03', ...window.COPY.nav.routes.lesson     },
  { id: 'puzzle',     num: '04', ...window.COPY.nav.routes.puzzle     },
  { id: 'play',       num: '05', ...window.COPY.nav.routes.play       },
  { id: 'targets',    num: '06', ...window.COPY.nav.routes.targets    },
  { id: 'vectors',    num: '07', ...window.COPY.nav.routes.vectors    },
  { id: 'overload',   num: '08', ...window.COPY.nav.routes.overload   },
  { id: 'ghost',      num: '09', ...window.COPY.nav.routes.ghost      },
];

// ROUTES: full list for route validation in app.jsx (includes hero/tension for deep-links).
const ROUTES = [
  ...NAV_ROUTES,
  { id: 'hero',    num: '10', ...window.COPY.nav.routes.hero    },
  { id: 'tension', num: '11', ...window.COPY.nav.routes.tension },
];

function ProgressBox({ palette }) {
  const C = palette;
  // Re-read on every render so it picks up changes made by lesson screens.
  const progress = window.getProgress ? window.getProgress() : {};
  const currentLessonId = window.LESSON ? window.LESSON.id : null;
  const currentProgress = currentLessonId ? (progress[currentLessonId] || { lastStep: 0 }) : { lastStep: 0 };
  const totalSteps = window.LESSON && window.LESSON.lesson ? window.LESSON.lesson.length : 6;
  const progressFraction = totalSteps > 0 ? currentProgress.lastStep / totalSteps : 0;
  const progressLabel = currentLessonId && window.LESSON && window.LESSON.meta
    ? (window.creativeTitle ? window.creativeTitle(currentLessonId) : window.LESSON.meta.title)
    : window.COPY.nav.progressLesson;

  return (
    <div className="atelier-rail-progress" style={{ marginTop: 'auto', padding: '0 6px', fontSize: 11, lineHeight: 1.5 }}>
      <div style={{
        padding: '14px 14px',
        background: C.cream,
        borderRadius: 10,
        border: `0.6px solid ${C.umberHair}`,
      }}>
        <div style={{
          fontFamily: window.ATELIER_TYPE.display,
          fontStyle: 'italic',
          fontWeight: 300,
          fontSize: 14,
          color: C.umber,
          marginBottom: 6,
        }}>
          {window.COPY.nav.progressLabel}
        </div>
        <div style={{
          opacity: 0.85,
          fontFamily: window.ATELIER_TYPE.ui,
          fontSize: 11,
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}>
          {progressLabel}
        </div>
        <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{
            flex: 1,
            height: 3,
            background: C.umberHair,
            borderRadius: 99,
            overflow: 'hidden',
          }}>
            <div style={{
              width: (progressFraction * 100) + '%',
              height: '100%',
              background: C.brass,
              transition: 'width 400ms ease',
            }} />
          </div>
          <span style={{ fontSize: 10, opacity: 0.6 }}>
            {currentProgress.lastStep} / {totalSteps}
          </span>
        </div>
      </div>
    </div>
  );
}

function Rail({ route, setRoute, palette }) {
  const C = palette;
  return (
    <nav style={{
      width: 232,
      flexShrink: 0,
      background: C.bone,
      borderRight: `0.6px solid ${C.umberHair}`,
      padding: '28px 18px',
      display: 'flex',
      flexDirection: 'column',
      gap: 22,
      fontFamily: window.ATELIER_TYPE.ui,
      color: C.umberSoft,
      position: 'relative',
      zIndex: 2,
    }}>
      <div style={{ padding: '0 6px' }}>
        <div style={{
          fontFamily: window.ATELIER_TYPE.display,
          fontStyle: 'italic',
          fontWeight: 300,
          fontSize: 28,
          lineHeight: 1,
          color: C.umber,
          letterSpacing: -0.3,
        }}>
          {window.COPY.nav.appName}
        </div>
        <div style={{
          marginTop: 6,
          fontSize: 9,
          letterSpacing: 3.5,
          textTransform: 'uppercase',
          opacity: 0.55,
        }}>
          {window.COPY.nav.version}
        </div>
      </div>

      <div className="atelier-rail-links" style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {NAV_ROUTES.filter((r) => {
          // Hide study routes when their underlying data isn't present.
          // The bundled fallback lesson predates the vulnerability/attackVectors
          // schema; without these checks the rail item appears but the screen
          // shows its empty state.
          if (r.id === 'lesson' || r.id === 'puzzle' || r.id === 'play') {
            return !!(window.LESSON && window.LESSON.id);
          }
          if (r.id === 'targets') {
            return !!(window.LESSON && window.LESSON.vulnerability);
          }
          if (r.id === 'vectors') {
            return !!(window.LESSON && window.LESSON.attackVectors);
          }
          if (r.id === 'overload') {
            return !!(window.LESSON && window.LESSON.overload
              && window.LESSON.overload.overloadedDefenders
              && window.LESSON.overload.overloadedDefenders.length > 0);
          }
          if (r.id === 'ghost') {
            return !!(window.LESSON && window.LESSON.heroRoute
              && window.LESSON.heroRoute.found
              && window.LESSON.heroRoute.hops >= 2);
          }
          return true;
        }).map((r) => {
          // A composite route like 'lesson:pin-001' should highlight the 'lesson' nav item.
          const screenName = route.includes(':') ? route.split(':')[0] : route;
          const active = r.id === screenName;
          return (
            <button
              key={r.id}
              onClick={() => setRoute(r.id)}
              style={{
                appearance: 'none',
                border: 'none',
                background: active ? C.cream : 'transparent',
                color: active ? C.umber : C.umberSoft,
                padding: '10px 14px 11px',
                textAlign: 'left',
                cursor: 'pointer',
                borderRadius: 8,
                display: 'flex',
                alignItems: 'baseline',
                gap: 10,
                fontFamily: 'inherit',
                transition: 'background 220ms ' + window.ATELIER_EASE + ', color 220ms',
                position: 'relative',
              }}
              onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'rgba(42,34,27,0.04)'; }}
              onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
            >
              <span className="atelier-rail-num" style={{
                fontSize: 9, letterSpacing: 2, opacity: 0.5, minWidth: 18,
              }}>{r.num}</span>
              <span style={{ flex: 1 }}>
                <span style={{
                  display: 'block',
                  fontFamily: window.ATELIER_TYPE.display,
                  fontStyle: active ? 'italic' : 'normal',
                  fontWeight: 400,
                  fontSize: 18,
                  lineHeight: 1.1,
                  color: 'inherit',
                }}>{r.label}</span>
                <span className="atelier-rail-sub" style={{
                  display: 'block',
                  fontSize: 10,
                  letterSpacing: 2,
                  textTransform: 'uppercase',
                  opacity: 0.55,
                  marginTop: 3,
                }}>{r.subtitle}</span>
              </span>
              {active && (
                <span style={{
                  position: 'absolute',
                  left: -6, top: '50%',
                  width: 3, height: 18,
                  marginTop: -9,
                  background: C.brassDeep,
                  borderRadius: 2,
                }} />
              )}
            </button>
          );
        })}
      </div>

      <ProgressBox palette={C} />
    </nav>
  );
}

function Topbar({ palette, title, kicker, rightSlot }) {
  const C = palette;
  return (
    <header style={{
      padding: '20px 40px',
      borderBottom: `0.6px solid ${C.umberHair}`,
      display: 'flex',
      alignItems: 'flex-end',
      justifyContent: 'space-between',
      gap: 24,
      background: C.bone,
    }}>
      <div>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui,
          fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase',
          opacity: 0.55,
          color: C.umberSoft,
          marginBottom: 6,
        }}>{kicker}</div>
        <h1 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display,
          fontWeight: 300,
          fontStyle: 'italic',
          fontSize: 30,
          lineHeight: 1,
          color: C.umber,
          letterSpacing: -0.3,
        }}>{title}</h1>
      </div>
      <div>{rightSlot}</div>
    </header>
  );
}

Object.assign(window, { Rail, Topbar, ROUTES });
