// editor.jsx — DOC-03 문서 에디터

const { Icon, Pill, Tag, Avatar, Button } = window.RAlly;

const COL_LABEL = { todo: '시작 전', doing: '작성 중', review: '검토 중', done: '완주' };
const CAT_LABEL = { sop: 'SOP', risk: '위험관리', tech: '기술문서', capa: 'CAPA' };

const Editor = ({ go }) => {
  const [tab, setTab] = React.useState('comments');
  const [aiAccepted, setAiAccepted] = React.useState(false);
  const [showShareToast, setShareToast] = React.useState(false);
  const docId = (typeof window !== 'undefined' && window.__RALLY_DOC) || null;
  const [doc, setDoc] = React.useState(null);
  const [comments, setComments] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const bodyRef = React.useRef(null);
  const bodyInit = React.useRef(false);
  const [bodyHtml, setBodyHtml] = React.useState('');
  const [saved, setSaved] = React.useState(true);

  React.useEffect(() => {
    if (bodyRef.current && bodyHtml && !bodyInit.current) {
      bodyRef.current.innerHTML = bodyHtml;
      bodyInit.current = true;
    }
  }, [bodyHtml]);

  const me = (window.RAlly.getUser && window.RAlly.getUser()) || null;

  const saveBody = () => {
    if (!docId || !bodyRef.current) return;
    // 권한 게이트는 서버가 세션에서 판정한다(클라이언트는 역할을 보내지 않는다).
    const headers = { 'Content-Type': 'application/json' };
    fetch('/api/doc/' + docId + '/body', {
      method: 'POST', headers,
      body: JSON.stringify({ body: bodyRef.current.innerHTML }),
    }).then((r) => {
      if (!r.ok) { r.json().then((e) => alert(e.error || '저장 권한이 없습니다.')).catch(() => alert('저장 실패')); return; }
      setSaved(true);
    }).catch(() => {});
  };

  const loadComments = React.useCallback(() => {
    if (!docId) return;
    fetch('/api/doc/' + docId + '/comments').then((r) => r.json()).then((d) => setComments(d.comments || [])).catch(() => {});
  }, [docId]);

  React.useEffect(() => {
    if (docId) {
      fetch('/api/review/doc?id=' + docId).then((r) => r.json()).then(setDoc).catch(() => {});
      fetch('/api/doc/' + docId + '/body').then((r) => r.json()).then((d) => { if (d.ok) setBodyHtml(d.body); }).catch(() => {});
      loadComments();
    }
  }, [docId, loadComments]);

  const postComment = () => {
    if (!draft.trim() || !docId) return;
    const u = me || { name: '사용자', initials: '나' };
    fetch('/api/doc/' + docId + '/comment', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ author: u.name, initials: u.initials, text: draft.trim() }),
    }).then((r) => r.json()).then((d) => { setComments(d.comments || []); setDraft(''); }).catch(() => {});
  };
  const requestReview = () => {
    if (!docId) return;
    // actor/actor_role은 보내지 않는다 — 서버가 세션에서 도출한다(역할 위조 방지).
    fetch('/api/kanban/move', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ doc_id: docId, col: 'review' }),
    }).then((r) => r.json()).then((d) => { if (d.ok) go('kanban'); else alert(d.error); }).catch(() => {});
  };
  const [regen, setRegen] = React.useState(null); // null | busy | done | err
  const regenerate = () => {
    if (!docId) return;
    setRegen('busy');
    fetch('/api/doc/' + docId + '/regenerate', { method: 'POST' })
      .then((r) => r.json()).then((d) => {
        if (d.ok && d.body) {
          if (bodyRef.current) bodyRef.current.innerHTML = d.body;
          bodyInit.current = true; setBodyHtml(d.body); setSaved(true); setRegen('done');
        } else { setRegen('err'); alert(d.error || '재생성 빌더가 없는 문서종입니다.'); }
      }).catch(() => setRegen('err'));
  };

  React.useEffect(() => {
    if (showShareToast) {
      const t = setTimeout(() => setShareToast(false), 2400);
      return () => clearTimeout(t);
    }
  }, [showShareToast]);

  const title = doc ? doc.name : 'R-018 · 인터페이스 오작동 위험 평가 및 통제 방안';
  const cat = doc ? (CAT_LABEL[doc.category] || doc.category) : '위험관리';
  const colLabel = doc ? (COL_LABEL[doc.kanban_col] || '검토 중') : '검토 중';

  // 개발자(AUTHOR) 권한 게이트: 열린 문서가 개발 문서(DEV_DOCS)가 아니면 편집 차단.
  // doc_type은 review/doc 응답 우선, 없으면 칸반 클릭 시 설정한 __RALLY_DOC_TYPE 폴백.
  const docType = (doc && doc.doc_type) || (typeof window !== 'undefined' && window.__RALLY_DOC_TYPE) || null;
  const blocked = !!(me && me.role === 'AUTHOR' && docType && !(window.RAlly.DEV_DOCS || []).includes(docType));

  return (
    <div>
      {/* Doc header */}
      <div className="editor-head">
        <div className="editor-head__row">
          <span
            onClick={() => go('kanban')}
            style={{ fontSize: 11, color: 'var(--ink-3)', cursor: 'pointer', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}
          >← STAGE 02 보드로</span>
          <Tag>{cat}</Tag>
          <Pill variant="coral">{colLabel}</Pill>
          {doc && doc.deadline && <Pill variant="red" className="tabular">마감 {doc.deadline}</Pill>}
          <span style={{ flex: 1 }} />
          <span style={{ fontSize: 11, color: saved ? 'var(--ink-3)' : 'var(--coral)', letterSpacing: '0.06em', fontWeight: 600 }}>
            <span className="row" style={{ gap: 6, display: 'inline-flex' }}>
              <span style={{ width: 6, height: 6, background: saved ? 'var(--green)' : 'var(--coral)', borderRadius: 999 }} />
              {saved ? '저장됨' : '미저장 변경'}
            </span>
          </span>
          <Button variant={saved ? 'ghost' : 'soft'} size="sm" icon="check" onClick={saveBody} disabled={blocked} title={blocked ? 'RA 담당 문서 — 개발자 계정은 저장할 수 없습니다.' : undefined}>저장</Button>
          <Button variant="ghost" size="sm" icon="download" onClick={() => { if (docId) window.location.href = '/api/doc/' + docId + '/file'; }}>다운로드</Button>
          <Button variant="ghost" size="sm" icon="download" onClick={() => { if (docId) window.location.href = '/api/doc/' + docId + '/hwpx'; }}>HWPX</Button>
          <Button variant="primary" size="sm" iconRight="arrow_right" onClick={requestReview}>검토 요청</Button>
        </div>
        <div>
          <div className="editor-head__title" contentEditable suppressContentEditableWarning style={{ outline: 'none' }}>
            {title}
          </div>
          <div className="editor-head__meta" style={{ marginTop: 8 }}>
            <span><strong style={{ color: 'var(--ink)' }}>{cat}</strong></span>
            <span>상태 · {colLabel}</span>
            <span>담당 {doc ? doc.author : '—'}</span>
            {doc && doc.deadline && <span>마감 · {doc.deadline}</span>}
            <div className="row" style={{ gap: 4 }}>
              <Avatar initials="박지" size="sm" />
              <Avatar initials="혜" size="sm" variant="coral" />
              <Avatar initials="김민" size="sm" />
              <span style={{ fontSize: 11, color: 'var(--ink-3)', marginLeft: 4 }}>3명 활성</span>
            </div>
          </div>
        </div>
      </div>

      {/* 개발자 권한 안내 배너 — RA 담당 문서일 때 */}
      {blocked && (
        <div className="row" style={{ gap: 10, padding: '10px 16px', background: 'var(--coral-soft, #FBEAE4)',
          borderBottom: '1px solid var(--coral-line, #F0D9C8)', color: 'var(--coral-2, #b94a2c)', fontSize: 12.5 }}>
          <Icon name="alert" size={15} />
          <span>이 문서는 RA 담당입니다. 개발자 계정은 기술문서(제품표준서)·SRS·SDS 등 개발 문서를 작성합니다.</span>
        </div>
      )}

      {/* Toolbar */}
      <div className="editor-toolbar">
        <button className="tool-btn"><Icon name="h1" size={15} /></button>
        <button className="tool-btn"><Icon name="h2" size={15} /></button>
        <span className="tool-divider" />
        <button className="tool-btn"><Icon name="bold" size={15} /></button>
        <button className="tool-btn"><Icon name="italic" size={15} /></button>
        <button className="tool-btn"><Icon name="underline" size={15} /></button>
        <span className="tool-divider" />
        <button className="tool-btn"><Icon name="list" size={15} /></button>
        <button className="tool-btn"><Icon name="table" size={15} /></button>
        <button className="tool-btn"><Icon name="link" size={15} /></button>
        <span style={{ flex: 1 }} />
        <button className="tool-btn">@ 멘션</button>
        <button className="tool-btn tool-btn--ai">
          <Icon name="sparkles" size={14} /> RAlly AI 도움
        </button>
      </div>

      {/* Body */}
      <div className="editor-shell">
        <div className="editor-main">
          <div className="editor-canvas">
            <div className="doc" contentEditable={!blocked} suppressContentEditableWarning
              ref={bodyRef} onInput={() => setSaved(false)}
              style={{ outline: "none", minHeight: 360 }} />

            {/* In-doc presence indicator */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '14px 4px', fontSize: 12, color: 'var(--ink-3)' }}>
              <span className="row" style={{ gap: 4 }}>
                <span style={{ width: 6, height: 6, background: 'var(--coral)', borderRadius: 999 }} />
                김혜진 · §3 통제 방안 보고 있어요
              </span>
            </div>
          </div>
        </div>

        {/* Right panel */}
        <aside className="editor-aside">
          <div className="aside-tabs">
            <button className={'aside-tab' + (tab === 'comments' ? ' aside-tab--active' : '')} onClick={() => setTab('comments')}>코멘트 · {comments.length}</button>
            <button className={'aside-tab' + (tab === 'activity' ? ' aside-tab--active' : '')} onClick={() => setTab('activity')}>활동</button>
            <button className={'aside-tab' + (tab === 'meta' ? ' aside-tab--active' : '')} onClick={() => setTab('meta')}>메타</button>
          </div>

          {tab === 'comments' && (
            <div className="aside-body">
              {/* AI 자동 작성 — 품목 정보 기반 실제수준 본문 재생성 */}
              <div className="ai-suggest">
                <div className="ai-suggest__head">
                  <Icon name="sparkles" size={14} style={{ color: 'var(--coral)' }} />
                  <span className="ai-suggest__label">RAlly AI 자동 작성</span>
                  {regen === 'done' && <span className="ai-suggest__time" style={{ color: 'var(--coral)' }}>완료</span>}
                </div>
                <div className="ai-suggest__body">
                  {regen === 'done'
                    ? '품목 정보 기반 실제 심사 수준 본문으로 다시 작성했습니다. 증거값([입력 필요])은 직접 채워주세요.'
                    : regen === 'err'
                      ? '이 문서종은 아직 자동 작성 빌더가 없습니다(추후 확장).'
                      : '이 문서를 품목 정보 기반 실제 심사 수준 본문으로 자동 작성합니다. 표준 구조·지침 내용은 자동, 시험결과·서명 등 증거는 [입력 필요]로 표시됩니다.'}
                </div>
                <div className="ai-suggest__actions">
                  <Button variant="accent" size="sm" onClick={regenerate} disabled={regen === 'busy'}>
                    {regen === 'busy' ? '작성 중…' : regen === 'done' ? '다시 작성' : '자동 작성'}
                  </Button>
                </div>
              </div>

              {/* 실 코멘트 */}
              {comments.length === 0 && (
                <div className="muted" style={{ fontSize: 12.5, padding: '8px 2px' }}>아직 코멘트가 없어요. 아래에서 첫 코멘트를 남겨보세요.</div>
              )}
              {comments.map((cm) => (
                <div key={cm.id} className="comment" style={cm.variant === 'coral' ? { borderColor: 'var(--coral-line)' } : null}>
                  <div className="comment__head">
                    <Avatar initials={cm.author_initials} variant={cm.variant} />
                    <span className="comment__name" style={cm.variant === 'coral' ? { color: 'var(--coral-2)' } : null}>{cm.author}</span>
                    <span className="comment__time" style={{ marginLeft: 'auto' }}>{(cm.created_at || '').slice(5, 16).replace('T', ' ')}</span>
                  </div>
                  <div className="comment__body">{cm.text}</div>
                </div>
              ))}

              {/* Comment input (작동) */}
              <div style={{ marginTop: 'auto', borderTop: '1px solid var(--line)', paddingTop: 12, position: 'sticky', bottom: 0, background: 'var(--surface)' }}>
                <textarea
                  value={draft}
                  onChange={(e) => setDraft(e.target.value)}
                  onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') postComment(); }}
                  placeholder="@멘션 또는 코멘트…"
                  style={{ width: '100%', border: '1px solid var(--line-2)', borderRadius: 8, padding: 10, fontSize: 13, minHeight: 60, fontFamily: 'inherit', resize: 'vertical', outline: 'none' }}
                />
                <div className="row" style={{ marginTop: 8, gap: 6 }}>
                  <Button variant="primary" size="sm" onClick={postComment}>코멘트</Button>
                  <span className="muted-2" style={{ fontSize: 11, marginLeft: 'auto' }}>⌘⏎ 보내기</span>
                </div>
              </div>
            </div>
          )}

          {tab === 'activity' && (
            <div className="aside-body">
              {comments.length === 0 && (
                <div className="muted" style={{ fontSize: 12.5, padding: '8px 2px' }}>아직 활동 기록이 없어요. 코멘트·검토 활동이 여기에 쌓입니다.</div>
              )}
              {comments.map((cm) => (
                <ActivityItem key={cm.id} time={(cm.created_at || '').slice(5, 16).replace('T', ' ')}
                  text={<><strong>{cm.author}</strong>: {cm.text}</>} tone={cm.variant} />
              ))}
            </div>
          )}

          {tab === 'meta' && (
            <div className="aside-body">
              <MetaRow label="문서" value={title} />
              <MetaRow label="상태" value={colLabel} />
              <MetaRow label="버전" value={doc ? ('v' + (doc.current_version || 1)) : 'v1'} />
              <MetaRow label="카테고리" value={cat} />
              <MetaRow label="담당" value={doc ? doc.author : '박지수'} />
              <MetaRow label="검토자" value={doc && doc.reviewer ? doc.reviewer : '미지정'} coral />
              {doc && doc.deadline && <MetaRow label="마감" value={doc.deadline} tone="coral" />}
            </div>
          )}
        </aside>
      </div>

      {showShareToast && (
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
          background: 'var(--navy)', color: 'var(--on-navy)',
          padding: '10px 16px', borderRadius: 6, fontSize: 13,
          display: 'flex', alignItems: 'center', gap: 10,
          boxShadow: 'var(--shadow-pop)', zIndex: 100,
        }}>
          <Icon name="check" size={14} style={{ color: 'var(--coral)' }} />
          공유 링크가 클립보드에 복사되었어요
          <span style={{ fontSize: 11, color: 'var(--on-navy-3)', marginLeft: 8, fontFamily: 'var(--font-mono)' }}>rally.io/s/4a8x</span>
        </div>
      )}
    </div>
  );
};

const ActivityItem = ({ time, text, tone }) => (
  <div className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
    <span style={{
      width: 6, height: 6, marginTop: 7,
      borderRadius: 999,
      background: tone === 'coral' ? 'var(--coral)' : 'var(--ink-3)',
      flexShrink: 0,
    }} />
    <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-2)', lineHeight: 1.5 }}>
      <span style={{ fontSize: 11, color: 'var(--ink-3)', marginRight: 8, letterSpacing: '0.04em' }}>{time}</span>
      {text}
    </div>
  </div>
);

const MetaRow = ({ label, value, tone, coral }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 3, paddingBottom: 10, borderBottom: '1px solid var(--line)' }}>
    <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.10em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{label}</span>
    <span style={{
      fontSize: 13,
      color: tone === 'coral' ? 'var(--coral)' : coral ? 'var(--coral-2)' : 'var(--ink)',
      fontWeight: tone === 'coral' ? 600 : 500,
    }}>{value}</span>
  </div>
);

window.RAlly.Editor = Editor;
