/* AI Assistant — 앱 내 양방향 AI (모바일 바텀시트 / 데스크탑 사이드패널)
   · 현재 분석(브랜드·페르소나·SA 전략·인지도)을 컨텍스트로 주입 → "사용자 인텔리전스화"
   · 호출 경로: window.claude.complete (이 환경/공유 아티팩트) → 없으면 DataLab 프록시 fn='claude' → 없으면 안내
   · 데이터 원칙 주입: tier A/B/C·거짓 정밀 금지·추정/실측 구분을 시스템 컨텍스트로 → 정직한 답변
   · 대화 localStorage 영속. iOS: 입력 16px(자동 줌 방지)·safe-area.
*/
const { useState: useAIState, useRef: useAIRef, useEffect: useAIEffect } = React;

const AI_STORE = 'gfa-ai-chat';
const AI_SYSTEM = [
  '너는 네이버 GFA(성과형 디스플레이)·SA(검색광고) 통합 광고 전략 어시스턴트다.',
  '이 앱(GFA 페르소나 매트릭스)의 분석 결과를 근거로, 미디어플래너에게 실무적이고 간결한 한국어 조언을 한다.',
  '원칙(반드시 준수): ①측정값은 실측(tier A), 표본은 참고 렌즈(tier C), 카테고리 추정은 tier B로 구분해 말한다.',
  '②거짓 정밀 금지 — 추정을 측정처럼 단정하지 말고 불확실성을 밝힌다. ③관심사/구매의도 비중은 고정 정답이 아니라 퍼널·브랜드핏·예산을 매핑한 추천값+신뢰구간으로 다룬다.',
  '④저인지(신규) 브랜드는 SA로 모수를 쌓아 GFA 맞춤타겟으로 잇는 선순환(시장개척자) 관점으로 제안한다.',
  '답변은 길지 않게, 불릿/짧은 문단으로. 숫자는 앱 컨텍스트에 있는 값만 인용하고 없으면 "추정"이라고 표시한다.',
].join(' ');

function gfaContextText() {
  const c = window.__gfaContext;
  if (!c) return '현재 분석 컨텍스트 없음(사용자가 아직 분석을 실행하지 않음).';
  const lines = ['[현재 분석 컨텍스트]', '브랜드/시드: ' + (c.label || '-')];
  if (c.archetype) lines.push('아키타입: ' + c.archetype);
  if (c.awareness) lines.push('브랜드 인지도: ' + c.awareness + (c.awareness === '저인지' ? ' (시장개척자 전략)' : ''));
  if (c.measured != null) lines.push('실측 적재: ' + (c.measured ? 'tier A 있음' : '없음(추정/표본 기반)'));
  if (c.confidence != null) lines.push('분석 신뢰도: ' + c.confidence + '점');
  if (c.personas && c.personas.length) {
    lines.push('페르소나(' + c.personas.length + '): ' + c.personas.map(p =>
      `${p.name}[${p.tier}] 도달~${p.reach} 전환적합 ${p.fit}`).join(' / '));
  }
  if (c.chosen) lines.push('현재 선택 페르소나: ' + c.chosen);
  if (c.sa) lines.push('SA: 의도분포 ' + c.sa);
  return lines.join('\n');
}

async function askAI(history) {
  const msgs = [
    { role: 'user', content: AI_SYSTEM + '\n\n' + gfaContextText() + '\n\n위 컨텍스트를 토대로 아래 대화에 답하라.' },
    ...history.map(m => ({ role: m.role === 'ai' ? 'assistant' : 'user', content: m.text })),
  ];
  // 1) 환경/아티팩트 내장 헬퍼
  if (window.claude && typeof window.claude.complete === 'function') {
    return await window.claude.complete({ messages: msgs });
  }
  // 2) 배포 환경: Apps Script 프록시 fn=claude (Script Properties에 키)
  if (window.DataLab && window.DATALAB_CONFIG && window.DATALAB_CONFIG.useReal && window.DATALAB_CONFIG.proxyUrl) {
    try {
      const url = window.DATALAB_CONFIG.proxyUrl + '?fn=claude&p=' + encodeURIComponent(JSON.stringify({ messages: msgs }));
      const r = await fetch(url); const j = await r.json();
      if (j && (j.text || j.completion)) return j.text || j.completion;
      throw new Error('proxy claude 응답 형식 오류');
    } catch (e) { throw new Error('프록시 AI 호출 실패: ' + (e.message || e)); }
  }
  throw new Error('NO_AI');
}

function AIAssistant() {
  const [open, setOpen] = useAIState(false);
  const [msgs, setMsgs] = useAIState(() => {
    try { return JSON.parse(localStorage.getItem(AI_STORE)) || []; } catch (e) { return []; }
  });
  const [draft, setDraft] = useAIState('');
  const [busy, setBusy] = useAIState(false);
  const [err, setErr] = useAIState('');
  const scrollRef = useAIRef(null);

  useAIEffect(() => {
    try { localStorage.setItem(AI_STORE, JSON.stringify(msgs.slice(-40))); } catch (e) {}
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, open]);

  async function send(text) {
    const t = (text != null ? text : draft).trim();
    if (!t || busy) return;
    setDraft(''); setErr('');
    const next = [...msgs, { role: 'user', text: t }];
    setMsgs(next); setBusy(true);
    try {
      const reply = await askAI(next);
      setMsgs(m => [...m, { role: 'ai', text: (reply || '').trim() || '(빈 응답)' }]);
    } catch (e) {
      if ((e.message || '') === 'NO_AI') {
        setErr('AI 미연결 — 이 환경에선 내장 AI가 활성이고, 배포 사이트에선 데이터랩 프록시에 fn=claude(Claude 키)를 추가하면 됩니다.');
      } else setErr(e.message || String(e));
    }
    setBusy(false);
  }

  const QUICK = [
    '이 페르소나를 한 줄로 요약해줘',
    'GFA·SA 통합 집행 전략을 제안해줘',
    '저예산이면 어디부터 써야 해?',
    '상품명 SEO 관점에서 조언해줘',
  ];

  return (
    <>
      <button className={'aia-fab' + (open ? ' is-open' : '')} onClick={() => setOpen(o => !o)} aria-label="AI 어시스턴트">
        {open ? '✕' : <span className="aia-fab-mark">AI</span>}
      </button>

      <div className={'aia-sheet' + (open ? ' is-open' : '')} role="dialog" aria-label="GFA AI 어시스턴트">
        <div className="aia-head">
          <div className="aia-title">
            <span className="aia-dot" /> GFA 어시스턴트
            <span className="aia-ctx">{(window.__gfaContext && window.__gfaContext.label) || '분석 전'}</span>
          </div>
          <button className="aia-x" onClick={() => setOpen(false)} aria-label="닫기">✕</button>
        </div>

        <div className="aia-msgs" ref={scrollRef}>
          {msgs.length === 0 && (
            <div className="aia-empty">
              <strong>무엇이든 물어보세요.</strong>
              현재 분석한 브랜드·페르소나·SA 전략을 근거로 답합니다.
              <div className="aia-quick">
                {QUICK.map((q, i) => <button key={i} onClick={() => send(q)}>{q}</button>)}
              </div>
            </div>
          )}
          {msgs.map((m, i) => (
            <div key={i} className={'aia-msg aia-' + m.role}>
              <div className="aia-bubble">{m.text}</div>
              {m.role === 'ai' && (
                <button className="aia-copy" onClick={() => { window.safeCopy ? window.safeCopy(m.text) : navigator.clipboard?.writeText(m.text); }} title="복사">⧉</button>
              )}
            </div>
          ))}
          {busy && <div className="aia-msg aia-ai"><div className="aia-bubble aia-typing"><span></span><span></span><span></span></div></div>}
          {err && <div className="aia-err">{err}</div>}
        </div>

        <div className="aia-input">
          <textarea
            value={draft} onChange={e => setDraft(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            placeholder="질문 또는 작업 의뢰… (Enter 전송)" rows={1}
          />
          <button className="aia-send" onClick={() => send()} disabled={busy || !draft.trim()}>↑</button>
        </div>
      </div>

      <style>{`
        .aia-fab {
          position: fixed; right: 16px; z-index: 99993;
          bottom: calc(16px + env(safe-area-inset-bottom, 0px));
          width: 56px; height: 56px; border-radius: 50%; border: none; cursor: pointer;
          background: radial-gradient(70% 70% at 35% 25%, #a87bff, #6a3df0 70%);
          color: #fff; font-weight: 800; font-size: 16px;
          box-shadow: 0 8px 28px oklch(0.50 0.18 300 / 0.5), 0 0 0 1px oklch(0.7 0.12 300 / 0.3);
          display: grid; place-items: center; transition: transform .18s;
        }
        .aia-fab:active { transform: scale(0.92); }
        .aia-fab.is-open { background: oklch(0.2 0.02 290); }
        .aia-fab-mark { font-family: var(--font-mono, monospace); letter-spacing: 0.02em; }

        .aia-sheet {
          position: fixed; z-index: 99994; display: flex; flex-direction: column;
          background: oklch(0.12 0.022 295 / 0.97);
          backdrop-filter: blur(24px) saturate(140%); -webkit-backdrop-filter: blur(24px) saturate(140%);
          border: 1px solid oklch(0.66 0.16 300 / 0.34);
          transform: translateY(110%); opacity: 0; pointer-events: none;
          transition: transform .3s cubic-bezier(.2,.7,.2,1), opacity .3s;
        }
        /* 모바일: 바텀시트 */
        .aia-sheet {
          left: 0; right: 0; bottom: 0;
          height: 82vh; border-radius: 18px 18px 0 0;
          padding-bottom: env(safe-area-inset-bottom, 0px);
        }
        .aia-sheet.is-open { transform: translateY(0); opacity: 1; pointer-events: auto; }
        /* 데스크탑: 우측 사이드 패널 */
        @media (min-width: 640px) {
          .aia-sheet {
            left: auto; right: 16px; bottom: 16px; width: 400px; height: 600px; max-height: 82vh;
            border-radius: 16px; transform: translateY(20px) scale(0.98);
          }
          .aia-sheet.is-open { transform: translateY(0) scale(1); }
        }

        .aia-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; border-bottom: 1px solid var(--border, oklch(0.3 0.02 290 / 0.4)); }
        .aia-title { display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 700; color: #f4f1fb; }
        .aia-dot { width: 8px; height: 8px; border-radius: 50%; background: #a87bff; box-shadow: 0 0 10px #a87bff; }
        .aia-ctx { font-size: 10px; font-family: var(--font-mono, monospace); color: oklch(0.82 0.08 300); background: oklch(0.6 0.16 300 / 0.16); padding: 2px 8px; border-radius: 10px; margin-left: 4px; }
        .aia-x { background: none; border: none; color: oklch(0.7 0.03 290); font-size: 17px; cursor: pointer; width: 32px; height: 32px; }

        .aia-msgs { flex: 1; overflow-y: auto; padding: 14px 14px 6px; display: flex; flex-direction: column; gap: 10px; -webkit-overflow-scrolling: touch; }
        .aia-empty { color: oklch(0.74 0.03 290); font-size: 13px; line-height: 1.6; text-align: center; padding: 18px 8px; }
        .aia-empty strong { display: block; color: #f0ecf8; font-size: 15px; margin-bottom: 4px; }
        .aia-quick { display: flex; flex-direction: column; gap: 7px; margin-top: 16px; }
        .aia-quick button { padding: 11px 13px; border-radius: 11px; border: 1px solid oklch(0.66 0.16 300 / 0.3); background: oklch(0.6 0.16 300 / 0.08); color: #e9e3f5; font-size: 13px; text-align: left; cursor: pointer; font-family: inherit; }
        .aia-quick button:active { background: oklch(0.6 0.16 300 / 0.2); }

        .aia-msg { display: flex; }
        .aia-user { justify-content: flex-end; }
        .aia-bubble { max-width: 85%; padding: 10px 13px; border-radius: 14px; font-size: 14px; line-height: 1.55; white-space: pre-wrap; word-break: break-word; }
        .aia-user .aia-bubble { background: linear-gradient(135deg, #6a3df0, #8a5cf0); color: #fff; border-bottom-right-radius: 5px; }
        .aia-ai .aia-bubble { background: oklch(0.18 0.02 290); color: #ece7f6; border: 1px solid oklch(0.5 0.05 290 / 0.3); border-bottom-left-radius: 5px; }
        .aia-ai { flex-direction: column; align-items: flex-start; gap: 3px; }
        .aia-copy { align-self: flex-start; background: none; border: none; color: oklch(0.62 0.04 290); font-size: 13px; cursor: pointer; padding: 1px 4px; }
        .aia-copy:active { color: #a87bff; }
        .aia-typing { display: flex; gap: 4px; align-items: center; }
        .aia-typing span { width: 7px; height: 7px; border-radius: 50%; background: #a87bff; animation: aiaBlink 1.2s infinite; }
        .aia-typing span:nth-child(2) { animation-delay: .2s; } .aia-typing span:nth-child(3) { animation-delay: .4s; }
        @keyframes aiaBlink { 0%,60%,100% { opacity: .3; } 30% { opacity: 1; } }
        .aia-err { font-size: 12px; color: oklch(0.75 0.16 25); background: oklch(0.68 0.21 22 / 0.08); border: 1px solid oklch(0.68 0.21 22 / 0.25); padding: 9px 11px; border-radius: 10px; line-height: 1.5; }

        .aia-input { display: flex; gap: 8px; padding: 10px 12px 12px; border-top: 1px solid var(--border, oklch(0.3 0.02 290 / 0.4)); align-items: flex-end; }
        .aia-input textarea {
          flex: 1; resize: none; max-height: 120px; box-sizing: border-box;
          background: oklch(0.08 0.015 290); border: 1px solid oklch(0.5 0.06 290 / 0.4);
          border-radius: 12px; color: #f4f1fb; padding: 11px 13px;
          font-size: 16px; /* iOS 포커스 시 자동 줌 방지 */ font-family: inherit; line-height: 1.4;
        }
        .aia-input textarea:focus { outline: none; border-color: #8a5cf0; }
        .aia-send { flex-shrink: 0; width: 42px; height: 42px; border-radius: 12px; border: none; cursor: pointer;
          background: linear-gradient(135deg, #6a3df0, #8a5cf0); color: #fff; font-size: 18px; font-weight: 700; }
        .aia-send:disabled { opacity: .4; cursor: default; }
      `}</style>
    </>
  );
}

Object.assign(window, { AIAssistant });

// 전역 마운트 — 위저드/고급 모드 어디서나 뜨는 독립 루트(앱 루트와 분리)
(function mountAI() {
  if (window.__aiAssistantMounted) return;
  window.__aiAssistantMounted = true;
  try {
    var d = document.createElement('div');
    d.id = 'ai-assistant-root';
    document.body.appendChild(d);
    ReactDOM.createRoot(d).render(React.createElement(AIAssistant));
  } catch (e) { console.warn('[AIAssistant] mount failed', e); }
})();

