/* polish/leren-shared.jsx
   Cross-view Leren-componenten. Wordt door alle 4 Leren-HTMLs geladen,
   na shared.jsx en leren-components.jsx. Bevat:
   - LerenPage (page-shell wrapper: Sidebar + Topbar + main)
   - ChapterHeader (breadcrumb + subject-chip + titel + mastery)
   - FlashcardDeck (vraag/antwoord-flip + grade-knoppen — gebruikt in
     hoofdstuk-flashcards-tab én herhaalsessie)
   - ChatPanel + ChatBubble + ChatComposer (gebruikt in hoofdstuk-pulse-tab
     én bibliotheek-pulse-entry)
   - LerenTabs (kleine tab-strip; gebruikt in hoofdstuk én bibliotheek)
*/

/* ─── LerenPage — page shell ─────────────────────────────── */
function LerenPage({ t, children, subtitle, title = 'Leren',
                    snaps = 1240, streak = 12, level = 7,
                    streakFrozen = false,
                    activeNav = 'leren', url = 'snapsnel.nl/leren',
                    rightExtra }) {
  const user = {
    name: 'sam_bakker', level, xp: 73, xpMax: 272,
    streak, snaps,
  };
  return (
    <BrowserShell t={t} url={url}>
      <Sidebar t={t} active={activeNav} user={user} streakFrozen={streakFrozen} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        <Topbar t={t} title={title} subtitle={subtitle} rightExtra={rightExtra} />
        <main style={{ flex: 1, overflow: 'auto', padding: '24px 28px 36px', background: t.bg }}>
          {children}
        </main>
      </div>
    </BrowserShell>
  );
}

/* ─── LerenTabs ──────────────────────────────────────────────
   Smalle horizontale tab-strip. Active = onderlijn in pijler-kleur,
   inactive = fgMute. Counts optioneel rechts in tab.
   ──────────────────────────────────────────────────────────── */
function LerenTabs({ t, tabs = [], active, accent }) {
  const c = accent || t.primary;
  return (
    <div style={{
      display: 'flex', gap: 4,
      borderBottom: `1px solid ${t.border}`,
      marginBottom: 0,
    }}>
      {tabs.map(tab => {
        const isActive = tab.id === active;
        return (
          <div key={tab.id} style={{
            padding: '12px 18px',
            borderBottom: `2px solid ${isActive ? c : 'transparent'}`,
            marginBottom: -1,
            display: 'inline-flex', alignItems: 'center', gap: 8,
            cursor: 'pointer',
          }}>
            {tab.icon && (
              <PI name={tab.icon} size={14}
                color={isActive ? c : t.fgMute} strokeWidth={2.4} />
            )}
            <span style={{
              fontFamily: 'Nunito', fontSize: 13, fontWeight: 800,
              color: isActive ? t.fg : t.fgMute,
              whiteSpace: 'nowrap',
            }}>{tab.label}</span>
            {tab.count != null && (
              <span style={{
                fontSize: 10.5, fontWeight: 800,
                padding: '2px 7px', borderRadius: 999,
                background: isActive
                  ? `color-mix(in srgb, ${c} 14%, transparent)`
                  : t.cardSunken,
                color: isActive ? c : t.fgMute,
                border: `1px solid ${isActive
                  ? `color-mix(in srgb, ${c} 28%, transparent)`
                  : t.border}`,
              }}>{tab.count}</span>
            )}
          </div>
        );
      })}
    </div>
  );
}

/* ─── ChapterHeader ─────────────────────────────────────────
   Breadcrumb + subject-chip + grote Fredoka-titel + MasteryDots
   + planner-handoff-badge. Hergebruikt in hoofdstuk-detail
   en eventueel later in herhaalsessie-context.
   ──────────────────────────────────────────────────────────── */
function ChapterHeader({ t, subject, breadcrumb = [], chapter, source,
                         masteryLevel, fromPlannen, toetsContext, rightExtra }) {
  return (
    <div style={{
      background: t.card, border: `1px solid ${t.border}`,
      borderRadius: 12, padding: 22,
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      {/* breadcrumb */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap',
        fontSize: 11.5, color: t.fgMute, fontWeight: 700,
      }}>
        {breadcrumb.map((bc, i) => (
          <React.Fragment key={i}>
            {i > 0 && <PI name="chevron-right" size={12} color={t.fgMute} />}
            <span style={{ color: i === breadcrumb.length - 1 ? t.fgDim : t.fgMute }}>{bc}</span>
          </React.Fragment>
        ))}
      </div>

      {/* main row: subject-chip + title + meta */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
        <SubjectChip t={t} subject={subject} size="lg" iconOnly />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
            {fromPlannen && (
              <HandoffBadge t={t} pillar="plannen" direction="from" label="uit Plannen" />
            )}
            {toetsContext && (
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 5, height: 22, padding: '0 9px',
                borderRadius: 999,
                background: t.mode === 'dark' ? 'rgba(244,114,182,0.14)' : 'rgba(190,24,93,0.10)',
                color: t.mode === 'dark' ? '#F472B6' : '#BE185D',
                border: `1px solid ${t.mode === 'dark' ? 'rgba(244,114,182,0.28)' : 'rgba(190,24,93,0.28)'}`,
                fontSize: 10.5, fontWeight: 800, letterSpacing: 0.3, textTransform: 'uppercase',
              }}>
                <PI name="alert-circle" size={10} strokeWidth={2.6} />{toetsContext}
              </span>
            )}
          </div>
          <h1 style={{
            margin: 0, fontFamily: 'Fredoka One', fontSize: 26,
            color: t.fg, lineHeight: 1.15, letterSpacing: '-0.01em',
          }}>{chapter}</h1>
          {source && (
            <div style={{ fontSize: 12, color: t.fgDim, fontWeight: 600, marginTop: 6 }}>
              {source}
            </div>
          )}
        </div>
        {rightExtra && <div style={{ flexShrink: 0 }}>{rightExtra}</div>}
      </div>

      {/* mastery rail */}
      {masteryLevel != null && (
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          paddingTop: 12, borderTop: `1px solid ${t.border}`,
        }}>
          <span style={{ fontSize: 10.5, color: t.fgMute, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase' }}>
            Beheersing
          </span>
          <MasteryDots t={t} level={masteryLevel} size="md" showLabel />
        </div>
      )}
    </div>
  );
}

/* ─── FlashcardDeck ─────────────────────────────────────────
   Eén kaart-in-beeld pattern. Toont:
   - Subject-bron-context bovenaan
   - Voortgang (3 / 12)
   - Front- of back-state (controle via prop `flipped`)
   - 4 grade-knoppen post-flip met tijdsindicaties (wanneer je deze kaart weer ziet)
   Statische compositie — geen click-handling.
   ──────────────────────────────────────────────────────────── */
function FlashcardDeck({ t, card, flipped = true, idx = 1, total = 12,
                         showStackHint = false, flipCtaSub, onGrade }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Context-rail */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        fontSize: 11.5, color: t.fgDim, fontWeight: 700,
      }}>
        <SubjectChip t={t} subject={card.subject} size="sm" iconOnly />
        <span>{card.source}</span>
        <span style={{ flex: 1 }} />
        <span style={{ color: t.fgMute, fontWeight: 800, letterSpacing: 0.3 }}>
          Kaart {idx} / {total}
        </span>
      </div>

      {/* Card itself, with optional stack-hint */}
      <div style={{ position: 'relative' }}>
        {showStackHint && (
          <>
            <div style={{
              position: 'absolute', left: 18, right: 18, top: 8,
              height: 24, background: t.card, border: `1px solid ${t.border}`,
              borderRadius: 8, opacity: 0.5, zIndex: 0,
            }} />
            <div style={{
              position: 'absolute', left: 10, right: 10, top: 4,
              height: 24, background: t.card, border: `1px solid ${t.border}`,
              borderRadius: 8, opacity: 0.7, zIndex: 0,
            }} />
          </>
        )}

        <div style={{
          position: 'relative', zIndex: 1,
          background: t.card, border: `1px solid ${t.border}`,
          borderRadius: 12, padding: '28px 28px 24px',
          minHeight: 240, display: 'flex', flexDirection: 'column', gap: 14,
        }}>
          {/* Side label */}
          <div style={{
            display: 'inline-flex', alignSelf: 'flex-start',
            padding: '3px 10px', borderRadius: 999,
            background: flipped ? t.primaryDim : t.cardSunken,
            color: flipped ? t.primary : t.fgMute,
            fontSize: 9.5, fontWeight: 800, letterSpacing: 0.6, textTransform: 'uppercase',
            border: `1px solid ${flipped ? `color-mix(in srgb, ${t.primary} 28%, transparent)` : t.border}`,
          }}>
            {flipped ? 'Antwoord' : 'Vraag'}
          </div>

          {/* Question */}
          <div style={{
            fontFamily: 'Fredoka One', fontSize: 22, color: t.fg,
            lineHeight: 1.3, letterSpacing: '-0.005em',
          }}>{card.front}</div>

          {/* Answer (only when flipped) */}
          {flipped && (
            <div style={{
              paddingTop: 14, borderTop: `1px dashed ${t.border}`,
              display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ fontSize: 14.5, color: t.fg, fontWeight: 600, lineHeight: 1.6 }}>
                {card.back}
              </div>
              {card.note && (
                <div style={{
                  display: 'flex', alignItems: 'flex-start', gap: 8,
                  padding: '10px 12px', borderRadius: 8,
                  background: t.cardSunken, border: `1px solid ${t.border}`,
                }}>
                  <PI name="lightbulb" size={13} color={t.gold} strokeWidth={2.4}
                       fill="currentColor" style={{ marginTop: 2, flexShrink: 0 }} />
                  <span style={{ fontSize: 12, color: t.fgDim, fontWeight: 600, lineHeight: 1.5 }}>
                    {card.note}
                  </span>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Grade buttons or flip-CTA */}
      {flipped ? (
        <GradeButtonRow t={t} />
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <BtnPrimary t={t} icon="repeat-2">Toon antwoord</BtnPrimary>
          {flipCtaSub && (
            <span style={{ fontSize: 11.5, color: t.fgMute, fontWeight: 600 }}>
              {flipCtaSub}
            </span>
          )}
        </div>
      )}
    </div>
  );
}

/* Tweeregelige header + 4-koloms grade-grid. Eén consistente eenheid
   die de "hoe goed kende je deze kaart" framing levert. */
function GradeButtonRow({ t }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <h3 style={{
          margin: 0, fontFamily: 'Nunito', fontSize: 14.5, fontWeight: 800,
          color: t.fg, letterSpacing: '-0.005em',
        }}>Hoe goed kende je deze kaart?</h3>
        <span style={{ fontSize: 11.5, color: t.fgMute, fontWeight: 600, lineHeight: 1.5 }}>
          Pulse plant op basis hiervan wanneer je 'm weer ziet.
        </span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
        <GradeButton t={t} grade="opnieuw"   label="Vergeten"  due="zo weer" />
        <GradeButton t={t} grade="moeilijk"  label="Moeilijk"  due="later vandaag" />
        <GradeButton t={t} grade="goed"      label="Goed"      due="morgen" />
        <GradeButton t={t} grade="makkelijk" label="Makkelijk" due="over 4 dagen" />
      </div>
    </div>
  );
}

function GradeButton({ t, grade, label, due }) {
  const dark = t.mode === 'dark';
  const palette = {
    opnieuw:   { c: dark ? '#F87171' : '#DC2626', bg: dark ? 'rgba(248,113,113,0.12)' : 'rgba(220,38,38,0.06)' },
    moeilijk:  { c: dark ? '#FBBF24' : '#B45309', bg: dark ? 'rgba(251,191,36,0.12)' : 'rgba(180,83,9,0.06)' },
    goed:      { c: dark ? '#22C55E' : '#15803D', bg: dark ? 'rgba(34,197,94,0.12)' : 'rgba(21,128,61,0.06)' },
    makkelijk: { c: dark ? '#22D3EE' : '#0369A1', bg: dark ? 'rgba(34,211,238,0.12)' : 'rgba(3,105,161,0.06)' },
  }[grade];
  return (
    <button style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
      padding: '11px 8px', borderRadius: 10,
      background: palette.bg,
      border: `1px solid ${palette.c}40`,
      color: palette.c, cursor: 'pointer', fontFamily: 'Nunito',
      whiteSpace: 'nowrap',
    }}>
      <span style={{
        fontSize: 13, fontWeight: 800, color: t.fg,
        whiteSpace: 'nowrap', lineHeight: 1.2,
      }}>{label}</span>
      <span style={{
        fontSize: 11, fontWeight: 700, color: t.fgMute,
        whiteSpace: 'nowrap', lineHeight: 1.2,
      }}>{due}</span>
    </button>
  );
}

/* ─── ChatPanel ──────────────────────────────────────────────
   RAG-chat-paneel. Toont een stack van bubbles + composer onderaan.
   Source-context-badge bovenaan. Voorbeeld-vraag-chips boven composer
   wanneer er nog geen geschiedenis is.
   ──────────────────────────────────────────────────────────── */
function ChatPanel({ t, source, messages = [], suggestions = [],
                     placeholder = 'Stel een vraag…', height = 520 }) {
  const dark = t.mode === 'dark';
  const purple = dark ? '#9D4EDD' : '#7C3AED';
  return (
    <div style={{
      background: t.card, border: `1px solid ${t.border}`,
      borderRadius: 12, padding: 0,
      display: 'flex', flexDirection: 'column', height,
      overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '14px 18px', borderBottom: `1px solid ${t.border}`,
        background: t.cardSunken,
      }}>
        <PulseMascot size={28} mood="thinking" />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Nunito', fontWeight: 800, fontSize: 13, color: t.fg }}>
            Pulse — vraag iets
          </div>
          {source && (
            <div style={{ fontSize: 10.5, color: t.fgMute, fontWeight: 700, marginTop: 2 }}>
              Antwoorden uit: <span style={{ color: t.fgDim }}>{source}</span>
            </div>
          )}
        </div>
        <span style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          padding: '3px 9px', borderRadius: 999,
          background: dark ? 'rgba(157,78,221,0.14)' : 'rgba(124,58,237,0.10)',
          color: purple, border: `1px solid ${dark ? 'rgba(157,78,221,0.28)' : 'rgba(124,58,237,0.28)'}`,
          fontSize: 9.5, fontWeight: 800, letterSpacing: 0.4, textTransform: 'uppercase',
          whiteSpace: 'nowrap',
        }}>
          <PI name="sparkles" size={9} color={purple} strokeWidth={2.4} />RAG
        </span>
      </div>

      {/* Messages */}
      <div style={{
        flex: 1, overflowY: 'auto', padding: '18px',
        display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        {messages.length === 0 ? (
          <div style={{
            margin: 'auto', maxWidth: 360,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
          }}>
            <PulseMascot size={56} mood="curious" />
            <div style={{
              fontFamily: 'Fredoka One', fontSize: 17, color: t.fg, textAlign: 'center',
            }}>Wat zou je willen weten?</div>
            <div style={{
              fontSize: 12, color: t.fgDim, textAlign: 'center', lineHeight: 1.5, fontWeight: 500,
            }}>
              Ik antwoord op basis van je lesmateriaal. Bronnen staan altijd onder het antwoord.
            </div>
          </div>
        ) : (
          messages.map((m, i) => <ChatBubble key={i} t={t} {...m} />)
        )}
      </div>

      {/* Suggestion chips */}
      {suggestions.length > 0 && (
        <div style={{
          display: 'flex', gap: 6, padding: '0 18px 10px', flexWrap: 'wrap',
        }}>
          {suggestions.map((s, i) => (
            <button key={i} style={{
              padding: '6px 10px', borderRadius: 999,
              background: t.cardSunken, border: `1px solid ${t.border}`,
              color: t.fgDim, fontSize: 11.5, fontWeight: 700, cursor: 'pointer',
              fontFamily: 'Nunito', whiteSpace: 'nowrap',
            }}>{s}</button>
          ))}
        </div>
      )}

      {/* Composer */}
      <div style={{
        padding: '12px 14px',
        borderTop: `1px solid ${t.border}`, background: t.bg,
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '8px 8px 8px 14px', borderRadius: 999,
          background: t.card, border: `1px solid ${t.borderStrong}`,
        }}>
          <span style={{ fontSize: 13, color: t.fgMute, flex: 1, fontFamily: 'Nunito' }}>
            {placeholder}
          </span>
          <button style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 32, height: 32, borderRadius: 999,
            background: t.primary, border: 'none', cursor: 'pointer',
            color: dark ? '#0A0F1E' : '#FFFFFF',
          }}>
            <PI name="arrow-up" size={16} strokeWidth={2.6} />
          </button>
        </div>
      </div>
    </div>
  );
}

function ChatBubble({ t, role, body, citations = [] }) {
  const dark = t.mode === 'dark';
  const isUser = role === 'user';
  return (
    <div style={{
      display: 'flex', flexDirection: 'column',
      alignItems: isUser ? 'flex-end' : 'flex-start',
      gap: 6,
    }}>
      <div style={{
        maxWidth: '88%',
        background: isUser
          ? t.primary
          : t.cardSunken,
        color: isUser
          ? (dark ? '#0A0F1E' : '#FFFFFF')
          : t.fg,
        border: isUser ? 'none' : `1px solid ${t.border}`,
        padding: '10px 14px', borderRadius: 8,
        borderBottomRightRadius: isUser ? 4 : 14,
        borderBottomLeftRadius: isUser ? 14 : 4,
        fontSize: 13.5, lineHeight: 1.55, fontWeight: isUser ? 700 : 500,
        whiteSpace: 'pre-wrap',
      }}>{body}</div>
      {citations.length > 0 && (
        <div style={{
          display: 'flex', flexWrap: 'wrap', gap: 5,
          maxWidth: '88%',
        }}>
          {citations.map((c, i) => (
            <span key={i} style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              padding: '2px 8px', borderRadius: 999,
              background: t.cardSunken, border: `1px solid ${t.border}`,
              color: t.fgMute, fontSize: 10, fontWeight: 700, letterSpacing: 0.2,
            }}>
              <PI name="book-open" size={10} color={t.fgMute} />
              {c}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

/* ─── Expose ─────────────────────────────────────────────── */
Object.assign(window, {
  LerenPage, LerenTabs, ChapterHeader,
  FlashcardDeck, GradeButton, GradeButtonRow,
  ChatPanel, ChatBubble,
});
