/* ============================================================
   社内FAQ（Q&A）
   - AIに質問：社内ナレッジ（手順/事例/FAQ/議事録＋素材）から AI が回答＋出典
   - みんなのQ&A：解決しなければ掲示板に投稿→同僚が回答→採用でFAQ蓄積
   ============================================================ */
const KB_LABEL_FAQ = { proposal: '提案文', recommend: '推薦用', quote: '見積もり用', howto: '手順', case: '事例', faq: 'FAQ', minutes: '議事録' };

/* AIの回答に付ける「根拠ナレッジ」チップ */
function SourceChips({ sources }) {
  if (!sources || !sources.length) return null;
  return (
    <div style={{ marginTop: 12 }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: '#9aa1ab', marginBottom: 6 }}>{t('faq.ask.sources')}</div>
      <div style={{ display: 'flex', gap: 7, flexWrap: 'wrap' }}>
        {sources.map((s, i) => (
          <span key={s.id || i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 600, color: '#5b54b8', background: '#eef0fe', border: '1px solid #e0e2fb', padding: '3px 9px', borderRadius: 7 }}>
            <span style={{ fontSize: 10, fontWeight: 700, color: '#fff', background: '#7b78dd', padding: '0 6px', borderRadius: 4 }}>{KB_LABEL_FAQ[s.kb] || s.kb}</span>
            {s.title}
          </span>
        ))}
      </div>
    </div>
  );
}

/* AIに質問するボックス（上部）。解決しなければそのまま掲示板へ投稿できる */
function AiAskBox() {
  const { askFaq, postQuestion, showToast } = useStore();
  const [q, setQ] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [result, setResult] = React.useState(null); // {answer, sources, enough}
  const [posting, setPosting] = React.useState(false);

  const ask = async () => {
    const question = q.trim();
    if (!question || loading) return;
    setLoading(true); setResult(null);
    try { setResult(await askFaq(question)); }
    catch (e) { showToast(e.message || 'エラーが発生しました', 'x'); }
    finally { setLoading(false); }
  };
  const toBoard = async () => {
    if (posting || !q.trim()) return;
    setPosting(true);
    try {
      await postQuestion({ title: q.trim(), aiAnswer: (result && result.answer) || '', aiSources: (result && result.sources) || [] });
      setQ(''); setResult(null);
    } catch (e) { showToast(e.message || 'エラーが発生しました', 'x'); }
    finally { setPosting(false); }
  };

  return (
    <Card style={{ marginBottom: 18 }} pad={18}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 12 }}>
        <div style={{ width: 30, height: 30, borderRadius: 9, background: 'linear-gradient(135deg,#6d68e0,#8b5cf6)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}>
          <Icon name="spark" size={17} stroke={2.2} style={{ color: '#fff' }} />
        </div>
        <div style={{ fontSize: 15, fontWeight: 700, color: '#1c2027' }}>{t('faq.ask.title')}</div>
      </div>
      <textarea value={q} onChange={(e) => setQ(e.target.value)} rows={3}
        onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') ask(); }}
        placeholder={t('faq.ask.placeholder')}
        style={{ width: '100%', resize: 'vertical', border: '1px solid #e2e5ea', borderRadius: 10, padding: '11px 13px', fontSize: 13.5, lineHeight: 1.6, color: '#2b2f38', outline: 'none', fontFamily: 'inherit' }} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
        <Button variant="primary" icon="spark" onClick={ask} disabled={loading || !q.trim()}>
          {loading ? t('faq.ask.asking') : t('faq.ask.btn')}
        </Button>
      </div>

      {result && (
        <div style={{ marginTop: 14, padding: '15px 16px', background: '#faf9ff', border: '1px solid #ecebfb', borderRadius: 12 }}>
          <div style={{ fontSize: 11.5, fontWeight: 700, color: '#6d68e0', marginBottom: 7, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="spark" size={13} stroke={2.2} />{t('faq.ask.answerTitle')}
          </div>
          {result.answer
            ? <div style={{ fontSize: 13.5, lineHeight: 1.75, color: '#2b2f38', whiteSpace: 'pre-wrap' }}>{result.answer}</div>
            : <div style={{ fontSize: 13, color: '#9aa1ab' }}>{t('faq.ask.noSource')}</div>}
          {result.enough === false && (
            <div style={{ marginTop: 10, fontSize: 12, color: '#b45309', background: '#fdf6ec', border: '1px solid #f6e6cc', borderRadius: 8, padding: '8px 11px', lineHeight: 1.6 }}>
              <Icon name="alert" size={13} stroke={2} style={{ verticalAlign: '-2px', marginRight: 5 }} />{t('faq.ask.lowConfidence')}
            </div>
          )}
          <SourceChips sources={result.sources} />
          <div style={{ display: 'flex', gap: 9, marginTop: 14, flexWrap: 'wrap' }}>
            <Button variant="primary" icon="inbox" onClick={toBoard} disabled={posting}>{t('faq.ask.toBoard')}</Button>
            <Button variant="default" onClick={() => { setQ(''); setResult(null); }}>{t('faq.ask.again')}</Button>
          </div>
        </div>
      )}
    </Card>
  );
}

/* 回答の入力欄（質問ごと） */
function AnswerComposer({ qId }) {
  const { answerQuestion, showToast } = useStore();
  const [body, setBody] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const submit = async () => {
    const b = body.trim();
    if (!b || busy) return;
    setBusy(true);
    try { await answerQuestion(qId, b); setBody(''); }
    catch (e) { showToast(e.message || 'エラーが発生しました', 'x'); }
    finally { setBusy(false); }
  };
  return (
    <div style={{ display: 'flex', gap: 8, marginTop: 12, alignItems: 'flex-end' }}>
      <textarea value={body} onChange={(e) => setBody(e.target.value)} rows={2}
        onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') submit(); }}
        placeholder={t('faq.addAnswer.placeholder')}
        style={{ flex: 1, resize: 'vertical', border: '1px solid #e2e5ea', borderRadius: 10, padding: '9px 12px', fontSize: 13, lineHeight: 1.6, color: '#2b2f38', outline: 'none', fontFamily: 'inherit' }} />
      <Button variant="primary" size="sm" icon="check" onClick={submit} disabled={busy || !body.trim()}>{t('faq.addAnswer.btn')}</Button>
    </div>
  );
}

/* 1件の回答 */
function AnswerRow({ qId, ans, canAccept, resolved }) {
  const { acceptAnswer, showToast } = useStore();
  const D = window.APP_DATA;
  const by = D.user(ans.answeredBy);
  const accept = async () => { try { await acceptAnswer(qId, ans.id); } catch (e) { showToast(e.message || 'エラーが発生しました', 'x'); } };
  return (
    <div style={{ display: 'flex', gap: 11, padding: '12px 0', borderTop: '1px solid #f4f5f7' }}>
      {by ? <Avatar user={by} size={30} /> : <div style={{ width: 30, height: 30, borderRadius: '50%', background: '#eceef1', flex: '0 0 auto' }} />}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: '#2b2f38' }}>{by ? by.name : '—'}</span>
          <span style={{ fontSize: 11, color: '#aab0ba' }}>{fmtDateTime(ans.createdAt)}</span>
          {ans.accepted && (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10.5, fontWeight: 700, color: '#15803d', background: '#e3f5e9', padding: '1px 8px', borderRadius: 5 }}>
              <Icon name="check" size={11} stroke={2.6} />{t('faq.bestAnswer')}
            </span>
          )}
        </div>
        <div style={{ fontSize: 13.5, lineHeight: 1.7, color: '#2b2f38', marginTop: 4, whiteSpace: 'pre-wrap' }}>{ans.body}</div>
      </div>
      {canAccept && !resolved && (
        <Button variant="default" size="sm" icon="check" onClick={accept} style={{ alignSelf: 'flex-start' }}>{t('faq.accept')}</Button>
      )}
    </div>
  );
}

/* 1件の質問（折りたたみカード） */
function QuestionCard({ q }) {
  const { currentUser, isManager, isAdmin, reopenQuestion, removeQuestion, showToast, navigate } = useStore();
  const D = window.APP_DATA;
  const [open, setOpen] = React.useState(false);
  const asker = D.user(q.askedBy);
  const answers = q.answers || [];
  const resolved = q.status === 'resolved';
  const mine = currentUser && q.askedBy === currentUser.id;
  const canAccept = !!(mine || isManager);
  const canDelete = !!(mine || isAdmin);
  const kc = q.caseId ? D.caseById(q.caseId) : null;

  const del = async (e) => { e.stopPropagation(); if (!window.confirm(t('faq.confirmDelete'))) return; try { await removeQuestion(q.id); } catch (err) { showToast(err.message || 'エラーが発生しました', 'x'); } };
  const reopen = async () => { try { await reopenQuestion(q.id); } catch (err) { showToast(err.message || 'エラーが発生しました', 'x'); } };

  return (
    <div style={{ borderBottom: '1px solid #f0f1f4' }}>
      <div onClick={() => setOpen(o => !o)} className="row-hover" style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '15px 18px', cursor: 'pointer' }}>
        <div style={{ flex: '0 0 auto', marginTop: 1 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10.5, fontWeight: 700, padding: '2px 9px', borderRadius: 6,
            color: resolved ? '#15803d' : '#b45309', background: resolved ? '#e3f5e9' : '#fdf0db' }}>
            <Icon name={resolved ? 'check' : 'clock'} size={11} stroke={2.4} />{resolved ? t('faq.status.resolved') : t('faq.status.open')}
          </span>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#1f2430', lineHeight: 1.5 }}>{q.title}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginTop: 5, flexWrap: 'wrap', fontSize: 11.5, color: '#9aa1ab' }}>
            <span>{t('faq.askedBy', { name: asker ? asker.name : '—' })}</span>
            <span>·</span>
            <span>{fmtDateTime(q.createdAt)}</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: answers.length ? '#4a5af0' : '#aab0ba', fontWeight: 600 }}>
              <Icon name="mail" size={12} stroke={2} />{t('faq.answers.count', { n: answers.length })}
            </span>
            {q.aiAnswer && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, color: '#6d68e0', fontWeight: 600 }}><Icon name="spark" size={12} stroke={2} />AI</span>}
          </div>
        </div>
        {canDelete && <IconButton name="x" size={15} onClick={del} title={t('faq.delete')} />}
        <Icon name={open ? 'chevronDown' : 'chevronRight'} size={17} stroke={2.2} style={{ color: '#c2c7cf', flex: '0 0 auto', marginTop: 2 }} />
      </div>

      {open && (
        <div style={{ padding: '4px 18px 18px', background: '#fcfcfe' }}>
          {q.body && <div style={{ fontSize: 13, lineHeight: 1.7, color: '#4b5159', whiteSpace: 'pre-wrap', marginBottom: 12 }}>{q.body}</div>}
          {kc && (
            <button onClick={() => navigate('case', kc.id)} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, marginBottom: 12, border: '1px solid #d7d5f5', background: '#f3f2fd', color: '#5b54b8', borderRadius: 6, padding: '2px 9px', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
              <Icon name="cases" size={12} stroke={2} />{kc.title}
            </button>
          )}

          {q.aiAnswer && (
            <div style={{ padding: '13px 15px', background: '#faf9ff', border: '1px solid #ecebfb', borderRadius: 11, marginBottom: 14 }}>
              <div style={{ fontSize: 11.5, fontWeight: 700, color: '#6d68e0', marginBottom: 6, display: 'flex', alignItems: 'center', gap: 6 }}>
                <Icon name="spark" size={13} stroke={2.2} />{t('faq.aiAnswer')}
              </div>
              <div style={{ fontSize: 13, lineHeight: 1.75, color: '#2b2f38', whiteSpace: 'pre-wrap' }}>{q.aiAnswer}</div>
              <SourceChips sources={q.aiSources} />
            </div>
          )}

          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: '#7b828d' }}>{t('faq.answers.count', { n: answers.length })}</div>
            {resolved && canAccept && <Button variant="default" size="sm" icon="refresh" onClick={reopen}>{t('faq.reopen')}</Button>}
          </div>

          {answers.length === 0
            ? <div style={{ fontSize: 12.5, color: '#9aa1ab', padding: '10px 0 2px' }}>{t('faq.answers.none')}</div>
            : answers.slice().sort((a, b) => (b.accepted ? 1 : 0) - (a.accepted ? 1 : 0)).map(a => (
                <AnswerRow key={a.id} qId={q.id} ans={a} canAccept={canAccept} resolved={resolved} />
              ))}

          <AnswerComposer qId={q.id} />
        </div>
      )}
    </div>
  );
}

function FaqScreen() {
  const { questions } = useStore();
  const [filter, setFilter] = React.useState('all'); // all | open | resolved
  const [query, setQuery] = React.useState('');

  const counts = React.useMemo(() => ({
    all: questions.length,
    open: questions.filter(q => q.status !== 'resolved').length,
    resolved: questions.filter(q => q.status === 'resolved').length,
  }), [questions]);

  const list = React.useMemo(() => {
    const term = query.trim().toLowerCase();
    return questions.filter(q => {
      if (filter === 'open' && q.status === 'resolved') return false;
      if (filter === 'resolved' && q.status !== 'resolved') return false;
      if (!term) return true;
      const hay = (q.title + ' ' + (q.body || '') + ' ' + (q.aiAnswer || '') + ' ' + (q.answers || []).map(a => a.body).join(' ')).toLowerCase();
      return hay.includes(term);
    });
  }, [questions, filter, query]);

  const FILTERS = [{ k: 'all', label: t('faq.filter.all') }, { k: 'open', label: t('faq.filter.open') }, { k: 'resolved', label: t('faq.filter.resolved') }];

  return (
    <Page title={t('nav.faq')}>
      <div style={{ fontSize: 12.5, color: '#7b828d', marginBottom: 16, lineHeight: 1.6 }}>{t('faq.subtitle')}</div>

      <AiAskBox />

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, marginBottom: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#1c2027' }}>{t('faq.board.title')}</div>
          <div style={{ display: 'flex', gap: 4, padding: 4, background: '#eceef1', borderRadius: 11 }}>
            {FILTERS.map(f => {
              const on = filter === f.k;
              return (
                <button key={f.k} onClick={() => setFilter(f.k)}
                  style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 13px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 600, border: 'none',
                    background: on ? '#fff' : 'transparent', color: on ? '#1c1f26' : '#7b828d', boxShadow: on ? '0 1px 2px rgba(20,22,40,.10)' : 'none' }}>
                  {f.label}<span style={{ fontSize: 11, fontWeight: 700, color: on ? '#9aa1ab' : '#aab0b9' }}>{counts[f.k]}</span>
                </button>
              );
            })}
          </div>
        </div>
        <div style={{ position: 'relative', minWidth: 200 }}>
          <Icon name="search" size={15} stroke={2} style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', color: '#aab0ba' }} />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t('faq.search.placeholder')}
            style={{ width: '100%', border: '1px solid #e2e5ea', borderRadius: 9, padding: '8px 12px 8px 33px', fontSize: 13, color: '#2b2f38', outline: 'none', fontFamily: 'inherit' }} />
        </div>
      </div>

      <Card pad={0}>
        {list.length === 0
          ? <div style={{ padding: '46px 0', textAlign: 'center', color: '#9aa1ab', fontSize: 13 }}>{questions.length === 0 ? t('faq.board.empty') : t('faq.board.searchEmpty')}</div>
          : list.map(q => <QuestionCard key={q.id} q={q} />)}
      </Card>
    </Page>
  );
}

Object.assign(window, { FaqScreen });
