/* prototype/views/ai-creator.jsx
   LerenAICreatorView — AI Content Creator hub.
   Drie ingangen: Foto / Beschrijven / Bestand.
   CreditsCounter in topbar, credit-warning bij ≤1 credit.
   Alle componenten via window-globals. Geen import-statements.
*/

(function () {
  const { useState } = React;

  /* ─── Mock: eerder toegevoegd ──────────────────────────── */
  const RECENT_UPLOADS = [
    {
      subject: 'frans', source: 'le-passe-compose.pdf',
      title: 'Le passé composé', masteryLevel: 1,
      cards: '18 kaarten', addedAgo: '4 dagen geleden',
    },
    {
      subject: 'engels', source: 'idioms-set.txt',
      title: 'Idioms & phrasal verbs', masteryLevel: 2,
      cards: '32 kaarten', addedAgo: 'vorige week',
    },
    {
      subject: 'aardrijkskunde', source: 'klimaat-fotos.jpg',
      title: 'Klimaatzones — schoolbord-foto', masteryLevel: 0,
      cards: '8 kaarten', addedAgo: '2 weken geleden',
    },
    {
      subject: 'biologie', source: 'celstructuur-samenvatting.pdf',
      title: 'Celstructuur & organellen', masteryLevel: 3,
      cards: '24 kaarten', addedAgo: '3 weken geleden',
    },
  ];

  /* ─── IngangCard — één van de drie ingangen ────────────── */
  function IngangCard({ t, icon, title, body, metaLines, ctaLabel, onClick }) {
    const dark = t.mode === 'dark';
    return (
      <div style={{
        background: t.card, border: `1px solid ${t.border}`,
        borderRadius: 12, padding: '20px 18px',
        display: 'flex', flexDirection: 'column', gap: 14,
        transition: 'border-color 0.15s',
      }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = t.primary; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = t.border; }}
      >
        {/* icon */}
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: dark ? 'rgba(0,180,216,0.12)' : 'rgba(0,150,199,0.10)',
          border: `1px solid ${dark ? 'rgba(0,180,216,0.22)' : 'rgba(0,150,199,0.22)'}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <PI name={icon} size={20} color={dark ? '#7DD3FC' : '#0369A1'} strokeWidth={2.0} />
        </div>

        {/* text */}
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: 'Fredoka One', fontSize: 18, color: t.fg,
            lineHeight: 1.2, marginBottom: 6,
          }}>{title}</div>
          <div style={{ fontSize: 13, color: t.fgDim, fontWeight: 600, lineHeight: 1.5 }}>
            {body}
          </div>
        </div>

        {/* meta lines */}
        <div style={{
          display: 'flex', flexDirection: 'column', gap: 4,
          padding: '10px 12px', borderRadius: 8,
          background: t.cardSunken, border: `1px solid ${t.border}`,
        }}>
          {metaLines.map((line, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              fontSize: 11.5, color: t.fgMute, fontWeight: 700,
            }}>
              <PI name="dot" size={10} color={t.fgMute} />
              {line}
            </div>
          ))}
        </div>

        {/* CTA */}
        <div>
          <BtnPrimary t={t} icon="arrow-right" onClick={onClick}>{ctaLabel}</BtnPrimary>
        </div>
      </div>
    );
  }

  /* ─── RecentTegel ────────────────────────────────────────── */
  function RecentTegel({ t, item, navigate }) {
    const fmtIcon = item.source.endsWith('.pdf') ? 'file-text'
      : (item.source.endsWith('.jpg') || item.source.endsWith('.png')) ? 'image'
      : 'type';
    return (
      <div
        onClick={() => navigate({ name: 'chapter', chapterId: item.source })}
        style={{
          background: t.card, border: `1px solid ${t.border}`,
          borderRadius: 10, padding: '12px 14px',
          display: 'flex', flexDirection: 'column', gap: 8,
          cursor: 'pointer', transition: 'border-color 0.12s',
        }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = t.primary; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = t.border; }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <SubjectChip t={t} subject={item.subject} size="sm" iconOnly />
          <span style={{
            fontSize: 10, color: t.fgMute, fontWeight: 800,
            letterSpacing: 0.3, textTransform: 'uppercase',
            display: 'inline-flex', alignItems: 'center', gap: 4,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }}>
            <PI name={fmtIcon} size={10} color={t.fgMute} strokeWidth={2.4} />
            {item.source}
          </span>
        </div>
        <div style={{
          fontFamily: 'Nunito', fontSize: 13.5, color: t.fg, fontWeight: 800,
          lineHeight: 1.3,
          overflow: 'hidden', display: '-webkit-box',
          WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
        }}>{item.title}</div>
        <MasteryDots t={t} level={item.masteryLevel} size="sm" />
        <div style={{
          paddingTop: 6, borderTop: `1px dashed ${t.border}`,
          fontSize: 10.5, color: t.fgMute, fontWeight: 700,
          display: 'flex', justifyContent: 'space-between',
        }}>
          <span>{item.cards}</span>
          <span>{item.addedAgo}</span>
        </div>
      </div>
    );
  }

  /* ─── Root view ──────────────────────────────────────────── */
  function LerenAICreatorView({ t, navigate, plan = 'premium', creditsLeft = 3, creditsMax = 10, hasFeature, consumeCredit }) {
    const dark = t.mode === 'dark';
    const lowCredits = creditsLeft <= 1;
    const isPremiumPlus = plan === 'premium-plus';

    function handleIngang(mode) {
      console.log('[AI Creator] ingang geopend:', mode);
      if (consumeCredit) consumeCredit(1);
    }

    return (
      <LerenPage
        t={t}
        title="AI Content Creator"
        subtitle="Maak van foto, tekst of bestand jouw studiemateriaal"
        snaps={1240}
        streak={12}
        level={7}
        url="snapsnel.nl/leren/ai-content"
        rightExtra={
          <CreditsCounter
            t={t}
            plan={plan}
            left={creditsLeft}
            max={creditsMax}
          />
        }
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 960 }}>

          {/* ── Hero-card ── */}
          <div style={{
            background: dark
              ? 'linear-gradient(135deg, #0F1F2E 0%, #0E2235 60%, #102438 100%)'
              : 'linear-gradient(135deg, #ECFEFF 0%, #E0F2FE 60%, #F0F9FF 100%)',
            border: `1px solid ${dark ? 'rgba(0,180,216,0.22)' : '#BAE6FD'}`,
            borderRadius: 14, padding: '24px 28px',
            display: 'flex', alignItems: 'center', gap: 22,
          }}>
            <PulseMascot size={64} mood="encouraging" style={{ flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: 'Fredoka One', fontSize: 24,
                color: dark ? '#F1F5F9' : '#0C4A6E', lineHeight: 1.2, marginBottom: 6,
              }}>
                Maak een leer-hoofdstuk in 1 minuut
              </div>
              <div style={{
                fontSize: 14, color: dark ? '#94A3B8' : '#075985',
                fontWeight: 600, lineHeight: 1.55,
              }}>
                Geef Pulse een foto, beschrijving of bestand — je krijgt een volledig hoofdstuk
                terug met samenvatting, flashcards, mindmap, je eigen Pulse-tutor en test-vragen.
                Materiaal blijft van jou. ±1 credit per creatie.
              </div>
            </div>
          </div>

          {/* ── Credit warning ── */}
          {lowCredits && (
            <div style={{
              background: dark ? 'rgba(239,68,68,0.10)' : 'rgba(220,38,38,0.07)',
              border: `1px solid ${dark ? 'rgba(239,68,68,0.28)' : 'rgba(220,38,38,0.25)'}`,
              borderRadius: 10, padding: '14px 18px',
              display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
            }}>
              <PI name="alert-triangle" size={18} color={dark ? '#F87171' : '#DC2626'} strokeWidth={2.2} />
              <div style={{ flex: 1, minWidth: 200 }}>
                <div style={{ fontSize: 13.5, color: t.fg, fontWeight: 800, marginBottom: 2 }}>
                  Bijna geen credits over.
                </div>
                <div style={{ fontSize: 12.5, color: t.fgDim, fontWeight: 600 }}>
                  Wacht tot 1 mei (refill) of upgrade voor meer credits.
                </div>
              </div>
              {plan === 'free' ? (
                <BtnPrimary t={t} icon="zap" onClick={() => console.log('upgrade naar Premium')}>
                  Upgrade naar Premium
                </BtnPrimary>
              ) : (
                <BtnPrimary t={t} icon="zap" onClick={() => console.log('upgrade naar Premium+')}>
                  Upgrade naar Premium+
                </BtnPrimary>
              )}
            </div>
          )}

          {/* ── Wat krijg je terug? ── */}
          <div>
            <SectionLabel t={t}>Wat krijg je terug?</SectionLabel>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10,
              padding: '14px', borderRadius: 12,
              background: dark ? 'rgba(0,180,216,0.06)' : 'rgba(0,150,199,0.04)',
              border: `1px solid ${dark ? 'rgba(0,180,216,0.18)' : 'rgba(0,150,199,0.18)'}`,
            }}>
              {[
                { icon: 'file-text',     label: 'Samenvatting',     sub: 'Per onderwerp uitgelegd' },
                { icon: 'git-branch',    label: 'Mindmap',           sub: 'Visueel verband' },
                { icon: 'layers',        label: 'Flashcards',        sub: 'Klaar voor herhaling' },
                { icon: 'message-circle', label: 'Vraag aan Pulse',  sub: 'RAG over jouw stof' },
                { icon: 'brain',         label: 'Test jezelf',       sub: 'Recall + uitleggen' },
              ].map((item, i) => (
                <div key={i} style={{
                  display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 6,
                  padding: '10px 6px',
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 8,
                    background: dark ? 'rgba(0,180,216,0.14)' : 'rgba(0,150,199,0.10)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <PI name={item.icon} size={15} color={dark ? '#7DD3FC' : '#0369A1'} strokeWidth={2.2} />
                  </div>
                  <div style={{ fontSize: 12, fontWeight: 800, color: t.fg, lineHeight: 1.2 }}>{item.label}</div>
                  <div style={{ fontSize: 10.5, color: t.fgMute, fontWeight: 600, lineHeight: 1.3 }}>{item.sub}</div>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 11.5, color: t.fgMute, fontWeight: 600, marginTop: 8, fontStyle: 'italic' }}>
              Eén creatie = compleet leer-hoofdstuk, klaar voor de toets.
            </div>
          </div>

          {/* ── Drie ingang-cards ── */}
          <div>
            <SectionLabel t={t}>Hoe wil je beginnen?</SectionLabel>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
              <IngangCard
                t={t}
                icon="camera"
                title="Foto"
                body="Maak een foto of upload een afbeelding van je boekpagina, stencil of aantekening."
                metaLines={['OCR + structuur', 'Volledig hoofdstuk', '1 credit']}
                ctaLabel="Upload foto"
                onClick={() => handleIngang('foto')}
              />
              <IngangCard
                t={t}
                icon="pencil"
                title="Beschrijven"
                body="Vertel Pulse wat je moet kennen — bijv. 'mitose en meiose voor de bio-toets'."
                metaLines={['Pulse stelt vragen', 'Volledig hoofdstuk', '1-2 credits']}
                ctaLabel="Beschrijf onderwerp"
                onClick={() => handleIngang('beschrijven')}
              />
              <IngangCard
                t={t}
                icon="file-text"
                title="Bestand"
                body="Upload een PDF, Word of tekstbestand. Tot 50 pagina's worden verwerkt."
                metaLines={['Tot 50 pagina\'s', 'Volledig hoofdstuk', '1-3 credits']}
                ctaLabel="Upload bestand"
                onClick={() => handleIngang('bestand')}
              />
            </div>
          </div>

          {/* ── Disclaimer-strip ── */}
          <div style={{
            display: 'flex', alignItems: 'flex-start', gap: 10,
            padding: '10px 14px', borderRadius: 8,
            background: t.cardSunken, border: `1px solid ${t.border}`,
          }}>
            <PI name="shield" size={15} color={t.fgMute} strokeWidth={2.2} style={{ marginTop: 1, flexShrink: 0 }} />
            <div style={{ fontSize: 12, color: t.fgMute, fontWeight: 600, lineHeight: 1.5 }}>
              Materiaal dat jij toevoegt blijft 100% van jou. We trainen onze modellen niet op jouw uploads zonder expliciete toestemming.
            </div>
          </div>

          {/* ── Eerder toegevoegd ── */}
          <div>
            <SectionLabel t={t} right={
              <span style={{ fontSize: 11, color: t.fgMute, fontWeight: 700 }}>
                {RECENT_UPLOADS.length} bestanden
              </span>
            }>
              Recent toegevoegd
            </SectionLabel>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
              {RECENT_UPLOADS.map((item, i) => (
                <RecentTegel key={i} t={t} item={item} navigate={navigate} />
              ))}
            </div>
          </div>

        </div>
      </LerenPage>
    );
  }

  window.LerenAICreatorView = LerenAICreatorView;
})();
