/* =============================================================
   三藏閣 — 학술 시그널 컴포넌트
   -------------------------------------------------------------
   SEP 톤의 학술 플랫폼에 필요한 작은 빌딩 블록들.
   백과 항목 / 연구노트 / 사전 / 리더 어디에서나 재사용 가능.

   - DefinitionBox    : 항목 상단 고정 짧은 정의 박스
   - MultilingualBox  : Pali / Skt / Ch / Tib 교차 표기
   - VersionBlock     : 최초 작성 · 최근 수정 · 상태 배지
   - LicenseBadge     : 제3자 자료 라이선스 구분
   - CitationButton + CitationModal : BibTeX / Chicago / MLA
   - NotesPanel       : 개인 메모·하이라이트 (로컬 저장)
   ============================================================= */

const { Icon: SIcon } = window;

/* ---------- 짧은 정의 박스 ---------- */
window.DefinitionBox = ({ children, term, original }) => (
  <aside className="sch-def" role="note">
    <div className="sch-def__eyebrow">정의 · 槪定</div>
    <div className="sch-def__body">
      {term && <span className="sch-def__term">{term}</span>}
      {original && <span className="sch-def__original">{original}</span>}
      <span className="sch-def__text">{children}</span>
    </div>
  </aside>
);

/* ---------- 다국어 명칭법 박스 ---------- */
/* names: { kr, han, pi, skt, tib, en, transl } 중 있는 것만 */
window.MultilingualBox = ({ names = {} }) => {
  const rows = [
    { key: 'kr',     label: '한국어',     lang: 'kr',   val: names.kr },
    { key: 'han',    label: '漢',         lang: 'han',  val: names.han },
    { key: 'pi',     label: 'PĀLI',       lang: 'pi',   val: names.pi },
    { key: 'skt',    label: 'SANSKRIT',   lang: 'skt',  val: names.skt },
    { key: 'tib',    label: 'TIBETAN',    lang: 'tib',  val: names.tib },
    { key: 'transl', label: 'WYLIE',      lang: 'pi',   val: names.transl },
    { key: 'en',     label: 'ENGLISH',    lang: 'en',   val: names.en },
  ].filter(r => r.val);
  if (rows.length === 0) return null;
  return (
    <aside className="sch-multi" aria-label="다국어 명칭">
      <div className="sch-multi__eyebrow">用語 · 다국어 표기</div>
      <dl className="sch-multi__list">
        {rows.map(r => (
          <div key={r.key} className="sch-multi__row">
            <dt className="sch-multi__key">{r.label}</dt>
            <dd className={'sch-multi__val sch-multi__val--' + r.lang}>{r.val}</dd>
          </div>
        ))}
      </dl>
    </aside>
  );
};

/* ---------- 버전 / 검수 블록 ---------- */
/* status: draft | review | verified | stable
   created, updated: 'YYYY.MM' 또는 'YYYY.MM.DD'
   editor: 작성·검수자 표시(텍스트) */
const STATUS_LABEL = {
  draft:    { kr: '초안',    en: 'DRAFT' },
  review:   { kr: '검토중',  en: 'IN REVIEW' },
  verified: { kr: '검수완료', en: 'VERIFIED' },
  stable:   { kr: '안정판',  en: 'STABLE' },
};

window.VersionBlock = ({ created, updated, status = 'review', editor, revisions = 0 }) => {
  const s = STATUS_LABEL[status] || STATUS_LABEL.review;
  return (
    <div className="sch-version" aria-label="항목 버전 정보">
      <div className="sch-version__cell">
        <div className="sch-version__key">최초 작성</div>
        <div className="sch-version__val">{created || '—'}</div>
      </div>
      <div className="sch-version__cell">
        <div className="sch-version__key">최근 수정</div>
        <div className="sch-version__val">{updated || '—'}</div>
      </div>
      <div className="sch-version__cell">
        <div className="sch-version__key">상태</div>
        <div className={'sch-version__val sch-version__val--status sch-version__val--' + status}>
          <span className="sch-version__dot"/>
          <span>{s.kr} · <span className="en">{s.en}</span></span>
        </div>
      </div>
      {(editor || revisions > 0) && (
        <div className="sch-version__cell">
          <div className="sch-version__key">검수</div>
          <div className="sch-version__val">
            {editor || '—'}{revisions > 0 ? ` · rev ${revisions}` : ''}
          </div>
        </div>
      )}
    </div>
  );
};

/* ---------- 라이선스 배지 ---------- */
/* preset: 'self' | 'cbeta' | 'vri' | 'pd' | 'custom'
   custom일 때 source/license/note prop으로 자유 입력 */
const LICENSE_PRESETS = {
  self:   { source: 'Dhamma Reader Original', license: '© Dhamma Reader',  note: '자체 저작 · 비영리 학술 인용 가능' },
  cbeta:  { source: 'CBETA',                  license: 'Non-commercial',   note: '中華電子佛典協會 · 학술/비상업 사용' },
  vri:    { source: 'VRI · CSCD',             license: 'Non-commercial',   note: 'Vipassana Research Institute · 학술/비상업' },
  pd:     { source: 'Public Domain',          license: 'CC0',              note: '공유 자료 · 자유 사용' },
};

window.LicenseBadge = ({ preset = 'self', source, license, note, compact = false }) => {
  const p = LICENSE_PRESETS[preset] || {};
  const src = source || p.source || '—';
  const lic = license || p.license || '—';
  const nt  = note   || p.note   || '';
  if (compact) {
    return (
      <span className={'sch-lic sch-lic--compact sch-lic--' + preset}>
        <span className="sch-lic__source">{src}</span>
        <span className="sch-lic__sep">·</span>
        <span className="sch-lic__license">{lic}</span>
      </span>
    );
  }
  return (
    <aside className={'sch-lic sch-lic--' + preset} aria-label="라이선스">
      <div className="sch-lic__row">
        <span className="sch-lic__key">출처</span>
        <span className="sch-lic__source">{src}</span>
      </div>
      <div className="sch-lic__row">
        <span className="sch-lic__key">라이선스</span>
        <span className="sch-lic__license">{lic}</span>
      </div>
      {nt && <div className="sch-lic__note">{nt}</div>}
    </aside>
  );
};

/* ---------- 인용 포맷 생성 ---------- */
const buildCitations = (e) => {
  const author  = e.author  || 'Dhamma Reader';
  const title   = e.title   || '제목 미상';
  const url     = e.url     || (typeof location !== 'undefined' ? location.href : '');
  const year    = e.year    || new Date().getFullYear();
  const updated = e.updated || '';
  const id      = e.id      || (title || 'entry').replace(/[^\w]/g, '').toLowerCase();

  const chicago = `${author}. "${title}." 三藏閣 · Tripiṭaka Reading Room. 최종 수정 ${updated || year}. ${url}.`;

  const mla = `${author}. "${title}." 三藏閣, ${year}, ${url}. Accessed ${new Date().toISOString().slice(0,10)}.`;

  const apa = `${author}. (${year}). ${title}. 三藏閣 · Tripiṭaka Reading Room. ${url}`;

  const bibtex = [
    `@misc{${id},`,
    `  author    = {${author}},`,
    `  title     = {${title}},`,
    `  year      = {${year}},`,
    `  url       = {${url}},`,
    `  note      = {三藏閣 · Tripiṭaka Reading Room${updated ? `, last modified ${updated}` : ''}},`,
    `}`,
  ].join('\n');

  return { chicago, mla, apa, bibtex };
};

window.CitationButton = ({ entry, label = '이 항목 인용' }) => {
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button className="sch-cite-btn" onClick={() => setOpen(true)}>
        <SIcon name="quote" size={14}/>
        <span>{label}</span>
      </button>
      {open && <window.CitationModal entry={entry} onClose={() => setOpen(false)}/>}
    </React.Fragment>
  );
};

window.CitationModal = ({ entry, onClose }) => {
  const cites = buildCitations(entry);
  const [fmt, setFmt] = React.useState('chicago');
  const text = cites[fmt];
  const [copied, setCopied] = React.useState(false);
  const copy = async () => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 1400);
    } catch (_) {}
  };
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div className="sch-cite-modal__backdrop" onClick={onClose}>
      <div className="sch-cite-modal" onClick={(e) => e.stopPropagation()}>
        <div className="sch-cite-modal__head">
          <div className="sch-cite-modal__eyebrow">이 항목 인용 · 引用</div>
          <button className="sch-cite-modal__close" onClick={onClose} aria-label="닫기">
            <SIcon name="close" size={18}/>
          </button>
        </div>
        <div className="sch-cite-modal__tabs" role="tablist">
          {[
            { id: 'chicago', label: 'Chicago' },
            { id: 'mla',     label: 'MLA' },
            { id: 'apa',     label: 'APA' },
            { id: 'bibtex',  label: 'BibTeX' },
          ].map(t => (
            <button key={t.id} role="tab"
              className={'sch-cite-modal__tab' + (fmt === t.id ? ' is-active' : '')}
              onClick={() => setFmt(t.id)}>
              {t.label}
            </button>
          ))}
        </div>
        <pre className="sch-cite-modal__output">{text}</pre>
        <div className="sch-cite-modal__foot">
          <span className="sch-cite-modal__hint">최근 수정일과 접속일은 자동 갱신.</span>
          <button className="sch-cite-modal__copy" onClick={copy}>
            {copied ? '복사됨 ✓' : '클립보드로 복사'}
          </button>
        </div>
      </div>
    </div>
  );
};

/* ---------- 개인 메모 (로컬 저장) ----------
   key: 항목/본문 식별자 (entryId 또는 passageId#paraIndex)
   localStorage에 단순 저장. 로그인 없이 디바이스 단위로 보존. */
const NOTES_KEY = 'sch.notes.v1';
const loadAllNotes = () => {
  try { return JSON.parse(localStorage.getItem(NOTES_KEY) || '{}'); }
  catch (_) { return {}; }
};
const saveAllNotes = (obj) => {
  try { localStorage.setItem(NOTES_KEY, JSON.stringify(obj)); }
  catch (_) {}
};

window.useNote = (key) => {
  const [val, setVal] = React.useState(() => loadAllNotes()[key] || '');
  React.useEffect(() => {
    const all = loadAllNotes();
    if (val) all[key] = val;
    else delete all[key];
    saveAllNotes(all);
  }, [key, val]);
  return [val, setVal];
};

window.NotePanel = ({ k }) => {
  const [text, setText] = window.useNote(k);
  return (
    <div className="sch-note">
      <div className="sch-note__head">
        <span>나의 메모</span>
        <span className="sch-note__meta">이 기기에만 저장됨 · 로컬</span>
      </div>
      <textarea
        className="sch-note__area"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="이 항목에 대한 메모…"
        rows={4}
      />
    </div>
  );
};
