/**
 * Home page: the principles of each modality, a body figure divided into seven
 * stations, a progress tracker and the self-test.
 *
 * Every way in opens the same lesson picker. Which lesson belongs where comes
 * from data/body-map.js, never from this file. The figure is drawn for the
 * pointer; the station buttons beside it are the keyboard and screen-reader
 * route to the same pickers, so the page does not depend on the drawing.
 */

(function () {
'use strict';

const { useState, useEffect, useRef } = React;

const isDone = (item) => window.Progress.isLessonComplete(item.lesson.id);
const doneCount = (items) => items.filter(isDone).length;

function progressState(items) {
  const done = doneCount(items);
  if (!items.length) return 'empty';
  if (done === items.length) return 'done';
  return done > 0 ? 'started' : 'new';
}

/** Lessons per modality, in display order, skipping modalities with none. */
function modalityCounts(items) {
  return window.BodyMap.MODALITY_ORDER
    .map((key) => ({ key, label: window.BodyMap.MODALITIES[key], count: items.filter((item) => item.modality === key).length }))
    .filter((entry) => entry.count > 0);
}

function Ring({ done, total }) {
  const radius = 52;
  const length = 2 * Math.PI * radius;
  const ratio = total ? done / total : 0;
  return (
    <svg className="ring" viewBox="0 0 120 120" role="img" aria-label={`הושלמו ${done} מתוך ${total} שיעורים`}>
      <circle className="ring__track" cx="60" cy="60" r={radius} />
      {ratio > 0 && (
        <circle
          className="ring__fill"
          cx="60"
          cy="60"
          r={radius}
          strokeDasharray={`${length * ratio} ${length}`}
          transform="rotate(-90 60 60)"
        />
      )}
      <text className="ring__value" x="60" y="58" textAnchor="middle">{Math.round(ratio * 100)}%</text>
      <text className="ring__label" x="60" y="78" textAnchor="middle">{done}/{total}</text>
    </svg>
  );
}

/**
 * The lesson picker. A native <dialog> gives the focus trap, Escape and the
 * inert background for free. Lessons are grouped by module, and the modality
 * chips narrow the list without closing it.
 */
function LessonPicker({ title, intro, items, withFilter, onClose, onOpenLesson }) {
  const ref = useRef(null);
  const [filter, setFilter] = useState('all');

  useEffect(() => {
    const dialog = ref.current;
    if (dialog && !dialog.open) dialog.showModal();
    return () => {
      if (dialog && dialog.open) dialog.close();
    };
  }, []);

  const counts = modalityCounts(items);
  const shown = filter === 'all' ? items : items.filter((item) => item.modality === filter);
  const groups = [];
  shown.forEach((item) => {
    const last = groups[groups.length - 1];
    if (last && last.region.id === item.region.id) last.items.push(item);
    else groups.push({ region: item.region, items: [item] });
  });

  return (
    <dialog
      ref={ref}
      className="picker"
      aria-labelledby="picker-title"
      onClose={onClose}
      onClick={(event) => {
        // A click on the backdrop lands on the dialog element itself.
        if (event.target === ref.current) onClose();
      }}
    >
      <div className="picker__head">
        <div>
          <h2 id="picker-title" className="picker__title">{title}</h2>
          <p className="picker__meta">
            {items.length ? `הושלמו ${doneCount(items)} מתוך ${items.length} שיעורים` : 'עדיין אין שיעורים'}
            {intro ? ` · ${intro}` : ''}
          </p>
        </div>
        <button type="button" className="btn btn--ghost btn--sm picker__close" onClick={onClose}>
          סגירה
        </button>
      </div>

      {withFilter && counts.length > 1 && (
        <div className="picker__filters" role="group" aria-label="סינון לפי סוג בדיקה">
          <button type="button" className="filter-chip" aria-pressed={filter === 'all'} onClick={() => setFilter('all')}>
            הכול <span className="filter-chip__count">{items.length}</span>
          </button>
          {counts.map((entry) => (
            <button
              key={entry.key}
              type="button"
              className="filter-chip"
              aria-pressed={filter === entry.key}
              onClick={() => setFilter(entry.key)}
            >
              {entry.label} <span className="filter-chip__count">{entry.count}</span>
            </button>
          ))}
        </div>
      )}

      <div className="picker__body">
        {!items.length && (
          <p className="picker__empty">
            עדיין אין שיעורים לאזור הזה. כשיתווספו, הם יופיעו כאן.
          </p>
        )}
        {groups.map((group) => (
          <section key={`${group.region.id}-${group.items[0].lesson.id}`} className="picker__group">
            <h3 className="picker__group-title">{group.region.title}</h3>
            <ul className="picker__list">
              {group.items.map((item) => {
                const done = isDone(item);
                return (
                  <li key={item.lesson.id}>
                    <button type="button" className="picker__lesson" onClick={() => onOpenLesson(item.lesson.id)}>
                      <span className={`picker__dot ${done ? 'picker__dot--done' : ''}`} aria-hidden="true">
                        {done ? '✓' : ''}
                      </span>
                      <span className="picker__lesson-text">
                        <span className="picker__lesson-title">{item.lesson.title}</span>
                        <span className="picker__lesson-sub">
                          {item.lesson.duration}
                          {done ? ' · הושלם' : ''}
                        </span>
                      </span>
                      {item.modality && (
                        <span className="chip chip--neutral">{window.BodyMap.MODALITIES[item.modality]}</span>
                      )}
                      <span className="picker__go" aria-hidden="true">←</span>
                    </button>
                  </li>
                );
              })}
            </ul>
          </section>
        ))}
      </div>
    </dialog>
  );
}

/**
 * An abstract figure built from separate flat blocks, one or two per station.
 * It is decoration for assistive technology: the station buttons carry the
 * names, the counts and the keyboard focus.
 */
function BodyFigure({ stations, hot, onHot, onPick }) {
  const part = (id, shape) => {
    const station = stations.find((entry) => entry.id === id);
    return (
      <g
        key={id}
        className={`figure__part figure__part--${station.state} ${hot === id ? 'figure__part--hot' : ''}`}
        onMouseEnter={() => onHot(id)}
        onMouseLeave={() => onHot(null)}
        onClick={() => onPick(id)}
      >
        {shape}
      </g>
    );
  };

  return (
    <svg className="figure" viewBox="0 0 300 560" aria-hidden="true" focusable="false">
      {part('head', <circle cx="150" cy="50" r="36" />)}
      {part('neck', <rect x="134" y="92" width="32" height="22" rx="8" />)}
      {part(
        'upper-limbs',
        <>
          <rect x="40" y="124" width="34" height="196" rx="17" transform="rotate(7 57 124)" />
          <rect x="226" y="124" width="34" height="196" rx="17" transform="rotate(-7 243 124)" />
        </>
      )}
      {part('chest', <path d="M102 120 H198 Q214 120 216 136 L220 206 H80 L84 136 Q86 120 102 120 Z" />)}
      {part('abdomen', <path d="M80 214 H220 L216 290 H84 Z" />)}
      {part('pelvis', <path d="M84 298 H216 L224 352 Q225 366 211 366 H89 Q75 366 76 352 Z" />)}
      {part(
        'lower-limbs',
        <>
          <rect x="88" y="374" width="56" height="174" rx="24" />
          <rect x="156" y="374" width="56" height="174" rx="24" />
        </>
      )}
    </svg>
  );
}

/** Modules of one evidence group, each with the lessons of that kind in it. */
function EvidenceList({ groups }) {
  return (
    <ul className="evidence">
      {groups.map((group) => (
        <li key={group.region.id}>
          <strong>{group.region.title}:</strong>{' '}
          {group.lessons.map((lesson) => lesson.title).join(' · ')}
        </li>
      ))}
    </ul>
  );
}

function HomePage({ regions, picker, onPick, onClosePicker, onOpenLesson, onCompare, onReset, signedIn, review }) {
  const map = window.BodyMap;
  const [hot, setHot] = useState(null);

  const stations = map.STATIONS.map((station) => {
    const items = map.lessonsFor(station.id);
    return { ...station, items, done: doneCount(items), state: progressState(items) };
  });
  const principles = map.PRINCIPLES.map((principle) => {
    const items = map.principleLessons(principle.id);
    return { ...principle, items, done: doneCount(items), state: progressState(items) };
  });
  const exam = map.examLessons();

  const allLessons = regions.flatMap((region) => region.lessons);
  const totalDone = allLessons.filter((lesson) => window.Progress.isLessonComplete(lesson.id)).length;
  const evidence = window.Coverage.lessonEvidence();

  const hotStation = stations.find((station) => station.id === hot);
  const caption = hotStation
    ? hotStation.items.length
      ? `${hotStation.name}: ${modalityCounts(hotStation.items).map((entry) => `${entry.label} ${entry.count}`).join(' · ')}`
      : `${hotStation.name}: עדיין אין שיעורים`
    : 'בחר אזור בגוף כדי לראות את כל הבדיקות והשיעורים שלו';

  let pickerProps = null;
  if (picker && picker.kind === 'station') {
    const station = stations.find((entry) => entry.id === picker.id);
    if (station) pickerProps = { title: station.name, items: station.items, withFilter: true, intro: 'בחר שיעור' };
  } else if (picker && picker.kind === 'principles') {
    const principle = principles.find((entry) => entry.id === picker.id);
    if (principle) pickerProps = { title: principle.name, items: principle.items, withFilter: false, intro: principle.blurb };
  } else if (picker && picker.kind === 'exam') {
    pickerProps = { title: 'בחן את עצמי', items: exam, withFilter: false, intro: 'מבחני תרגול, ציון עובר 70%' };
  }

  return (
    <div className="home animate-in">
      <header className="home__intro">
        <h1 className="home__title">מערך למידה דיגיטלי — דימות רפואי</h1>
        <p className="home__lead">
          מתחילים בעקרונות של כל שיטת הדמיה, ואז בוחרים אזור בגוף ולומדים את הבדיקה שרוצים.
        </p>
      </header>

      {review && (
        <div className="callout callout--note review-banner" role="status">
          <span style={{ flex: 1 }}>
            <strong>מצב סקירה פעיל.</strong> אפשר לקפוץ לכל שלב בלחיצה על פס ההתקדמות, ובכל שלב
            מוצגים מפתח התשובות והסדרה שמאחוריו. הלומדים לא רואים את זה.
            {window.Curriculum.problems.length > 0
              ? ` נמצאו ${window.Curriculum.problems.length} בעיות תוכן — פירוט בתחתית העמוד.`
              : ' בדיקת התוכן האוטומטית לא מצאה בעיות.'}
          </span>
        </div>
      )}

      <section aria-labelledby="principles-heading" className="home__section">
        <h2 id="principles-heading" className="home__heading">עקרונות לפי שיטת הדמיה</h2>
        <div className="principles">
          {principles.map((principle) => (
            <button
              key={principle.id}
              type="button"
              className={`principle principle--${principle.state}`}
              onClick={() => onPick('principles', principle.id)}
            >
              <span className="principle__mark" dir="ltr" aria-hidden="true">{principle.modality}</span>
              <span className="principle__name">{principle.name}</span>
              <span className="principle__blurb">{principle.blurb}</span>
              <span className="gauge" aria-hidden="true">
                <span className="gauge__fill" style={{ transform: `scaleX(${principle.items.length ? principle.done / principle.items.length : 0})` }} />
              </span>
              <span className="principle__count">
                {principle.done} מתוך {principle.items.length} שיעורים
              </span>
            </button>
          ))}
        </div>
      </section>

      <div className="home__stage">
        <section aria-labelledby="body-heading" className="card bodymap">
          <h2 id="body-heading" className="home__heading">לימוד לפי אזור בגוף</h2>
          <div className="bodymap__grid">
            <div className="bodymap__figure">
              <BodyFigure stations={stations} hot={hot} onHot={setHot} onPick={(id) => onPick('station', id)} />
              <p className="bodymap__caption" aria-hidden="true">{caption}</p>
            </div>
            <ul className="stations">
              {stations.map((station) => (
                <li key={station.id}>
                  <button
                    type="button"
                    className={`station station--${station.state} ${hot === station.id ? 'station--hot' : ''}`}
                    onClick={() => onPick('station', station.id)}
                    onMouseEnter={() => setHot(station.id)}
                    onMouseLeave={() => setHot(null)}
                    onFocus={() => setHot(station.id)}
                    onBlur={() => setHot(null)}
                  >
                    <span className="station__name">{station.name}</span>
                    <span className="station__count">
                      {station.items.length ? `${station.done}/${station.items.length}` : 'בקרוב'}
                    </span>
                    <span className="gauge" aria-hidden="true">
                      <span
                        className="gauge__fill"
                        style={{ transform: `scaleX(${station.items.length ? station.done / station.items.length : 0})` }}
                      />
                    </span>
                  </button>
                </li>
              ))}
            </ul>
          </div>

          <div className="selftest">
            <div>
              <h3 className="selftest__title">בחן את עצמי</h3>
              <p className="selftest__text">
                {exam.length} מבחני תרגול מסכמים. הושלמו {doneCount(exam)} מתוך {exam.length}.
              </p>
            </div>
            <button type="button" className="btn btn--primary" onClick={() => onPick('exam', null)}>
              למבחנים
            </button>
          </div>
        </section>

        <aside className="card tracker" aria-labelledby="tracker-heading">
          <h2 id="tracker-heading" className="home__heading">ההתקדמות שלי</h2>
          <Ring done={totalDone} total={allLessons.length} />
          <p className="tracker__summary">
            השלמת {totalDone} מתוך {allLessons.length} שיעורים
          </p>

          <h3 className="tracker__sub">עקרונות</h3>
          <ul className="tracker__list">
            {principles.map((principle) => (
              <li key={principle.id} className="tracker__row">
                <span>{principle.name}</span>
                <span className="tracker__num">{principle.done}/{principle.items.length}</span>
              </li>
            ))}
          </ul>

          <h3 className="tracker__sub">אזורי הגוף</h3>
          <ul className="tracker__list">
            {stations.map((station) => (
              <li key={station.id} className="tracker__row">
                <span>{station.name}</span>
                <span className="tracker__num">
                  {station.items.length ? `${station.done}/${station.items.length}` : '—'}
                </span>
              </li>
            ))}
          </ul>
          <p className="tracker__note">
            שיעור שמופיע בשני אזורים נספר בכל אחד מהם. הסיכום למעלה סופר כל שיעור פעם אחת.
          </p>
        </aside>
      </div>

      <div className="card comparison-entry">
        <div>
          <h2>השוואת תקין מול פתולוגי</h2>
          <p>בחר איבר והשווה נבדק ביקורת למקרה מחלה באותו איבר. בכל צד אפשר לגלול ולשנות את החלון בנפרד.</p>
        </div>
        <button type="button" className="btn btn--secondary" onClick={onCompare}>פתיחת השוואה</button>
      </div>

      <details className="card home__about">
        <summary>באילו שיעורים המערך מראה את הממצא, ובאילו לא</summary>
        <div className="prose" style={{ fontSize: 'var(--text-sm)' }}>
          <p>
            המערך מראה ממצא רק כשיש לו על מה להסתמך: סימון של רדיולוג, או תיאור של מי שצילם את
            התמונה. לכן שיעורים שיש בהם מקרי מחלה מתחלקים לשלושה סוגים.
          </p>

          <h3>מראים את הממצא, ובודקים אותך מולו</h3>
          <p>
            רדיולוג סימן את הממצא על הסריקה. אתה מחפש אותו בעצמך, ואז המערך מראה לך היכן הוא.
          </p>
          <EvidenceList groups={evidence.marked} />

          <h3>מראים את הממצא לפי המקור</h3>
          <p>
            באולטרסאונד, מי שצילם את התמונה כתב מה רואים בה או סימן את הנגע. השיעור מוסר זאת כפי
            שנכתב במקור.
          </p>
          <EvidenceList groups={evidence.source} />

          <h3>לא מראים היכן הממצא</h3>
          <p>
            על הנבדקים בשיעורים האלה ידוע רק מאיזו קבוצת חולים הם הגיעו. אין דוח ואין סימון, ולכן
            המערך אינו אומר מה נמצא בסריקה. מתרגלים בהם סדר סקירה או טכניקה. כדי שיראו את הממצא,
            רדיולוג צריך לעבור על המקרים ולכתוב מה רואים בכל אחד.
          </p>
          <EvidenceList groups={evidence.unmarked} />

          <p>
            בשאר השיעורים אין מקרי מחלה. הם עוסקים בעקרונות ובאנטומיה תקינה. המערך אינו כלי אבחון
            ואינו תחליף להכשרה קלינית מוסמכת.
          </p>
        </div>
      </details>

      {window.Curriculum.problems.length > 0 && (
        <div className="callout callout--warn" style={{ marginTop: 'var(--space-5)' }}>
          <strong className="callout__title">אזהרות תוכן ({window.Curriculum.problems.length})</strong>
          <ul style={{ paddingInlineStart: 'var(--space-5)', fontSize: 'var(--text-xs)' }}>
            {window.Curriculum.problems.map((problem, index) => (
              <li key={index}>{problem}</li>
            ))}
          </ul>
        </div>
      )}

      <div className="home__footer">
        <button type="button" className="btn btn--ghost btn--sm" onClick={onReset}>
          {signedIn ? 'איפוס ההתקדמות שלי' : 'איפוס התקדמות'}
        </button>
        <a className="btn btn--ghost btn--sm" href="tests/index.html">הרצת בדיקות</a>
      </div>

      {pickerProps && (
        <LessonPicker
          key={`${picker.kind}-${picker.id || ''}`}
          {...pickerProps}
          onClose={onClosePicker}
          onOpenLesson={onOpenLesson}
        />
      )}
    </div>
  );
}

window.HomePage = HomePage;

})();
