// atelier-screens-g.jsx — Path screens (Block B).
//
// Two screens here:
//   PathListScreen   — /#paths        — all curated paths
//   PathDetailScreen — /#path:<pathId> — one path's vertical lesson list
//
// Both read paths from window.PathData (loaded by path-data.js) and
// per-user progress from window.DataLayer (the F.2.5 adapter).
//
// Per the post-review revisions in docs/BLOCK_B_PEDAGOGY.md:
//   - No lock icons. No completion checks. No percent.
//   - Quiet typography: completed lessons in umber, upcoming in
//     umberSoft, current with a brass underline.
//   - "mark as done" link on every lesson card (replaces the old
//     "I already know this — skip" copy).

const { useState: useSG, useEffect: useEG, useMemo: useMG } = React;

function PathListScreen({ palette, setRoute }) {
  const C = palette;
  const isMobile = window.useBreakpoint().isMobile;
  const [pathsData, setPathsData] = useSG(null);
  const [progressTick, setProgressTick] = useSG(0);

  useEG(() => {
    let cancelled = false;
    window.PathData.load().then((data) => { if (!cancelled) setPathsData(data); });
    const onChanged = () => setProgressTick((t) => t + 1);
    window.addEventListener('progressChanged', onChanged);
    return () => { cancelled = true; window.removeEventListener('progressChanged', onChanged); };
  }, []);

  const userProgress = useMG(() => (window.getProgress && window.getProgress()) || {}, [progressTick]);

  if (!pathsData) {
    return (
      <div style={{ flex: 1, padding: 48, color: C.umberSoft, fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic' }}>
        Loading paths…
      </div>
    );
  }

  const themePaths = pathsData.paths.filter((p) => p.kind === 'theme');
  const piecePaths = pathsData.paths.filter((p) => p.kind === 'piece');

  return (
    <div style={{ flex: 1, height: '100%', overflow: 'auto', background: C.bone }}>
      <section className="atelier-section-pad" style={{ padding: isMobile ? '40px 20px 12px' : '56px 48px 12px' }}>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase', opacity: 0.55, color: C.umberSoft, marginBottom: 8,
        }}>The full collection of paths</div>
        <h1 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: isMobile ? 36 : 48, lineHeight: 1.05, color: C.umber, letterSpacing: -0.5,
        }}>A path to walk.</h1>
        <p style={{ marginTop: 14, fontFamily: window.ATELIER_TYPE.display, fontSize: 17, lineHeight: 1.5, color: C.umberSoft, maxWidth: 600 }}>
          Each path is a sequence of positions chosen to climb gently. Theme paths walk a single tactic from its simplest to its most quietly broken form. Piece paths follow one piece across the whole repertoire.
        </p>
      </section>

      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 16px' : '32px 48px 16px' }}>
        <h2 style={{
          margin: '0 0 18px',
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: 22, color: C.umber, letterSpacing: -0.2,
        }}>By theme</h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 18 }}>
          {themePaths.map((p) => <PathCard key={p.id} path={p} palette={C} userProgress={userProgress} setRoute={setRoute} />)}
        </div>
      </section>

      <section className="atelier-section-pad" style={{ padding: isMobile ? '16px 20px 48px' : '24px 48px 56px' }}>
        <h2 style={{
          margin: '0 0 18px',
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: 22, color: C.umber, letterSpacing: -0.2,
        }}>By piece</h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 18 }}>
          {piecePaths.map((p) => <PathCard key={p.id} path={p} palette={C} userProgress={userProgress} setRoute={setRoute} />)}
        </div>
      </section>
    </div>
  );
}

function PathCard({ palette, path, userProgress, setRoute }) {
  const C = palette;
  const prog = window.PathData.computeProgress(path, userProgress);
  const hasProgress = prog.done > 0;

  return (
    <button
      onClick={() => setRoute('path:' + path.id)}
      style={{
        appearance: 'none',
        textAlign: 'left',
        cursor: 'pointer',
        background: C.cream,
        border: '0.6px solid ' + C.umberHair,
        borderRadius: 14,
        padding: 22,
        boxShadow: '0 14px 28px -22px rgba(42,34,27,0.35)',
        fontFamily: 'inherit',
        transition: 'transform 220ms ' + window.ATELIER_EASE + ', border-color 220ms',
      }}
      onMouseEnter={(e) => { e.currentTarget.style.borderColor = C.brassDeep; }}
      onMouseLeave={(e) => { e.currentTarget.style.borderColor = C.umberHair; }}
    >
      <div style={{
        fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
        textTransform: 'uppercase', color: C.umberSoft, opacity: 0.7, marginBottom: 6,
      }}>{path.kind === 'theme' ? 'Theme path' : 'Piece path'}</div>
      <div style={{
        fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', fontWeight: 300,
        fontSize: 22, color: C.umber, letterSpacing: -0.3, lineHeight: 1.15,
      }}>{path.name}</div>
      <p style={{
        margin: '8px 0 14px',
        fontFamily: window.ATELIER_TYPE.display, fontSize: 14, lineHeight: 1.5,
        color: C.umberSoft,
      }}>{path.kicker}</p>
      <div style={{
        fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 2,
        textTransform: 'uppercase', color: C.umberFaint,
      }}>
        {hasProgress ? prog.done + ' of ' + prog.total + ' done' : prog.total + ' positions'}
      </div>
    </button>
  );
}

function PathDetailScreen({ palette, setRoute, pathId }) {
  const C = palette;
  const isMobile = window.useBreakpoint().isMobile;
  const [pathsData, setPathsData] = useSG(null);
  const [lessonIndex, setLessonIndex] = useSG(window.LESSON_INDEX || null);
  const [progressTick, setProgressTick] = useSG(0);

  useEG(() => {
    let cancelled = false;
    window.PathData.load().then((data) => { if (!cancelled) setPathsData(data); });
    const onIdx = (e) => setLessonIndex(e.detail);
    const onProg = () => setProgressTick((t) => t + 1);
    window.addEventListener('lessonIndexLoaded', onIdx);
    window.addEventListener('progressChanged', onProg);
    if (window.LESSON_INDEX) setLessonIndex(window.LESSON_INDEX);
    return () => {
      cancelled = true;
      window.removeEventListener('lessonIndexLoaded', onIdx);
      window.removeEventListener('progressChanged', onProg);
    };
  }, []);

  const userProgress = useMG(() => (window.getProgress && window.getProgress()) || {}, [progressTick]);

  const path = pathsData ? pathsData.paths.find((p) => p.id === pathId) : null;
  const lessonMap = useMG(() => {
    const m = {};
    if (lessonIndex && lessonIndex.lessons) {
      for (const l of lessonIndex.lessons) m[l.id] = l;
    }
    return m;
  }, [lessonIndex]);

  if (!pathsData) {
    return <div style={{ flex: 1, padding: 48, color: C.umberSoft, fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic' }}>Loading…</div>;
  }
  if (!path) {
    return (
      <div style={{ flex: 1, padding: 48 }}>
        <h2 style={{ fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', color: C.umber }}>Path not found.</h2>
        <button style={window.ghostBtn(C)} onClick={() => setRoute('paths')}>See all paths</button>
      </div>
    );
  }

  const prog = window.PathData.computeProgress(path, userProgress);

  return (
    <div style={{ flex: 1, height: '100%', overflow: 'auto', background: C.bone }}>
      <section className="atelier-section-pad" style={{ padding: isMobile ? '40px 20px 12px' : '56px 48px 12px' }}>
        <button
          onClick={() => setRoute('paths')}
          style={{
            appearance: 'none', background: 'transparent', border: 'none',
            padding: 0, cursor: 'pointer', marginBottom: 14,
            fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
            textTransform: 'uppercase', color: C.umberSoft, opacity: 0.7,
          }}
        >← All paths</button>
        <div style={{
          fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 3.5,
          textTransform: 'uppercase', opacity: 0.55, color: C.umberSoft, marginBottom: 8,
        }}>{path.kind === 'theme' ? 'Theme path' : 'Piece path'} · {prog.done} of {prog.total}</div>
        <h1 style={{
          margin: 0,
          fontFamily: window.ATELIER_TYPE.display, fontWeight: 300, fontStyle: 'italic',
          fontSize: isMobile ? 36 : 48, lineHeight: 1.05, color: C.umber, letterSpacing: -0.5,
        }}>{path.name}</h1>
        <p style={{ marginTop: 14, fontFamily: window.ATELIER_TYPE.display, fontSize: 17, lineHeight: 1.5, color: C.umberSoft, maxWidth: 600 }}>
          {path.kicker}
        </p>
      </section>

      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 12px' : '24px 48px 12px' }}>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {path.lessonIds.map((lessonId, i) => {
            const meta = lessonMap[lessonId];
            const entry = userProgress[lessonId];
            const isComplete = !!(entry && entry.complete);
            const isCurrent = i === prog.currentIndex;
            return (
              <PathLessonRow
                key={lessonId}
                palette={C}
                index={i}
                lessonId={lessonId}
                meta={meta}
                complete={isComplete}
                current={isCurrent}
                onOpen={() => {
                  if (window.DataLayer && window.DataLayer.setActivePath) {
                    window.DataLayer.setActivePath(pathId);
                  }
                  setRoute('lesson:' + lessonId);
                }}
                onMarkDone={() => {
                  if (window.DataLayer && window.DataLayer.recordAttempt) {
                    window.DataLayer.recordAttempt({ lessonId, phase: 'solve', outcome: 'correct', completed: true });
                  }
                }}
              />
            );
          })}
        </div>
      </section>

      <section className="atelier-section-pad" style={{ padding: isMobile ? '24px 20px 48px' : '24px 48px 56px' }}>
        <h2 style={{
          margin: '0 0 8px',
          fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', fontWeight: 300,
          fontSize: 18, color: C.umberSoft, letterSpacing: -0.2,
        }}>About this path</h2>
        <p style={{ margin: 0, fontFamily: window.ATELIER_TYPE.display, fontSize: 15, lineHeight: 1.6, color: C.umberSoft, maxWidth: 720 }}>
          {path.rationale}
        </p>
      </section>
    </div>
  );
}

function PathLessonRow({ palette, index, lessonId, meta, complete, current, onOpen, onMarkDone }) {
  const C = palette;
  const labelColor = complete ? C.umber : (current ? C.umber : C.umberSoft);
  const title = meta ? (window.creativeTitle ? window.creativeTitle(meta.id) : meta.title) : lessonId;
  const themeLabel = meta ? meta.theme : '';
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 18,
      padding: '14px 0',
      borderBottom: '0.6px solid ' + C.umberHair,
    }}>
      <div style={{
        flexShrink: 0, width: 36, textAlign: 'right',
        fontFamily: window.ATELIER_TYPE.ui, fontSize: 11,
        color: C.umberFaint, letterSpacing: 2,
        paddingTop: 3,
      }}>{String(index + 1).padStart(2, '0')}</div>
      <button
        onClick={onOpen}
        style={{
          appearance: 'none', background: 'transparent', border: 'none', padding: 0,
          textAlign: 'left', cursor: 'pointer', flex: 1, fontFamily: 'inherit',
        }}
      >
        <div style={{
          fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic', fontWeight: 300,
          fontSize: 19, color: labelColor, lineHeight: 1.2,
          borderBottom: current ? '0.6px solid ' + C.brassDeep : 'none',
          display: 'inline',
          paddingBottom: current ? 2 : 0,
        }}>{title}</div>
        {themeLabel && (
          <div style={{
            marginTop: 4,
            fontFamily: window.ATELIER_TYPE.ui, fontSize: 10, letterSpacing: 2,
            textTransform: 'uppercase', color: C.umberFaint,
          }}>{themeLabel}</div>
        )}
      </button>
      {!complete && (
        <button
          onClick={onMarkDone}
          style={{
            appearance: 'none', background: 'transparent', border: 'none', padding: 0,
            cursor: 'pointer',
            fontFamily: window.ATELIER_TYPE.display, fontStyle: 'italic',
            fontSize: 13, color: C.umberFaint,
            opacity: 0.8,
            textDecoration: 'underline', textUnderlineOffset: 3,
            textDecorationColor: C.umberHair,
          }}
          title="Mark this lesson as done without playing it"
        >mark as done</button>
      )}
    </div>
  );
}

Object.assign(window, { PathListScreen, PathDetailScreen });
