// AIチャットボット — SUEボット
// 画面右下のフローティングボタン → チャットパネル
// /api/chat（Cloudflare Pages Function → Claude API）に問い合わせる

const CB = {
  cream:   '#faf6f0',
  paper:   '#fffdf9',
  ink:     '#2d2218',
  inkMid:  '#5a3e2b',
  inkSoft: '#7a5d45',
  terra:   '#b85c38',
  terraL:  '#e8c4ae',
  sage:    '#4a6741',
  rule:    '#e8ddd0',
  serif:   '"Shippori Mincho", "Times New Roman", serif',
  hand:    '"Caveat", cursive',
  sans:    '"Noto Sans JP", sans-serif',
};

const CB_GREETING =
  'こんにちは！スマートウェブ制作 SUE のAIアシスタントです。\n料金プランや制作の流れなど、お気軽にご質問ください。';

const CB_QUICK = [
  '料金プランを教えて',
  '制作の流れは？',
  '保守には何が含まれる？',
  '納期はどれくらい？',
];

function ChatStyles() {
  return (
    <style>{`
      @keyframes cb-pop {
        from { opacity:0; transform:translateY(16px) scale(.97); }
        to   { opacity:1; transform:translateY(0) scale(1); }
      }
      @keyframes cb-msg {
        from { opacity:0; transform:translateY(8px); }
        to   { opacity:1; transform:translateY(0); }
      }
      @keyframes cb-dot {
        0%, 60%, 100% { transform:translateY(0); opacity:.4; }
        30% { transform:translateY(-4px); opacity:1; }
      }
      @keyframes cb-ring {
        0%   { transform:scale(1); opacity:.45; }
        100% { transform:scale(1.75); opacity:0; }
      }
      .cb-panel { animation: cb-pop .28s cubic-bezier(.16,1,.3,1); }
      .cb-msg   { animation: cb-msg .25s ease; }
      .cb-teaser { animation: cb-pop .35s cubic-bezier(.16,1,.3,1); }
      .cb-quick:hover { background:${CB.terra}; color:${CB.paper}; border-color:${CB.terra}; }
      .cb-send:not(:disabled):hover { background:#a04e2d; }
      .cb-fab:hover { transform:translateY(-3px); box-shadow:0 12px 32px rgba(45,34,24,.28); }
      .cb-fab-label:hover { transform:translateY(-2px); box-shadow:0 10px 26px rgba(45,34,24,.26); }
      .cb-input:focus { border-color:${CB.terra}; }
      @media (max-width: 480px) {
        .cb-panel {
          right: 12px !important; left: 12px !important;
          width: auto !important; height: min(70vh, 560px) !important;
          bottom: 84px !important;
        }
        .cb-fab-label { font-size: 12.5px !important; padding: 9px 14px !important; }
        .cb-teaser { right: 12px !important; left: 12px !important; width: auto !important; }
      }
      @media (prefers-reduced-motion: reduce) {
        .cb-panel, .cb-msg, .cb-teaser { animation: none; }
        .cb-ring-anim { animation: none !important; display: none; }
      }
    `}</style>
  );
}

function ChatMessage({ role, content }) {
  const isUser = role === 'user';
  return (
    <div className="cb-msg" style={{ display: 'flex', justifyContent: isUser ? 'flex-end' : 'flex-start' }}>
      <div style={{
        maxWidth: '82%',
        padding: '10px 14px',
        borderRadius: isUser ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
        background: isUser ? CB.terra : CB.paper,
        color: isUser ? CB.paper : CB.ink,
        border: isUser ? 'none' : `1px solid ${CB.rule}`,
        fontFamily: CB.sans, fontSize: 14, lineHeight: 1.8,
        whiteSpace: 'pre-wrap', wordBreak: 'break-word',
      }}>
        {content}
      </div>
    </div>
  );
}

function TypingDots() {
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
      <div style={{
        padding: '12px 16px', borderRadius: '14px 14px 14px 4px',
        background: CB.paper, border: `1px solid ${CB.rule}`,
        display: 'flex', gap: 5, alignItems: 'center',
      }}>
        {[0, 1, 2].map((i) => (
          <span key={i} style={{
            width: 7, height: 7, borderRadius: '50%', background: CB.inkSoft,
            display: 'inline-block',
            animation: `cb-dot 1.2s ease-in-out ${i * 0.18}s infinite`,
          }} />
        ))}
      </div>
    </div>
  );
}

function SueChatBot() {
  const [open, setOpen] = React.useState(false);
  const [teaser, setTeaser] = React.useState(false);
  const [messages, setMessages] = React.useState([{ role: 'assistant', content: CB_GREETING }]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const listRef = React.useRef(null);
  const inputRef = React.useRef(null);

  const teaserSeen = () => {
    try { return sessionStorage.getItem('sue-chat-teaser') === '1'; } catch { return false; }
  };
  const markTeaserSeen = () => {
    try { sessionStorage.setItem('sue-chat-teaser', '1'); } catch { /* no-op */ }
  };

  const openChat = React.useCallback(() => {
    setOpen(true);
    setTeaser(false);
    markTeaserSeen();
  }, []);

  // 外部（ヒーローのボタンなど）から window.openSueChat() で開けるようにする
  React.useEffect(() => {
    window.openSueChat = openChat;
    const onEvent = () => openChat();
    window.addEventListener('sue:open-chat', onEvent);
    return () => {
      delete window.openSueChat;
      window.removeEventListener('sue:open-chat', onEvent);
    };
  }, [openChat]);

  // 数秒後にティーザー吹き出しを表示（セッション中1回だけ）
  React.useEffect(() => {
    if (teaserSeen()) return;
    const t = setTimeout(() => {
      setTeaser((v) => v || !teaserSeen());
    }, 6000);
    return () => clearTimeout(t);
  }, []);

  React.useEffect(() => {
    if (open) setTeaser(false);
  }, [open]);

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

  React.useEffect(() => {
    if (open && inputRef.current && window.matchMedia('(min-width: 481px)').matches) {
      inputRef.current.focus();
    }
  }, [open]);

  const send = async (text) => {
    const content = (text || '').trim();
    if (!content || loading) return;
    const next = [...messages, { role: 'user', content }];
    setMessages(next);
    setInput('');
    setLoading(true);
    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        // 挨拶（固定文）は除いて履歴を送る
        body: JSON.stringify({ messages: next.slice(1).slice(-12) }),
      });
      const data = await res.json().catch(() => ({}));
      const reply = res.ok && data.reply
        ? data.reply
        : (data.error || 'うまく応答できませんでした。時間をおいてお試しいただくか、下部のお問い合わせフォームをご利用ください。');
      setMessages((m) => [...m, { role: 'assistant', content: reply }]);
    } catch {
      setMessages((m) => [...m, {
        role: 'assistant',
        content: '通信エラーが発生しました。時間をおいてお試しいただくか、下部のお問い合わせフォームをご利用ください。',
      }]);
    } finally {
      setLoading(false);
    }
  };

  const showQuick = messages.length === 1 && !loading;

  return (
    <>
      <ChatStyles />

      {/* チャットパネル */}
      {open && (
        <div className="cb-panel" role="dialog" aria-label="AIチャット相談" style={{
          position: 'fixed', bottom: 96, right: 24, zIndex: 1000,
          width: 360, height: 520,
          display: 'flex', flexDirection: 'column',
          background: CB.cream, borderRadius: 18,
          border: `1px solid ${CB.rule}`,
          boxShadow: '0 20px 60px rgba(45,34,24,.22)',
          overflow: 'hidden',
        }}>
          {/* ヘッダー */}
          <div style={{
            padding: '14px 18px', background: CB.ink,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <span style={{
              width: 34, height: 34, borderRadius: '50%', background: CB.terra,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              color: CB.paper, fontFamily: CB.serif, fontWeight: 600, fontSize: 15, flexShrink: 0,
            }}>S</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: CB.serif, fontSize: 15, fontWeight: 600, color: CB.paper, lineHeight: 1.3 }}>
                AIチャット相談
              </div>
              <div style={{ fontFamily: CB.sans, fontSize: 11, color: CB.terraL }}>
                24時間いつでも・匿名OK
              </div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="チャットを閉じる" style={{
              background: 'none', border: 'none', color: CB.paper, cursor: 'pointer',
              fontSize: 22, lineHeight: 1, padding: 4, opacity: .8,
            }}>×</button>
          </div>

          {/* メッセージ一覧 */}
          <div ref={listRef} style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {messages.map((m, i) => <ChatMessage key={i} role={m.role} content={m.content} />)}
            {loading && <TypingDots />}
            {showQuick && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 4 }}>
                {CB_QUICK.map((q) => (
                  <button key={q} className="cb-quick" onClick={() => send(q)} style={{
                    padding: '7px 13px', borderRadius: 999,
                    border: `1px solid ${CB.terraL}`, background: CB.paper,
                    color: CB.inkMid, fontFamily: CB.sans, fontSize: 13,
                    cursor: 'pointer', transition: 'all .2s ease',
                  }}>{q}</button>
                ))}
              </div>
            )}
          </div>

          {/* 入力欄 */}
          <form
            onSubmit={(e) => { e.preventDefault(); send(input); }}
            style={{
              display: 'flex', gap: 8, padding: 12,
              borderTop: `1px solid ${CB.rule}`, background: CB.paper,
            }}
          >
            <input
              ref={inputRef}
              className="cb-input"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="質問を入力…"
              maxLength={500}
              aria-label="質問を入力"
              style={{
                flex: 1, padding: '10px 14px', borderRadius: 999,
                border: `1.5px solid ${CB.rule}`, outline: 'none',
                fontFamily: CB.sans, fontSize: 14, color: CB.ink,
                background: CB.cream,
              }}
            />
            <button type="submit" className="cb-send" disabled={loading || !input.trim()} aria-label="送信" style={{
              width: 42, height: 42, borderRadius: '50%', border: 'none',
              background: CB.terra, color: CB.paper, cursor: loading || !input.trim() ? 'default' : 'pointer',
              opacity: loading || !input.trim() ? .5 : 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'background .2s ease', flexShrink: 0,
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M22 2L11 13" /><path d="M22 2l-7 20-4-9-9-4 20-7z" />
              </svg>
            </button>
          </form>

          {/* 注意書き */}
          <div style={{
            padding: '6px 14px 10px', background: CB.paper,
            fontFamily: CB.sans, fontSize: 10.5, color: CB.inkSoft, textAlign: 'center',
          }}>
            AIによる自動応答です。正確な内容はお問い合わせフォームでご確認ください。
          </div>
        </div>
      )}

      {/* ティーザー吹き出し（数秒後に1回だけ表示） */}
      {teaser && !open && (
        <div className="cb-teaser" style={{
          position: 'fixed', bottom: 96, right: 24, zIndex: 999,
          width: 280, padding: '14px 16px',
          background: CB.paper, borderRadius: '16px 16px 4px 16px',
          border: `1px solid ${CB.rule}`,
          boxShadow: '0 14px 40px rgba(45,34,24,.2)',
        }}>
          <button
            onClick={() => { setTeaser(false); markTeaserSeen(); }}
            aria-label="閉じる"
            style={{
              position: 'absolute', top: 6, right: 8,
              background: 'none', border: 'none', cursor: 'pointer',
              color: CB.inkSoft, fontSize: 16, lineHeight: 1, padding: 4,
            }}
          >×</button>
          <div
            onClick={openChat}
            role="button"
            tabIndex={0}
            onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') openChat(); }}
            style={{ cursor: 'pointer' }}
          >
            <div style={{ fontFamily: CB.serif, fontSize: 14.5, fontWeight: 600, color: CB.ink, marginBottom: 4, paddingRight: 16 }}>
              何かお困りですか？
            </div>
            <div style={{ fontFamily: CB.sans, fontSize: 13, color: CB.inkMid, lineHeight: 1.7 }}>
              料金や納期など、AIがその場でお答えします。お気軽にどうぞ！
            </div>
          </div>
        </div>
      )}

      {/* フローティングボタン（ラベル付き） */}
      <div style={{
        position: 'fixed', bottom: 24, right: 24, zIndex: 1000,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        {!open && (
          <button
            className="cb-fab-label"
            onClick={openChat}
            style={{
              border: 'none', cursor: 'pointer',
              background: CB.terra, color: CB.paper,
              fontFamily: CB.serif, fontWeight: 600, fontSize: 14,
              letterSpacing: '.04em', lineHeight: 1,
              padding: '12px 18px', borderRadius: 999,
              boxShadow: '0 8px 24px rgba(184,92,56,.32)',
              transition: 'transform .2s ease, box-shadow .2s ease',
              whiteSpace: 'nowrap',
            }}
          >
            AIに無料相談
          </button>
        )}
        <span style={{ position: 'relative', display: 'inline-flex', flexShrink: 0 }}>
          {!open && (
            <span className="cb-ring-anim" aria-hidden="true" style={{
              position: 'absolute', inset: 0, borderRadius: '50%',
              background: CB.terra, opacity: .45,
              animation: 'cb-ring 2.4s ease-out infinite',
            }} />
          )}
          <button
            className="cb-fab"
            onClick={() => (open ? setOpen(false) : openChat())}
            aria-label={open ? 'チャットを閉じる' : 'AIチャットで相談する'}
            aria-expanded={open}
            style={{
              position: 'relative',
              width: 60, height: 60, borderRadius: '50%',
              border: 'none', cursor: 'pointer',
              background: CB.ink, color: CB.paper,
              boxShadow: '0 8px 24px rgba(45,34,24,.24)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'transform .2s ease, box-shadow .2s ease',
            }}
          >
            {open ? (
              <span style={{ fontSize: 26, lineHeight: 1 }} aria-hidden="true">×</span>
            ) : (
              <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                <path d="M8 9h8M8 13h5" />
              </svg>
            )}
          </button>
        </span>
      </div>
    </>
  );
}

if (typeof window !== 'undefined') window.SueChatBot = SueChatBot;
