/* =========================================================================
   Two canvas layouts: InlineCanvas (chain) and DockedCanvas (journey strip).
   Toggled by the Tweaks panel.
   ========================================================================= */

/* ---------- Shared footer ---------- */
function ToolkitFooter({ currentIdx, flat, current }) {
  return (
    <footer className="app-footer">
      <div className="app-footer__progress">
        <div className="app-footer__progresslabel">
          Section {currentIdx + 1} of {flat.length} · <strong style={{ color: "var(--fg-1)" }}>{current.eyebrow} · {current.title}</strong>
        </div>
        <div className="app-footer__progressbar">
          <div className="app-footer__progressfill" style={{ width: `${((currentIdx + 1) / flat.length) * 100}%` }} />
        </div>
      </div>
      <div className="app-footer__spacer" />
      <div className="app-footer__kbd-hint">
        <kbd>←</kbd><kbd>→</kbd> navigate &nbsp;·&nbsp; <kbd>Tab</kbd> next field &nbsp;·&nbsp; <kbd>Space</kbd> select
      </div>
    </footer>
  );
}

/* =========================================================================
   ContextStrip — prev / current / next cards shown above the chain
   ========================================================================= */
function ContextStrip({ flat, currentIdx, steps, jumpTo }) {
  const prev = currentIdx > 0 ? flat[currentIdx - 1] : null;
  const curr = flat[currentIdx];
  const next = currentIdx < flat.length - 1 ? flat[currentIdx + 1] : null;

  const getStep = (lesson) => steps.find(s => s.id === lesson.stepId);

  const StripCard = ({ lesson, role }) => {
    const step = getStep(lesson);
    const isCurrent = role === "current";
    const flatIdx = flat.findIndex(f => f.id === lesson.id);
    return (
      <button
        className={`ctx-card ctx-card--${role}`}
        onClick={() => jumpTo(flatIdx)}
        style={isCurrent ? { borderColor: step.colorHex } : {}}
        disabled={isCurrent}
      >
        <span className="ctx-card__badge" style={{ background: step.colorHex }}>
          Step {step.number}
        </span>
        <div className="ctx-card__body">
          <span className="ctx-card__eyebrow">{lesson.eyebrow}</span>
          <span className="ctx-card__title">{lesson.title}</span>
        </div>
      </button>
    );
  };

  return (
    <div className="ctx-strip">
      <div className="ctx-strip__inner">
        {prev
          ? <StripCard lesson={prev} role="prev" />
          : <div className="ctx-card ctx-card--empty" />
        }
        <div className="ctx-strip__arrow">›</div>
        <StripCard lesson={curr} role="current" />
        <div className="ctx-strip__arrow">›</div>
        {next
          ? <StripCard lesson={next} role="next" />
          : <div className="ctx-card ctx-card--empty" />
        }
      </div>
    </div>
  );
}

/* =========================================================================
   InlineCanvas — current behaviour: horizontal chain, current is the big card
   ========================================================================= */
function InlineCanvas({
  steps, flat, currentIdx, answers, updateAnswer,
  naState, onToggleNa,
  jumpTo, previewForLesson, currentStep, current,
  canvasRef, activeCardRef, next, prev, onOpenReport,
  showReportBtnInFooter, tocGateMsg
}) {
  return (
    <main className="main-panel">
      <div className="canvas-wrap" ref={canvasRef}>
        <div className="chain">
          {flat.map((lesson, i) => {
            const stepObj = steps.find(s => s.id === lesson.stepId);
            const colorHex = stepObj.colorHex;

            const connector = i > 0 ? (
              <div
                key={`c-${i}`}
                className={`chain__connector ${i <= currentIdx ? "chain__connector--complete" : ""}`}
              />
            ) : null;

            if (i === currentIdx) {
              const isSectionIntro = lesson.type === "section-intro";
              return (
                <React.Fragment key={lesson.id}>
                  {connector}
                  <div className="chain__active-wrap" ref={activeCardRef}>
                    {isSectionIntro
                      ? <SectionIntroCard step={{ colorHex: lesson.colorHex, number: lesson.stepNumber, title: lesson.stepTitle, sectionIntro: lesson.sectionIntro }} />
                      : <LessonCard
                          lesson={lesson}
                          step={stepObj}
                          answers={answers}
                          onChange={updateAnswer}
                          naState={naState}
                          onToggleNa={onToggleNa}
                        />
                    }
                    <div className="chain__card-nav">
                      <Btn variant="ghost" icon="arrow-l" onClick={prev} disabled={currentIdx === 0}>Previous</Btn>
                      {isSectionIntro
                        ? <Btn variant="primary" iconRight="arrow-r" onClick={next}>Begin Step {lesson.stepNumber}</Btn>
                        : currentIdx < flat.length - 1
                          ? <Btn variant="primary" iconRight="arrow-r" onClick={next}>Next section</Btn>
                          : <Btn variant="primary" iconRight="doc" onClick={onOpenReport}>Finish &amp; view report</Btn>
                      }
                    </div>
                    {tocGateMsg && !isSectionIntro && (
                      <div className="toc-gate-warn">
                        <Icon name="warn" size={15} />
                        {tocGateMsg}
                      </div>
                    )}
                  </div>
                </React.Fragment>
              );
            }

            const variant = i < currentIdx ? "complete" : "upcoming";
            return (
              <React.Fragment key={lesson.id}>
                {connector}
                <NodeCard
                  lesson={lesson}
                  variant={variant}
                  colorHex={colorHex}
                  answer={variant === "complete" ? previewForLesson(lesson) : null}
                  onClick={() => jumpTo(i)}
                />
              </React.Fragment>
            );
          })}
        </div>
      </div>

      <ToolkitFooter
        currentIdx={currentIdx}
        flat={flat}
        current={current}
        prev={prev}
        next={next}
        onOpenReport={onOpenReport}
        showReportBtn={showReportBtnInFooter}
      />
    </main>
  );
}

/* =========================================================================
   DockedCanvas — journey strip at top, full-width content below
   ========================================================================= */
function DockedCanvas({
  steps, flat, currentIdx, answers, updateAnswer,
  naState, onToggleNa,
  jumpTo, currentStep, current,
  next, prev, onOpenReport,
  showReportBtnInFooter,
  hideStrip = false
}) {
  // group flat by stepId for the journey strip
  const stepLanes = steps.map(s => ({
    step: s,
    lessons: flat
      .map((l, i) => ({ ...l, flatIdx: i }))
      .filter(l => l.stepId === s.id)
  }));

  // auto-scroll the current step into view in the strip
  const stripRef = useRef(null);
  useEffect(() => {
    const strip = stripRef.current;
    if (!strip) return;
    const el = strip.querySelector(`.j-dot--current`);
    if (el) {
      const rect = el.getBoundingClientRect();
      const stripRect = strip.getBoundingClientRect();
      if (rect.left < stripRect.left || rect.right > stripRect.right) {
        const target = el.offsetLeft - strip.clientWidth / 2 + el.clientWidth / 2;
        strip.scrollTo({ left: target, behavior: "smooth" });
      }
    }
  }, [currentIdx]);

  return (
    <main className="main-panel main-panel--docked">

      {/* Journey strip — hidden when sidebar is present */}
      {!hideStrip && (
        <div className="journey-strip">
          <div className="journey-strip__title">Your learning path · click any section to jump</div>
          <div className="journey-strip__lanes" ref={stripRef}>
            {stepLanes.map((lane, li) => (
              <React.Fragment key={lane.step.id}>
                <div className="j-step">
                  <div className="j-step__head">
                    <span className="j-step__num" style={{ background: lane.step.colorHex }}>{lane.step.number}</span>
                    <span className="j-step__title">{lane.step.title}</span>
                  </div>
                  <div className="j-step__dots">
                    {lane.lessons.map(lsn => {
                      const status =
                        lsn.flatIdx < currentIdx ? "done" :
                        lsn.flatIdx === currentIdx ? "current" : "upcoming";
                      return (
                        <button
                          key={lsn.id}
                          className={`j-dot j-dot--${status}`}
                          onClick={() => jumpTo(lsn.flatIdx)}
                          title={`${lsn.eyebrow} — ${lsn.title}`}
                        >
                          <span className="j-dot__circle">
                            {status === "done" ? <Icon name="check" size={10} /> : lsn.id.split(".")[1]}
                          </span>
                          <span className="j-dot__tooltip">{lsn.eyebrow}: {lsn.title}</span>
                        </button>
                      );
                    })}
                  </div>
                </div>
                {li < stepLanes.length - 1 && <div className="j-step__connector" />}
              </React.Fragment>
            ))}
          </div>
        </div>
      )}

      {/* Content area — split: reading on left, reflection (sticky) on right */}
      <div className="docked-content">
        <div className="docked-card">
          <div className="docked-card__topbar" style={{ background: currentStep.colorHex }} />
          <div className="docked-card__inner" style={{ display: "flex", flexDirection: "column", gap: "40px" }}>
            <div className="docked-card__reading">
              <div className="lesson-card__eyebrow-row">
                <span className="lesson-card__stepbadge" style={{ background: currentStep.colorHex }}>
                  Step {currentStep.number} · {currentStep.title}
                </span>
                <span className="lesson-card__step-of">{current.eyebrow}</span>
              </div>
              <h2>{current.title}</h2>
              <p className="lesson-card__intro">{current.intro}</p>
              <LessonBody blocks={current.body || []} colorHex={currentStep.colorHex} />
              {current.callout && <Callout data={current.callout} />}
            </div>

            <aside className="docked-card__sticky" style={{ position: "static", borderTop: "1px solid var(--border-soft)", paddingTop: "36px" }}>
              <Reflection
                lesson={current}
                answers={answers}
                onChange={updateAnswer}
                naState={naState}
                onToggleNa={onToggleNa}
              />
            </aside>
          </div>
        </div>
      </div>

      <ToolkitFooter
        currentIdx={currentIdx}
        flat={flat}
        current={current}
        prev={prev}
        next={next}
        onOpenReport={onOpenReport}
        showReportBtn={showReportBtnInFooter}
      />
    </main>
  );
}

Object.assign(window, { InlineCanvas, DockedCanvas, ToolkitFooter });
