/* pages-inner.jsx — Kurse, KW-Plan, Checkliste, 7-Tage-Plan, Shop */

/* persistent state helper */
function useStore(key, initial) {
  const [val, setVal] = useState(() => {
    try { const r = localStorage.getItem(key); return r ? JSON.parse(r) : initial; }
    catch (e) { return initial; }
  });
  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(val)); } catch (e) {}
  }, [key, val]);
  return [val, setVal];
}

function PageHeader({ eyebrow, title, lead, children }) {
  return (
    <div className="page-head">
      <div className="wrap">
        <span className="eyebrow">{eyebrow}</span>
        <h1>{title}</h1>
        {lead && <p className="page-head__lead">{lead}</p>}
        {children}
      </div>
    </div>
  );
}

/* ============================== Kurse ============================== */
function KursePage({ onNav }) {
  return (
    <main>
      <Breadcrumb trail={[{ label: 'Start', id: 'start' }, { label: 'Kursübersicht' }]} onNav={onNav} />
      <PageHeader eyebrow="Kursübersicht" title="Kurse & Vorbereitung"
        lead="Vier Bereiche begleiten dich von der Anmeldung bis zum Dienststart. Jeder Kurs ist in kurze Einheiten gegliedert." />
      <div className="wrap section" style={{ paddingTop: '2rem' }}>
        {COURSE_CATEGORIES.map(cat => (
          <section key={cat.id} className="course-cat" data-tint={cat.tint}>
            <div className="course-cat__head">
              <span className="course-cat__icon"><Icon name={cat.icon} size={24} /></span>
              <div>
                <h2>{cat.label}</h2>
                <p className="muted">{cat.blurb}</p>
              </div>
              <span className="chip chip--mono course-cat__count">{cat.courses.length} Kurse</span>
            </div>
            <div className="course-list">
              {cat.courses.map((c, i) => (
                <article key={i} className="course-row card">
                  <span className="course-row__bar" />
                  <div className="course-row__main">
                    <div className="course-row__title">
                      <h3>{c.t}</h3>
                      {c.tag && <span className={`chip ${c.tag === 'Pflicht' ? 'chip--warn' : c.tag === 'Neu' ? 'chip--ok' : ''}`}>{c.tag}</span>}
                    </div>
                    <div className="course-row__meta mono">
                      <span><Icon name="target" size={14} /> {c.lvl}</span>
                      <span><Icon name="layers" size={14} /> {c.units} Einheiten</span>
                      <span><Icon name="clock" size={14} /> {c.dur}</span>
                    </div>
                  </div>
                  <button className="btn btn--ghost course-row__cta">
                    Ansehen <Icon name="arrowRight" size={16} />
                  </button>
                </article>
              ))}
            </div>
          </section>
        ))}
      </div>
    </main>
  );
}

/* ============================== KW-Plan ============================== */
function KwPlanPage({ onNav }) {
  const [done, setDone] = useStore('rs.kw.done', {});
  const allTasks = KW_PLAN.flatMap(w => w.tasks.map(t => t.id));
  const doneCount = allTasks.filter(id => done[id]).length;
  const toggle = (id) => setDone(d => ({ ...d, [id]: !d[id] }));

  return (
    <main>
      <Breadcrumb trail={[{ label: 'Start', id: 'start' }, { label: 'KW-Plan' }]} onNav={onNav} />
      <PageHeader eyebrow="KW-Plan & Kalender" title="12-Wochen-Vorbereitung"
        lead="Wochenweise Aufgaben bis zum Dienststart. Haken setzen — der Fortschritt wird automatisch gespeichert.">
        <div className="page-progress">
          <div className="page-progress__row">
            <span className="mono">{doneCount} / {allTasks.length} Aufgaben erledigt</span>
            <span className="mono">{Math.round((doneCount / allTasks.length) * 100)} %</span>
          </div>
          <ProgressBar value={doneCount} max={allTasks.length} />
        </div>
      </PageHeader>

      <div className="wrap section" style={{ paddingTop: '2rem' }}>
        <div className="kw-grid">
          {KW_PLAN.map(w => {
            const wd = w.tasks.filter(t => done[t.id]).length;
            const complete = wd === w.tasks.length;
            return (
              <article key={w.kw} className={`kw-card card ${complete ? 'is-complete' : ''}`} data-tint={w.tint}>
                <header className="kw-card__head">
                  <span className="kw-card__kw mono">KW {w.kw}</span>
                  <span className="kw-card__phase">{w.phase}</span>
                  {complete && <span className="kw-card__check"><Icon name="check" size={14} /></span>}
                </header>
                <h3 className="kw-card__title">Woche {w.week}</h3>
                <ul className="kw-card__tasks">
                  {w.tasks.map(t => (
                    <li key={t.id}>
                      <label className="taskline">
                        <input type="checkbox" checked={!!done[t.id]} onChange={() => toggle(t.id)} />
                        <span className="taskline__box"><Icon name="check" size={13} /></span>
                        <span className="taskline__txt">{t.t}</span>
                      </label>
                    </li>
                  ))}
                </ul>
              </article>
            );
          })}
        </div>
      </div>
    </main>
  );
}

/* ============================== Checkliste ============================== */
function ChecklistePage({ onNav }) {
  const [done, setDone] = useStore('rs.check.done', {});
  const all = CHECKLIST.flatMap((g, gi) => g.items.map((_, ii) => `${gi}-${ii}`));
  const doneCount = all.filter(k => done[k]).length;
  const toggle = (k) => setDone(d => ({ ...d, [k]: !d[k] }));
  const reset = () => setDone({});

  return (
    <main>
      <Breadcrumb trail={[{ label: 'Start', id: 'start' }, { label: 'Dienststart-Checkliste' }]} onNav={onNav} />
      <PageHeader eyebrow="Checkliste" title="Dienststart-Checkliste"
        lead="Alles, was vor dem ersten Tag erledigt sein sollte — nach Bereichen geordnet.">
        <div className="page-progress">
          <div className="page-progress__row">
            <span className="mono">{doneCount} / {all.length} erledigt</span>
            <button className="btn btn--quiet page-progress__reset" onClick={reset}>Zurücksetzen</button>
          </div>
          <ProgressBar value={doneCount} max={all.length} />
        </div>
      </PageHeader>

      <div className="wrap section" style={{ paddingTop: '2rem' }}>
        <div className="check-grid">
          {CHECKLIST.map((g, gi) => {
            const gd = g.items.filter((_, ii) => done[`${gi}-${ii}`]).length;
            return (
              <section key={gi} className="check-card card">
                <header className="check-card__head">
                  <h2>{g.group}</h2>
                  <span className="chip chip--mono">{gd}/{g.items.length}</span>
                </header>
                <ul className="check-card__list">
                  {g.items.map((item, ii) => {
                    const k = `${gi}-${ii}`;
                    return (
                      <li key={ii}>
                        <label className={`taskline taskline--lg ${done[k] ? 'is-done' : ''}`}>
                          <input type="checkbox" checked={!!done[k]} onChange={() => toggle(k)} />
                          <span className="taskline__box"><Icon name="check" size={14} /></span>
                          <span className="taskline__txt">{item}</span>
                        </label>
                      </li>
                    );
                  })}
                </ul>
              </section>
            );
          })}
        </div>
      </div>
    </main>
  );
}

/* ============================== 7-Tage-Plan ============================== */
function Plan7Page({ onNav }) {
  const [done, setDone] = useStore('rs.p7.done', {});
  const toggle = (k) => setDone(d => ({ ...d, [k]: !d[k] }));
  return (
    <main>
      <Breadcrumb trail={[{ label: 'Start', id: 'start' }, { label: '7-Tage-Plan' }]} onNav={onNav} />
      <PageHeader eyebrow="Vorbereitungsplan" title="Die letzten 7 Tage"
        lead="Tag für Tag bis zum Dienststart. Eine klare Struktur für die entscheidende Woche." />
      <div className="wrap section" style={{ paddingTop: '2rem' }}>
        <ol className="plan7">
          {PLAN_7.map((day, di) => (
            <li key={di} className="plan7__item">
              <div className="plan7__marker">
                <span className="plan7__num mono">{di + 1}</span>
                {di < PLAN_7.length - 1 && <span className="plan7__line" />}
              </div>
              <article className="plan7__card card">
                <header className="plan7__head">
                  <div>
                    <span className="plan7__day mono">{day.d}</span>
                    <h3>{day.focus}</h3>
                  </div>
                  {di === PLAN_7.length - 1 && <span className="chip chip--ok"><Icon name="flag" size={13} /> Dienststart</span>}
                </header>
                <ul className="plan7__tasks">
                  {day.tasks.map((t, ti) => {
                    const k = `${di}-${ti}`;
                    return (
                      <li key={ti}>
                        <label className={`taskline ${done[k] ? 'is-done' : ''}`}>
                          <input type="checkbox" checked={!!done[k]} onChange={() => toggle(k)} />
                          <span className="taskline__box"><Icon name="check" size={13} /></span>
                          <span className="taskline__txt">{t}</span>
                        </label>
                      </li>
                    );
                  })}
                </ul>
              </article>
            </li>
          ))}
        </ol>
      </div>
    </main>
  );
}

/* ============================== Shop ============================== */
function ShopPage({ onNav }) {
  return (
    <main>
      <Breadcrumb trail={[{ label: 'Start', id: 'start' }, { label: 'Rekruten-Shop' }]} onNav={onNav} />
      <PageHeader eyebrow="Rekruten-Shop" title="Material & Pakete"
        lead="Optionale, unabhängige Materialien für deine Vorbereitung. Digitale Inhalte und Empfehlungen." />
      <div className="wrap section" style={{ paddingTop: '2rem' }}>
        <div className="shop-grid">
          {SHOP.map(s => (
            <article key={s.id} className="shop-card card" data-tint={s.tint}>
              <image-slot id={`shop-${s.id}`} class="shop-card__img" shape="rounded" radius="7"
                placeholder="Produktbild ziehen"></image-slot>
              <div className="shop-card__body">
                <div className="shop-card__row">
                  <h3>{s.name}</h3>
                  {s.badge && <span className="chip">{s.badge}</span>}
                </div>
                <p className="shop-card__desc">{s.desc}</p>
                <ul className="shop-card__items">
                  {s.items.map((it, i) => <li key={i}><Icon name="check" size={15} /> {it}</li>)}
                </ul>
                <div className="shop-card__foot">
                  <span className="shop-card__price mono">{s.price}</span>
                  <button className="btn"><Icon name="bag" size={17} /> In den Warenkorb</button>
                </div>
              </div>
            </article>
          ))}
        </div>
        <p className="shop-note muted">
          <Icon name="info" size={16} /> Preise inkl. MwSt. Digitale Inhalte sind nach dem Kauf sofort verfügbar. Kein offizielles Angebot der Bundeswehr.
        </p>
      </div>
    </main>
  );
}

Object.assign(window, { KursePage, KwPlanPage, ChecklistePage, Plan7Page, ShopPage, useStore });
