// Chat-style question flow (mobile-first)
const { useState: useChatState, useEffect: useChatEffect, useRef: useChatRef } = React;

function ChatFlow({ questions, answers, setAnswers, onComplete, useIllustration }) {
  const [step, setStep] = useChatState(0);
  const [typing, setTyping] = useChatState(true);
  const [showOptions, setShowOptions] = useChatState(false);
  const [progressOpen, setProgressOpen] = useChatState(false);
  const scrollerRef = useChatRef(null);

  const q = questions[step];
  const done = step >= questions.length;

  useChatEffect(() => {
    if (done) return;
    setTyping(true);
    setShowOptions(false);
    const t1 = setTimeout(() => setTyping(false), 700);
    const t2 = setTimeout(() => setShowOptions(true), 1150);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [step, done]);

  useChatEffect(() => {
    if (scrollerRef.current) {
      scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
    }
  }, [step, typing, showOptions, answers]);

  const handlePick = (val) => {
    setAnswers({ ...answers, [q.id]: val });
    setTimeout(() => {
      if (step + 1 >= questions.length) {
        onComplete({ ...answers, [q.id]: val });
      } else {
        setStep(step + 1);
      }
    }, 320);
  };

  const handleMulti = (val) => {
    const cur = Array.isArray(answers[q.id]) ? answers[q.id] : [];
    const next = cur.includes(val) ? cur.filter(v => v !== val) : [...cur, val];
    setAnswers({ ...answers, [q.id]: next });
  };

  const submitMulti = () => {
    const cur = Array.isArray(answers[q.id]) ? answers[q.id] : [];
    if (cur.length === 0) return;
    setTimeout(() => {
      if (step + 1 >= questions.length) onComplete(answers);
      else setStep(step + 1);
    }, 200);
  };

  const goBack = () => {
    if (step === 0) return;
    setStep(step - 1);
  };

  const past = questions.slice(0, step);
  const progress = step / questions.length;

  return (
    <div className="chat-shell">
      {/* Compact progress bar */}
      <div style={{
        position: 'sticky', top: 65, zIndex: 20,
        background: 'var(--cream)',
        borderBottom: '1px solid var(--line-soft)',
        padding: '10px 16px',
        display: 'flex', alignItems: 'center', gap: 12,
      }}
      className="chat-progress">
        <button onClick={goBack}
          disabled={step === 0}
          aria-label="戻る"
          style={{
            appearance: 'none', background: 'transparent', border: 'none', cursor: 'pointer',
            padding: 4, color: 'var(--ink)', opacity: step === 0 ? 0.25 : 1,
            fontSize: 18, lineHeight: 1,
          }}>←</button>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', opacity: 0.7 }}>
              Q{String(Math.min(step + 1, questions.length)).padStart(2, '0')} / {String(questions.length).padStart(2, '0')}
            </span>
            <span className="mono" style={{ fontSize: 10, opacity: 0.5 }}>{Math.round(progress * 100)}%</span>
          </div>
          <div style={{ height: 3, background: 'var(--line-soft)', borderRadius: 2, overflow: 'hidden' }}>
            <div style={{
              width: `${progress * 100}%`,
              height: '100%', background: 'var(--ink)',
              transition: 'width .3s cubic-bezier(.2,.7,.2,1)',
            }} />
          </div>
        </div>
        <button onClick={() => setProgressOpen(true)}
          aria-label="回答履歴"
          className="chat-history-btn"
          style={{
            appearance: 'none', background: 'transparent', border: '1px solid var(--line)',
            padding: '6px 10px', cursor: 'pointer',
            borderRadius: 999, fontSize: 11,
            fontFamily: 'inherit', color: 'var(--ink)',
          }}>履歴</button>
      </div>

      <div className="chat-layout">
        {/* Chat scroller */}
        <div ref={scrollerRef} className="chat-scroller" style={{
          padding: '20px 16px 160px',
          overflowY: 'auto',
          minHeight: 'calc(100vh - 65px - 56px)',
        }}>
          <div style={{ maxWidth: 680, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {past.map((pq, idx) => (
              <PastBubblePair key={pq.id} q={pq} a={answers[pq.id]} idx={idx} />
            ))}

            {!done && (
              <>
                <BubbleRow side="taro">
                  {typing ? (
                    <div className="bubble from-taro bubble-in dots">
                      <span></span><span></span><span></span>
                    </div>
                  ) : (
                    <div className="bubble from-taro bubble-in">
                      <span className="display-md" style={{ fontSize: 16, lineHeight: 1.55, fontWeight: 700 }}>
                        {q.text}
                      </span>
                    </div>
                  )}
                </BubbleRow>
              </>
            )}
          </div>
        </div>

        {/* Desktop sidebar */}
        <aside className="chat-side">
          <SidePanel step={step} total={questions.length} answers={answers} questions={questions} />
        </aside>
      </div>

      {/* Bottom action sheet — fixed options */}
      {!done && showOptions && (
        <div className="action-sheet">
          <div style={{ maxWidth: 680, margin: '0 auto' }}>
            <div className="mono" style={{
              fontSize: 10, opacity: 0.55, letterSpacing: '0.12em',
              marginBottom: 8, display: 'flex', justifyContent: 'space-between',
            }}>
              <span>{q.type === 'multi' ? '複数選択OK' : '1つ選んでください'}</span>
              {q.type === 'multi' && Array.isArray(answers[q.id]) && answers[q.id].length > 0 && (
                <span>{answers[q.id].length}件選択中</span>
              )}
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {q.options.map(opt => {
                const isActive = q.type === 'multi'
                  ? Array.isArray(answers[q.id]) && answers[q.id].includes(opt.value)
                  : false;
                return (
                  <button
                    key={opt.value}
                    className={`chip${isActive ? ' active' : ''}`}
                    onClick={() => q.type === 'multi' ? handleMulti(opt.value) : handlePick(opt.value)}
                  >
                    {opt.emoji && <span style={{ fontSize: 15 }}>{opt.emoji}</span>}
                    {opt.label}
                  </button>
                );
              })}
            </div>
            {q.type === 'multi' && (
              <button
                className="btn"
                onClick={submitMulti}
                disabled={!Array.isArray(answers[q.id]) || answers[q.id].length === 0}
                style={{ width: '100%', marginTop: 12 }}
              >
                決定 →
              </button>
            )}
          </div>
        </div>
      )}

      {/* Mobile history drawer */}
      {progressOpen && (
        <div onClick={() => setProgressOpen(false)} className="fade-in" style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 40,
        }}>
          <div onClick={e => e.stopPropagation()}
            style={{
              position: 'absolute', bottom: 0, left: 0, right: 0,
              background: 'var(--cream)',
              borderTop: '1px solid var(--line)',
              borderRadius: '20px 20px 0 0',
              padding: '20px 20px 32px',
              maxHeight: '80vh', overflowY: 'auto',
            }}>
            <div style={{ width: 40, height: 4, background: 'var(--line)', borderRadius: 2, margin: '0 auto 16px' }} />
            <SidePanel step={step} total={questions.length} answers={answers} questions={questions} compact />
          </div>
        </div>
      )}

      <style>{`
        .chat-layout {
          display: flex; flex-direction: column;
        }
        .chat-side { display: none; }
        .action-sheet {
          position: fixed; left: 0; right: 0; bottom: 0; z-index: 15;
          background: var(--cream-3);
          border-top: 1px solid var(--line);
          padding: 14px 16px;
          padding-bottom: calc(14px + env(safe-area-inset-bottom, 0));
          box-shadow: 0 -8px 24px rgba(42,31,21,0.06);
        }
        @media (min-width: 1024px) {
          .chat-layout { display: grid; grid-template-columns: 1fr 340px; }
          .chat-scroller { padding: 28px 40px 200px !important; max-height: calc(100vh - 65px - 56px); }
          .chat-side {
            display: block;
            background: var(--cream-3);
            border-left: 1px solid var(--line);
            padding: 28px 24px;
            position: sticky; top: calc(65px + 56px); height: calc(100vh - 65px - 56px);
            overflow-y: auto;
          }
          .chat-history-btn { display: none !important; }
          .action-sheet { left: 0; right: 340px; padding: 18px 40px; padding-bottom: 18px; }
        }
      `}</style>
    </div>
  );
}

function BubbleRow({ side, children }) {
  if (side === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, alignItems: 'flex-start' }}>
        <div style={{ maxWidth: '82%' }}>{children}</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <TaroAvatar size={36} />
      <div style={{ maxWidth: '82%' }}>{children}</div>
    </div>
  );
}

function PastBubblePair({ q, a, idx }) {
  const labels = Array.isArray(a)
    ? a.map(v => q.options.find(o => o.value === v)?.label).filter(Boolean).join(' / ')
    : q.options.find(o => o.value === a)?.label || a;
  return (
    <>
      <BubbleRow side="taro">
        <div className="bubble from-taro">
          <span style={{ fontSize: 14, lineHeight: 1.6, fontWeight: 500 }}>{q.text}</span>
        </div>
      </BubbleRow>
      <BubbleRow side="user">
        <div className="bubble from-user" style={{ fontWeight: 500 }}>{labels}</div>
      </BubbleRow>
    </>
  );
}

function SidePanel({ step, total, answers, questions, compact }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', opacity: 0.6, marginBottom: 8 }}>
        PROGRESS
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 14 }}>
        <span className="display" style={{ fontSize: 48 }}>
          {String(step).padStart(2, '0')}
        </span>
        <span style={{ fontSize: 18, opacity: 0.5, fontWeight: 500 }}>/ {String(total).padStart(2, '0')}</span>
      </div>

      <div style={{ display: 'flex', gap: 3, marginBottom: 24 }}>
        {questions.map((_, i) => (
          <div key={i} style={{
            flex: 1, height: 4,
            background: i < step ? 'var(--ink)' : 'var(--line)',
            borderRadius: 2,
          }} />
        ))}
      </div>

      <div className="rule-soft" style={{ marginBottom: 18 }} />

      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', opacity: 0.6, marginBottom: 12 }}>
        これまでの回答
      </div>

      {Object.keys(answers).length === 0 && (
        <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>
          まだ回答はありません。
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {questions.slice(0, step).map((q, i) => {
          const a = answers[q.id];
          if (a === undefined) return null;
          const labels = Array.isArray(a)
            ? a.map(v => q.options.find(o => o.value === v)?.label).filter(Boolean).join('、')
            : q.options.find(o => o.value === a)?.label || a;
          return (
            <div key={q.id} style={{ display: 'flex', gap: 10 }}>
              <span className="mono" style={{ fontSize: 10, color: 'var(--ink-soft)', minWidth: 22, paddingTop: 3 }}>
                {String(i + 1).padStart(2, '0')}
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginBottom: 2 }}>
                  {q.text.split('\n')[0].replace(/[?？]$/, '')}
                </div>
                <div className="display-md" style={{ fontSize: 14, fontWeight: 700 }}>
                  {labels}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {!compact && (
        <div style={{ marginTop: 32 }}>
          <div className="rule-soft" style={{ marginBottom: 14 }} />
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', opacity: 0.5, marginBottom: 8 }}>
            MEMO — 太郎より
          </div>
          <p className="hand" style={{ fontSize: 16, lineHeight: 1.8, color: 'var(--ink-soft)', margin: 0 }}>
            「贈り物は、相手のことを考える時間そのもの。<br/>
            焦らずひとつずつ。」
          </p>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ChatFlow });
