/* global React */

// 자비스 PM + 카피라이터 + QA 3인 회의 패널
const AGENTS = {
  jarvis: { name: '자비스', role: 'PM', color: '#0F0D05', text: '#FFD93D' },
  copy:   { name: '한카피', role: '카피라이터', color: '#D94125', text: '#fff' },
  qa:     { name: '김검수', role: 'QA 리드',   color: '#2F4FBA', text: '#fff' },
};

const SCRIPT = [
  { who: 'jarvis', kind: 'normal', text: '📍 런칭 회의 시작합니다. 제이씨드 재테크 클래스 — 11세션 만에 배포 준비 완료. 오늘 안건은 "톤 확정 + 배포 패키지 점검" 두 가지입니다.' },
  { who: 'jarvis', kind: 'win', text: '✅ 톤앤매너 확정: 토스/토스증권 결 — 화이트 베이스, 무채색 그레이 스케일, 옐로우(#FFD600)는 액센트 1색만. 다크 노이즈/네온 빼고, 여백 + 타이포 위계로 정보 밀도 확보.' },
  { who: 'copy', kind: 'critical', text: '히어로 카피 — "직장인이 월 1억 모으는 방법, 같이 공부하는 클래스입니다." 직설적이라 좋아요. 단, "1억"은 시선 끄는 후크지 약속이 아닙니다. 푸터 법적 고지 3줄(참고자료 · 교육 목적 · 학습 참고용)이 뒤를 받쳐주는 구조라 OK.',
    diff: [
      { tag: 'bad', text: '"월 1억 만들어드립니다" — 약속형 (금감원 광고심의 위험)' },
      { tag: 'good', text: '"월 1억 모으는 방법을 같이 공부합니다" — 학습형 (현재 카피)' },
    ]},
  { who: 'qa', kind: 'critical', text: '배포 전 체크리스트 점검 — (1) ✅ index.html 리네임 완료, 한글 URL 이슈 해결 (2) ✅ manifest.webmanifest + favicon.svg + icon-192/512 PNG 생성 (3) ✅ OG 이미지 1200×630 생성 (4) ✅ vercel.json 헤더 + 리다이렉트 (5) ✅ robots.txt + sitemap.xml.' },
  { who: 'qa', kind: 'normal', text: '⚠️ 운영 권고 — Babel standalone은 dev 빌드. 트래픽 들어오면 Vite로 사전 트랜스파일 권장. 지금은 MVP 검증용으로 충분합니다.' },
  { who: 'copy', kind: 'win', text: '✅ 카피 일관성 확보: "베이스캠프"는 메인 키워드로 고정. 푸터·OG·메타 description까지 단일 톤으로 통일했습니다. 검색 결과에서 "베이스캠프"로 회상될 수 있어요.' },
  { who: 'jarvis', kind: 'normal', text: '포트폴리오 정책 — "왜 숫자는 공개 안 하는가" 섹션 유지. 커뮤니티에서 "금액 공개" 요청 들어오면 이 페이지로 정책 응답하는 플로우, 운영팀에 인계.' },
  { who: 'jarvis', kind: 'win', text: '📦 배포 산출물 12종: index.html · site.css · responsive.css · pages.jsx · crit.jsx · data.js · tweaks-panel.jsx · favicon.svg · icon-192/512.png · og-image.png · manifest.webmanifest · vercel.json · robots.txt · sitemap.xml · README.md · DEPLOY.md.' },
  { who: 'jarvis', kind: 'normal', text: '🚀 다음 분기 옵션: ① Vercel 실제 배포 ② 결제·멤버십 (토스페이먼츠) ③ 관리자 대시보드 ④ 칼럼 CMS ⑤ 실 썸네일 촬영 디렉션. 한 줄 지시 주시면 바로 진입합니다. 회의 끝.' },
];

function CritPanel({ open, onClose }) {
  const [messages, setMessages] = React.useState([]);
  const [idx, setIdx] = React.useState(0);
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);

  // 패널이 열리면 대본 자동 재생
  React.useEffect(() => {
    if (!open) return;
    if (idx >= SCRIPT.length) return;
    const delay = idx === 0 ? 400 : 1600 + Math.random() * 700;
    const t = setTimeout(() => {
      setMessages(m => [...m, SCRIPT[idx]]);
      setIdx(i => i + 1);
    }, delay);
    return () => clearTimeout(t);
  }, [open, idx]);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = () => {
    if (!input.trim()) return;
    setMessages(m => [...m, { who: 'user', kind: 'me', text: input }]);
    const reply = input;
    setInput('');
    setTimeout(() => {
      setMessages(m => [...m, {
        who: 'jarvis', kind: 'normal',
        text: '접수했습니다 — "' + reply.slice(0, 30) + (reply.length > 30 ? '...' : '') + '" 반영본에 포함시키겠습니다.'
      }]);
    }, 900);
  };

  return (
    <div className={'crit-panel' + (open ? ' open' : '')}>
      <div className="crit-head">
        <div className="crit-head-title">
          <h3>🎙 런칭 회의방</h3>
          <div className="sub">Jarvis · Copy · QA</div>
        </div>
        <button className="crit-close" onClick={onClose}>×</button>
      </div>

      <div className="crit-agents">
        {Object.values(AGENTS).map(a => (
          <div key={a.name} className="crit-agent">
            <div className="av" style={{background:a.color, color:a.text}}>{a.name[0]}</div>
            {a.name} <span style={{color:'var(--ink-400)', fontWeight:400}}>· {a.role}</span>
          </div>
        ))}
      </div>

      <div className="crit-messages" ref={scrollRef}>
        {messages.map((m, i) => {
          if (m.kind === 'me') {
            return (
              <div key={i} className="crit-msg" style={{flexDirection:'row-reverse'}}>
                <div className="crit-av" style={{background:'var(--y-500)', color:'var(--ink-900)'}}>나</div>
                <div className="crit-body" style={{textAlign:'right'}}>
                  <div className="crit-bubble" style={{background:'var(--y-200)', borderColor:'var(--y-300)', borderRadius:'14px 4px 14px 14px', display:'inline-block', textAlign:'left'}}>{m.text}</div>
                </div>
              </div>
            );
          }
          const a = AGENTS[m.who];
          return (
            <div key={i} className="crit-msg">
              <div className="crit-av" style={{background:a.color, color:a.text}}>{a.name[0]}</div>
              <div className="crit-body">
                <div className="crit-name">{a.name} <span className="crit-role">· {a.role}</span></div>
                <div className={'crit-bubble' + (m.kind === 'critical' ? ' critical' : '') + (m.kind === 'win' ? ' win' : '')}>
                  {m.kind === 'critical' && <div className="crit-tag">⚠ 딴지</div>}
                  {m.kind === 'win' && <div className="crit-tag">✓ 합격</div>}
                  {m.text}
                  {m.diff && (
                    <div className="crit-diff">
                      {m.diff.map((d, j) => (
                        <div key={j} className="diff-row">
                          <span className={'diff-tag ' + d.tag}>{d.tag === 'bad' ? 'AS-IS' : 'TO-BE'}</span>
                          <span className={'diff-text ' + d.tag}>{d.text}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          );
        })}
        {idx < SCRIPT.length && messages.length > 0 && (
          <div className="crit-msg">
            <div className="crit-av" style={{background: AGENTS[SCRIPT[idx].who].color, color: AGENTS[SCRIPT[idx].who].text}}>{AGENTS[SCRIPT[idx].who].name[0]}</div>
            <div className="crit-body">
              <div className="crit-name">{AGENTS[SCRIPT[idx].who].name}</div>
              <div className="crit-bubble" style={{display:'inline-flex', gap:4, padding:'14px 16px'}}>
                <span style={{width:6, height:6, borderRadius:'50%', background:'var(--ink-400)', animation:'ping 1.2s infinite'}}/>
                <span style={{width:6, height:6, borderRadius:'50%', background:'var(--ink-400)', animation:'ping 1.2s infinite 0.2s'}}/>
                <span style={{width:6, height:6, borderRadius:'50%', background:'var(--ink-400)', animation:'ping 1.2s infinite 0.4s'}}/>
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="crit-input">
        <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && send()} placeholder="자비스에게 반박하거나 지시하세요..." />
        <button className="btn btn-dark" onClick={send}>전송</button>
      </div>
    </div>
  );
}

window.CritPanel = CritPanel;
