/* ============================================================
   CURIO — Preview page (paginated learner-facing read-only view)
   ============================================================ */

/* ---------- MarkdownViewer — Toast UI viewer mode ---------- */
function MarkdownViewer({ value }) {
  const containerRef = useRef(null);
  const viewerRef = useRef(null);

  useEffect(() => {
    let cancelled = false;
    let pollId = null;
    let attempts = 0;

    const mount = () => {
      if (cancelled || viewerRef.current || !containerRef.current) return;
      try {
        viewerRef.current = window.toastui.Editor.factory({
          el: containerRef.current,
          viewer: true,
          initialValue: value || '',
          theme: 'light',
        });
      } catch (e) {
        containerRef.current.innerHTML = '<div style="color:var(--muted);font-size:13px">Could not render content.</div>';
      }
    };

    if (window.toastui && window.toastui.Editor) {
      mount();
    } else {
      pollId = setInterval(() => {
        attempts += 1;
        if (window.toastui && window.toastui.Editor) {
          clearInterval(pollId);
          pollId = null;
          mount();
        } else if (attempts > 80) {
          clearInterval(pollId);
          pollId = null;
          if (containerRef.current && !viewerRef.current) {
            containerRef.current.innerHTML = '<pre style="white-space:pre-wrap;font-family:inherit;font-size:15px;line-height:1.7;color:var(--ink-2);margin:0">' +
              (value || '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])) + '</pre>';
          }
        }
      }, 50);
    }

    return () => {
      cancelled = true;
      if (pollId) clearInterval(pollId);
      if (viewerRef.current) {
        try { viewerRef.current.destroy(); } catch (e) {}
        viewerRef.current = null;
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!viewerRef.current) return;
    try { viewerRef.current.setMarkdown(value || ''); } catch (e) {}
  }, [value]);

  return <div ref={containerRef} className="preview-body" />;
}

/* ---------- Quiz question (read-only with reveal) ---------- */
function PreviewQuestion({ q, idx }) {
  const [picked, setPicked] = useState(null);
  const correctIdx = ({ A: 0, B: 1, C: 2, D: 3 })[q.correctAnswer] ?? 0;
  const options = [q.optionA, q.optionB, q.optionC, q.optionD];
  return (
    <div className="card" style={{ padding: '22px 24px', marginBottom: 16 }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--amber)', marginBottom: 8 }}>Question {idx + 1}</div>
      <h3 style={{ fontSize: 17, lineHeight: 1.4, letterSpacing: '-0.01em' }}>{q.question}</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9, marginTop: 16 }}>
        {options.map((o, i) => {
          const show = picked != null;
          const isCorrect = i === correctIdx;
          const state = show && isCorrect ? 'correct' : show && picked === i && !isCorrect ? 'wrong' : 'idle';
          return (
            <button key={i} onClick={() => setPicked(i)} className="card" style={{ textAlign: 'left', padding: '11px 14px', display: 'flex', alignItems: 'center', gap: 11, cursor: 'pointer',
              border: state === 'correct' ? '1.5px solid var(--green)' : state === 'wrong' ? '1.5px solid var(--rose)' : '1px solid var(--line)',
              background: state === 'correct' ? 'var(--green-tint)' : state === 'wrong' ? 'var(--rose-tint)' : 'var(--surface)' }}>
              <span className="center" style={{ width: 22, height: 22, borderRadius: 50, fontSize: 11.5, fontWeight: 700, flexShrink: 0,
                background: state === 'correct' ? 'var(--green)' : state === 'wrong' ? 'var(--rose)' : 'var(--surface-2)', color: state === 'idle' ? 'var(--muted)' : '#fff' }}>
                {state === 'correct' ? <Check size={13} /> : state === 'wrong' ? <X size={13} /> : String.fromCharCode(65 + i)}
              </span>
              <span style={{ fontSize: 14.5 }}>{o}</span>
            </button>
          );
        })}
      </div>
      {picked != null && q.explanation && (
        <div className="fade-in" style={{ marginTop: 14, padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 10, fontSize: 13.5, lineHeight: 1.55 }}>
          <b style={{ color: 'var(--green)' }}>Explanation. </b>{q.explanation}
        </div>
      )}
    </div>
  );
}

/* ---------- Flatten course into pages ---------- */
// Each "page" is either:
//   { kind: 'intro' }                                 — course overview
//   { kind: 'lesson', moduleIdx, lessonIdx, lesson, module }
//   { kind: 'quiz',   moduleIdx, module, quiz }       — module-end quiz
//   { kind: 'outro' }                                 — congrats card
function buildPages(course) {
  const pages = [{ kind: 'intro' }];
  (course.modules || []).forEach((m, mi) => {
    const lessons = (m.lessons || []).filter(l => l.type === 'lesson');
    lessons.forEach((l, li) => {
      pages.push({ kind: 'lesson', moduleIdx: mi, lessonIdx: li, lesson: l, module: m, lessonsInModule: lessons.length });
    });
    const quizRow = (m.lessons || []).find(l => l.type === 'quiz' && l._quiz?.questions?.length);
    if (quizRow) {
      pages.push({ kind: 'quiz', moduleIdx: mi, module: m, quiz: quizRow._quiz });
    }
  });
  pages.push({ kind: 'outro' });
  return pages;
}

function pageKey(p) {
  if (p.kind === 'lesson') return 'l:' + p.lesson.id;
  if (p.kind === 'quiz') return 'q:' + p.module.id;
  return p.kind;
}

/* ---------- Sidebar (course outline, marks current page) ---------- */
function PreviewSidebar({ course, pages, currentIdx, onJump, totalPages }) {
  return (
    <aside style={{
      width: 280,
      borderRight: '1px solid var(--line)',
      background: 'var(--surface)',
      height: '100vh',
      position: 'sticky',
      top: 0,
      overflowY: 'auto',
      flexShrink: 0,
    }} className="scroll">
      <div style={{ padding: '20px 18px 12px' }}>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--faint)', marginBottom: 6 }}>Course</div>
        <div style={{ fontSize: 14.5, fontWeight: 700, letterSpacing: '-0.01em', lineHeight: 1.3 }}>{course.title}</div>
        <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>{currentIdx + 1} of {totalPages}</div>
      </div>
      <div style={{ padding: '4px 8px 24px', display: 'flex', flexDirection: 'column', gap: 1 }}>
        <button
          className="nav-item"
          style={{
            height: 34, fontSize: 13,
            background: pages[currentIdx]?.kind === 'intro' ? 'var(--brand-tint)' : 'transparent',
            color: pages[currentIdx]?.kind === 'intro' ? 'var(--brand-ink)' : 'var(--ink-2)',
            fontWeight: pages[currentIdx]?.kind === 'intro' ? 600 : 500,
          }}
          onClick={() => onJump(0)}
        >
          <Spark size={13} /> Course overview
        </button>

        {(course.modules || []).map((m, mi) => {
          const moduleLessons = (m.lessons || []).filter(l => l.type === 'lesson');
          const hasQuiz = (m.lessons || []).some(l => l.type === 'quiz' && l._quiz?.questions?.length);
          return (
            <div key={m.id || mi} style={{ marginTop: 14 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '.1em', textTransform: 'uppercase', color: 'var(--faint)', padding: '0 10px 6px' }}>Module {mi + 1}</div>
              <div className="muted" style={{ fontSize: 12, padding: '0 10px 8px', fontWeight: 600, color: 'var(--ink-2)' }}>{m.title}</div>
              {moduleLessons.map((l, li) => {
                const idx = pages.findIndex(p => p.kind === 'lesson' && p.lesson.id === l.id);
                const active = idx === currentIdx;
                return (
                  <button
                    key={l.id || li}
                    className="nav-item"
                    style={{
                      height: 'auto', minHeight: 30, padding: '8px 10px',
                      fontSize: 12.5, lineHeight: 1.35,
                      background: active ? 'var(--brand-tint)' : 'transparent',
                      color: active ? 'var(--brand-ink)' : 'var(--ink-2)',
                      fontWeight: active ? 600 : 500,
                      textAlign: 'left',
                      whiteSpace: 'normal',
                    }}
                    onClick={() => onJump(idx)}
                  >
                    <span style={{ flexShrink: 0, width: 18, color: 'var(--faint)', fontSize: 11.5 }}>{mi + 1}.{li + 1}</span>
                    <span style={{ flex: 1, textAlign: 'left' }}>{l.title}</span>
                  </button>
                );
              })}
              {hasQuiz && (() => {
                const idx = pages.findIndex(p => p.kind === 'quiz' && p.module.id === m.id);
                const active = idx === currentIdx;
                return (
                  <button
                    className="nav-item"
                    style={{
                      height: 'auto', minHeight: 30, padding: '8px 10px', fontSize: 12.5, lineHeight: 1.35,
                      background: active ? 'var(--amber-tint)' : 'transparent',
                      color: active ? '#8a560a' : 'var(--ink-2)',
                      fontWeight: active ? 600 : 500,
                    }}
                    onClick={() => onJump(idx)}
                  >
                    <Help size={12} style={{ color: 'var(--amber)' }} />
                    <span style={{ flex: 1, textAlign: 'left' }}>Module quiz</span>
                  </button>
                );
              })()}
            </div>
          );
        })}

        <button
          className="nav-item"
          style={{
            marginTop: 14, height: 34, fontSize: 13,
            background: pages[currentIdx]?.kind === 'outro' ? 'var(--brand-tint)' : 'transparent',
            color: pages[currentIdx]?.kind === 'outro' ? 'var(--brand-ink)' : 'var(--ink-2)',
            fontWeight: pages[currentIdx]?.kind === 'outro' ? 600 : 500,
          }}
          onClick={() => onJump(pages.length - 1)}
        >
          <Check size={13} /> Course complete
        </button>
      </div>
    </aside>
  );
}

/* ---------- Page renderers ---------- */
function IntroView({ course }) {
  const raw = course._raw || course;
  const totalLessons = (course.modules || []).reduce((a, m) => a + (m.lessons || []).filter(l => l.type === 'lesson').length, 0);
  const totalQuizzes = (course.modules || []).filter(m => (m.lessons || []).some(l => l.type === 'quiz' && l._quiz?.questions?.length)).length;
  const learningOutcomes = (raw.learningOutcomes || []);
  return (
    <>
      <div className="mono" style={{ fontSize: 11.5, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--brand)', marginBottom: 14 }}>Course overview</div>
      <h1 style={{ fontSize: 'clamp(32px, 4vw, 42px)', letterSpacing: '-0.03em', lineHeight: 1.08, fontWeight: 800 }}>{course.title}</h1>
      {course.description && <p className="lead" style={{ fontSize: 18, marginTop: 18, lineHeight: 1.55 }}>{course.description}</p>}
      <div className="row" style={{ gap: 18, marginTop: 22, fontSize: 13.5, flexWrap: 'wrap', color: 'var(--muted)' }}>
        <span className="row" style={{ gap: 6 }}><Layers size={14} />{course.modules.length} modules</span>
        <span className="row" style={{ gap: 6 }}><File size={14} />{totalLessons} lessons</span>
        {totalQuizzes > 0 && <span className="row" style={{ gap: 6 }}><Help size={14} />{totalQuizzes} quizzes</span>}
        <span className="row" style={{ gap: 6 }}><Clock size={14} />{course.hours}h</span>
        <span className="row" style={{ gap: 6, textTransform: 'capitalize' }}>{course.level}</span>
      </div>
      {learningOutcomes.length > 0 && (
        <div style={{ marginTop: 40 }}>
          <h2 style={{ fontSize: 19, letterSpacing: '-0.02em', marginBottom: 14 }}>What you'll learn</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 10 }}>
            {learningOutcomes.map((o, i) => (
              <div key={i} className="row" style={{ gap: 10, fontSize: 14.5, alignItems: 'flex-start', lineHeight: 1.5 }}>
                <Check size={16} style={{ color: 'var(--green)', marginTop: 2, flexShrink: 0 }} />
                <span>{o}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
}

function LessonView({ page }) {
  const { lesson, module: m, moduleIdx, lessonIdx, lessonsInModule } = page;
  return (
    <>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--brand)', marginBottom: 8 }}>
        Module {moduleIdx + 1} · Lesson {lessonIdx + 1} of {lessonsInModule}
      </div>
      <div className="muted" style={{ fontSize: 13, marginBottom: 14 }}>{m.title}</div>
      <h1 style={{ fontSize: 'clamp(26px, 3vw, 32px)', letterSpacing: '-0.025em', lineHeight: 1.15 }}>{lesson.title}</h1>
      <div style={{ marginTop: 26 }}>
        <MarkdownViewer value={lesson.body || '*This lesson has no content yet.*'} />
      </div>
    </>
  );
}

function QuizView({ page }) {
  const { module: m, moduleIdx, quiz } = page;
  return (
    <>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--amber)', marginBottom: 8 }}>Module {moduleIdx + 1} · Quiz</div>
      <div className="muted" style={{ fontSize: 13, marginBottom: 14 }}>{m.title}</div>
      <h1 style={{ fontSize: 'clamp(24px, 3vw, 30px)', letterSpacing: '-0.02em' }}>Test what you've learned</h1>
      <p className="muted" style={{ fontSize: 15, marginTop: 10, lineHeight: 1.5 }}>Pick an answer for each. The explanation appears once you choose.</p>
      <div style={{ marginTop: 28 }}>
        {(quiz.questions || []).map((q, qi) => <PreviewQuestion key={q.id || qi} q={q} idx={qi} />)}
      </div>
    </>
  );
}

function OutroView({ course, onJump }) {
  return (
    <div className="center" style={{ minHeight: 480, flexDirection: 'column', textAlign: 'center' }}>
      <div className="center" style={{ width: 64, height: 64, borderRadius: 18, background: 'var(--ai-grad)', color: '#fff', marginBottom: 18, boxShadow: 'var(--sh-brand)' }}>
        <Check size={28} />
      </div>
      <h1 style={{ fontSize: 32, letterSpacing: '-0.02em' }}>You've finished the preview</h1>
      <p className="muted" style={{ fontSize: 16, marginTop: 12, maxWidth: 480 }}>
        This is exactly what a learner sees when they complete <b>{course.title}</b>. Use the sidebar to jump to any lesson, or head back to the editor.
      </p>
      <div className="row" style={{ gap: 10, marginTop: 26 }}>
        <Btn variant="outline" onClick={() => onJump(0)} icon={<Refresh size={15} />}>Restart preview</Btn>
      </div>
    </div>
  );
}

/* ---------- PreviewPage root ---------- */
function PreviewPage({ go, params }) {
  const courseId = params.id;
  const [course, setCourse] = useState(null);
  const [error, setError] = useState(null);
  const [currentIdx, setCurrentIdx] = useState(0);

  // Load the course tree.
  useEffect(() => {
    if (!courseId) return;
    let cancelled = false;
    setError(null); setCourse(null);
    window.API.getCourse(courseId).then(c => {
      if (cancelled) return;
      setCourse(c);
    }).catch(e => {
      if (cancelled) return;
      setError(e?.message || 'Could not load course');
    });
    return () => { cancelled = true; };
  }, [courseId]);

  const pages = useMemo(() => course ? buildPages(course) : [], [course]);

  // Sync currentIdx with ?p=<idx> or ?lesson=<id> (lesson wins if both are present).
  useEffect(() => {
    if (!pages.length) return;
    const sp = new URLSearchParams(window.location.search);
    const lessonId = sp.get('lesson');
    if (lessonId) {
      const idx = pages.findIndex(pg => pg.kind === 'lesson' && pg.lesson && pg.lesson.id === lessonId);
      if (idx >= 0) { setCurrentIdx(idx); return; }
    }
    const p = parseInt(sp.get('p') || '0', 10);
    const safe = Number.isFinite(p) && p >= 0 && p < pages.length ? p : 0;
    setCurrentIdx(safe);
  }, [pages.length]);

  // Update URL when currentIdx changes.
  useEffect(() => {
    if (!pages.length) return;
    const sp = new URLSearchParams(window.location.search);
    sp.set('p', String(currentIdx));
    const newUrl = window.location.pathname + '?' + sp.toString();
    if (newUrl !== window.location.pathname + window.location.search) {
      window.history.replaceState({}, '', newUrl);
    }
  }, [currentIdx, pages.length]);

  // Listen for popstate so back/forward updates the page index.
  useEffect(() => {
    const onPop = () => {
      const sp = new URLSearchParams(window.location.search);
      const p = parseInt(sp.get('p') || '0', 10);
      if (Number.isFinite(p) && p >= 0 && p < (pages.length || 1)) setCurrentIdx(p);
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, [pages.length]);

  // Keyboard nav
  useEffect(() => {
    const onKey = (e) => {
      if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable)) return;
      if (e.key === 'ArrowLeft') { setCurrentIdx(i => Math.max(0, i - 1)); }
      else if (e.key === 'ArrowRight') { setCurrentIdx(i => Math.min((pages.length || 1) - 1, i + 1)); }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [pages.length]);

  // Scroll to top on page change.
  const scrollRef = useRef(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [currentIdx]);

  if (error) {
    return (
      <div className="center" style={{ minHeight: '100vh', background: 'var(--paper)', flexDirection: 'column', padding: 32 }}>
        <div className="card" style={{ padding: 24, maxWidth: 420, textAlign: 'center' }}>
          <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 8 }}>Course unavailable</div>
          <div className="muted" style={{ fontSize: 14, lineHeight: 1.5, marginBottom: 16 }}>{error}</div>
          <Btn variant="outline" size="sm" onClick={() => go('library')}>Back to library</Btn>
        </div>
      </div>
    );
  }
  if (!course || !pages.length) {
    return (
      <div className="center" style={{ minHeight: '100vh', background: 'var(--paper)' }}>
        <div className="row" style={{ gap: 10 }}>
          <span className="spinner dark" style={{ width: 14, height: 14 }} />
          <span className="mono muted" style={{ fontSize: 12 }}>Loading preview…</span>
        </div>
      </div>
    );
  }

  const page = pages[currentIdx];
  const progress = Math.round(((currentIdx + 1) / pages.length) * 100);
  const onJump = (idx) => setCurrentIdx(Math.max(0, Math.min(pages.length - 1, idx)));

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--paper)' }} data-screen-label="Course preview">
      <PreviewSidebar course={course} pages={pages} currentIdx={currentIdx} onJump={onJump} totalPages={pages.length} />

      <div ref={scrollRef} className="scroll" style={{ flex: 1, minWidth: 0, overflowY: 'auto', height: '100vh', display: 'flex', flexDirection: 'column' }}>
        {/* Top bar */}
        <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'rgba(250,250,248,.92)', backdropFilter: 'blur(12px)', borderBottom: '1px solid var(--line)' }}>
          <div className="row" style={{ padding: '12px 32px', gap: 14 }}>
            <button className="btn btn-icon btn-ghost btn-sm" onClick={() => go('creator', { editId: courseId })}><ChevL size={18} /></button>
            <span className="badge badge-brand" style={{ background:'var(--brand)', color:'#fff' }}><Eye size={11} /> Preview</span>
            <span className="muted mono" style={{ fontSize: 11.5 }}>learner view</span>
            <div className="grow" />
            <span className="mono muted" style={{ fontSize: 12 }}>{currentIdx + 1} / {pages.length}</span>
            <Btn variant="outline" size="sm" icon={<Edit size={14} />} onClick={() => go('creator', { editId: courseId })}>Back to editor</Btn>
          </div>
          <div style={{ height: 3, background: 'var(--surface-2)' }}>
            <div style={{ height: '100%', width: progress + '%', background: 'var(--ai-grad)', transition: 'width .25s var(--ease-out)' }} />
          </div>
        </div>

        {/* Page content */}
        <div style={{ maxWidth: 760, margin: '0 auto', padding: '52px 32px 40px', width: '100%', flex: 1 }} key={pageKey(page)} className="fade-in">
          {page.kind === 'intro' && <IntroView course={course} />}
          {page.kind === 'lesson' && <LessonView page={page} />}
          {page.kind === 'quiz' && <QuizView page={page} />}
          {page.kind === 'outro' && <OutroView course={course} onJump={onJump} />}
        </div>

        {/* Footer pagination */}
        <div style={{ borderTop: '1px solid var(--line)', background: 'var(--surface)' }}>
          <div className="row" style={{ maxWidth: 760, margin: '0 auto', padding: '18px 32px', gap: 14 }}>
            <Btn
              variant="outline"
              size="sm"
              icon={<ChevL size={15} />}
              disabled={currentIdx === 0}
              onClick={() => onJump(currentIdx - 1)}
              style={{ opacity: currentIdx === 0 ? 0.4 : 1 }}
            >
              Previous
            </Btn>
            <div className="grow center muted mono" style={{ fontSize: 11.5 }}>
              {pageKey(page) === 'intro' ? 'Start the course' :
                pageKey(page) === 'outro' ? 'You made it' :
                page.kind === 'lesson' ? ('Reading time ~' + Math.max(2, Math.round(((page.lesson.body || '').split(/\s+/).length) / 220)) + ' min') :
                page.kind === 'quiz' ? 'Quick check' : ''}
            </div>
            <Btn
              variant="brand"
              size="sm"
              iconR={<ChevR size={15} />}
              disabled={currentIdx >= pages.length - 1}
              onClick={() => onJump(currentIdx + 1)}
              style={{ opacity: currentIdx >= pages.length - 1 ? 0.4 : 1 }}
            >
              {currentIdx === 0 ? 'Start' : page.kind === 'lesson' ? 'Next lesson' : page.kind === 'quiz' ? 'Continue' : 'Next'}
            </Btn>
          </div>
        </div>
      </div>

      {/* Toast viewer styling */}
      <style>{`
        .preview-body .toastui-editor-contents { font-size: 16px; line-height: 1.75; color: var(--ink-2); padding: 0; }
        .preview-body .toastui-editor-contents p { margin: 0 0 1em; }
        .preview-body .toastui-editor-contents h1,
        .preview-body .toastui-editor-contents h2,
        .preview-body .toastui-editor-contents h3 { letter-spacing: -0.01em; margin-top: 1.6em; margin-bottom: .6em; color: var(--ink); }
        .preview-body .toastui-editor-contents h1 { font-size: 26px; }
        .preview-body .toastui-editor-contents h2 { font-size: 21px; }
        .preview-body .toastui-editor-contents h3 { font-size: 18px; }
        .preview-body .toastui-editor-contents ul, .preview-body .toastui-editor-contents ol { padding-left: 22px; }
        .preview-body .toastui-editor-contents li { margin-bottom: 6px; }
        .preview-body .toastui-editor-contents blockquote { border-left: 3px solid var(--brand); padding-left: 14px; color: var(--muted); }
        .preview-body .toastui-editor-contents img { max-width: 100%; border-radius: 10px; margin: 14px 0; }
        .preview-body .toastui-editor-contents code { background: var(--surface-2); padding: 2px 6px; border-radius: 4px; font-size: .9em; }
      `}</style>
    </div>
  );
}

Object.assign(window, { PreviewPage, MarkdownViewer });
