// js/components/DiagnosisQuestions.jsx
// 24개 진단 질문 페이지

window.DiagnosisQuestions = function({ productInfo, onComplete, onBack }) {
  const { useState, useCallback, useEffect } = React;
  
  const questions = window.PCODE_QUESTIONS;
  const helpers = window.PCODE_HELPERS;
  const totalQuestions = questions.length;

  const [currentIndex, setCurrentIndex] = useState(0);
  const [answers, setAnswers] = useState({});
  const [selectedAnswer, setSelectedAnswer] = useState(null);
  const [isAnimating, setIsAnimating] = useState(false);

  const currentQuestion = questions[currentIndex];
  const progress = Math.round(((currentIndex + 1) / totalQuestions) * 100);
  const answeredCount = Object.keys(answers).length;

  // 현재 질문의 저장된 답변 로드
  useEffect(() => {
    if (currentQuestion) {
      setSelectedAnswer(answers[currentQuestion.id] || null);
    }
  }, [currentIndex, currentQuestion, answers]);

  // 답변 선택
  const handleSelectAnswer = useCallback((score) => {
    setSelectedAnswer(score);
  }, []);

  // 다음 질문
  const handleNext = useCallback(() => {
    if (selectedAnswer === null) return;
    
    const newAnswers = { ...answers, [currentQuestion.id]: selectedAnswer };
    setAnswers(newAnswers);

    if (currentIndex < totalQuestions - 1) {
      setIsAnimating(true);
      setTimeout(() => {
        setCurrentIndex(prev => prev + 1);
        setIsAnimating(false);
      }, 200);
    } else {
      // 마지막 질문 완료
      onComplete(newAnswers);
    }
  }, [selectedAnswer, answers, currentQuestion, currentIndex, totalQuestions, onComplete]);

  // 이전 질문
  const handlePrev = useCallback(() => {
    if (currentIndex > 0) {
      setIsAnimating(true);
      setTimeout(() => {
        setCurrentIndex(prev => prev - 1);
        setIsAnimating(false);
      }, 200);
    } else {
      onBack();
    }
  }, [currentIndex, onBack]);

  // 키보드 단축키
  useEffect(() => {
    const handleKeyPress = (e) => {
      if (e.key >= '1' && e.key <= '5') {
        handleSelectAnswer(parseInt(e.key));
      } else if (e.key === 'Enter' && selectedAnswer !== null) {
        handleNext();
      } else if (e.key === 'ArrowLeft') {
        handlePrev();
      }
    };
    window.addEventListener('keydown', handleKeyPress);
    return () => window.removeEventListener('keydown', handleKeyPress);
  }, [handleSelectAnswer, handleNext, handlePrev, selectedAnswer]);

  // 축별 색상
  const axisColors = {
    US: { bg: 'from-blue-500 to-pink-500', badge: 'bg-blue-100 text-blue-700', text: 'text-blue-600' },
    TC: { bg: 'from-green-500 to-yellow-500', badge: 'bg-green-100 text-green-700', text: 'text-green-600' },
    FE: { bg: 'from-red-500 to-purple-500', badge: 'bg-red-100 text-red-700', text: 'text-red-600' },
    PG: { bg: 'from-gray-500 to-yellow-500', badge: 'bg-gray-100 text-gray-700', text: 'text-gray-600' },
  };

  const axisColor = axisColors[currentQuestion.axis] || axisColors.US;

  // 답변 옵션
  const answerOptions = [
    { score: 1, label: '전혀 아니다', emoji: '😞', short: '매우\n아님', color: 'hover:border-red-400 hover:bg-red-50', selectedColor: 'border-red-400 bg-red-50 ring-red-200' },
    { score: 2, label: '아니다', emoji: '🙁', short: '아님', color: 'hover:border-orange-400 hover:bg-orange-50', selectedColor: 'border-orange-400 bg-orange-50 ring-orange-200' },
    { score: 3, label: '중립', emoji: '😐', short: '중립', color: 'hover:border-gray-400 hover:bg-gray-50', selectedColor: 'border-gray-400 bg-gray-50 ring-gray-200' },
    { score: 4, label: '그렇다', emoji: '🙂', short: '그렇다', color: 'hover:border-blue-400 hover:bg-blue-50', selectedColor: 'border-blue-400 bg-blue-50 ring-blue-200' },
    { score: 5, label: '매우 그렇다', emoji: '😄', short: '매우\n그렇다', color: 'hover:border-indigo-400 hover:bg-indigo-50', selectedColor: 'border-indigo-400 bg-indigo-50 ring-indigo-200' },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-indigo-50 to-purple-50">
      {/* 상단 헤더 */}
      <div className="sticky top-0 z-10 bg-white/95 backdrop-blur-sm border-b border-gray-100 shadow-sm">
        <div className="max-w-2xl mx-auto px-4 py-3">
          {/* 제품 정보 */}
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <button
                onClick={handlePrev}
                className="p-2 rounded-lg hover:bg-gray-100 transition-colors text-gray-500 hover:text-gray-700"
                title={currentIndex === 0 ? '입력 화면으로' : '이전 문항'}
              >
                <i className="fas fa-chevron-left text-sm"></i>
              </button>
              <div>
                <p className="text-xs text-gray-500">{productInfo.productName}</p>
                <p className="text-xs text-indigo-400">{productInfo.category}</p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-xs font-bold text-gray-600">
                {currentIndex + 1} <span className="text-gray-400">/ {totalQuestions}</span>
              </p>
              <p className="text-xs text-green-500">{answeredCount}개 완료</p>
            </div>
          </div>

          {/* 진행 바 */}
          <div className="w-full bg-gray-100 rounded-full h-2.5 overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-500 bg-gradient-to-r ${axisColor.bg}`}
              style={{ width: `${progress}%` }}
            ></div>
          </div>
          <div className="flex justify-between text-xs text-gray-400 mt-1">
            <span>시작</span>
            <span className="font-medium text-indigo-600">{progress}% 완료</span>
            <span>완료</span>
          </div>
        </div>
      </div>

      {/* 질문 영역 */}
      <div className="max-w-2xl mx-auto px-4 py-6 sm:py-10">
        {/* 축 배지 */}
        <div className="flex items-center gap-2 mb-4">
          <span className={`text-xs font-bold px-3 py-1 rounded-full ${axisColor.badge}`}>
            {currentQuestion.axisLabel}
          </span>
          <span className="text-xs text-gray-400">
            문항 {currentIndex + 1}
          </span>
        </div>

        {/* 질문 카드 */}
        <div
          className={`bg-white rounded-3xl shadow-lg border border-gray-100 p-6 sm:p-8 mb-6 transition-all duration-200 ${
            isAnimating ? 'opacity-0 translate-y-2' : 'opacity-100 translate-y-0'
          }`}
        >
          <div className="mb-2 flex items-start gap-3">
            <div className={`flex-shrink-0 w-8 h-8 rounded-full bg-gradient-to-r ${axisColor.bg} flex items-center justify-center text-white text-sm font-bold`}>
              {currentIndex + 1}
            </div>
            <h2 className="text-lg sm:text-xl font-bold text-gray-800 leading-relaxed">
              {currentQuestion.question}
            </h2>
          </div>
          
          {currentQuestion.hint && (
            <p className="text-sm text-gray-500 mt-3 pl-11 flex items-center gap-1">
              <i className="fas fa-info-circle text-indigo-300"></i>
              {currentQuestion.hint}
            </p>
          )}
        </div>

        {/* 답변 옵션 */}
        <div className="space-y-3 mb-8">
          {/* 모바일: 수직 나열 / 데스크탑: 가로 나열 */}
          <div className="hidden sm:flex gap-3 justify-center">
            {answerOptions.map(option => (
              <button
                key={option.score}
                onClick={() => handleSelectAnswer(option.score)}
                className={`flex-1 flex flex-col items-center gap-2 p-4 rounded-2xl border-2 transition-all cursor-pointer ${
                  selectedAnswer === option.score
                    ? `${option.selectedColor} ring-2 transform scale-105`
                    : `border-gray-200 bg-white ${option.color}`
                }`}
              >
                <span className="text-2xl">{option.emoji}</span>
                <span className={`text-xs font-semibold text-center leading-tight ${
                  selectedAnswer === option.score ? 'text-gray-700' : 'text-gray-500'
                }`}>
                  {option.score}
                </span>
                <span className={`text-xs text-center leading-tight ${
                  selectedAnswer === option.score ? 'text-gray-600' : 'text-gray-400'
                }`} style={{ whiteSpace: 'pre-line' }}>
                  {option.short}
                </span>
              </button>
            ))}
          </div>

          {/* 모바일 버전 */}
          <div className="sm:hidden space-y-2">
            {answerOptions.map(option => (
              <button
                key={option.score}
                onClick={() => handleSelectAnswer(option.score)}
                className={`w-full flex items-center gap-4 p-4 rounded-2xl border-2 transition-all cursor-pointer text-left ${
                  selectedAnswer === option.score
                    ? `${option.selectedColor} ring-2`
                    : `border-gray-200 bg-white ${option.color}`
                }`}
              >
                <span className={`text-2xl w-10 h-10 flex items-center justify-center rounded-xl flex-shrink-0 ${
                  selectedAnswer === option.score ? 'bg-white/70' : 'bg-gray-50'
                }`}>
                  {option.emoji}
                </span>
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className={`text-sm font-bold ${
                      selectedAnswer === option.score ? 'text-gray-800' : 'text-gray-600'
                    }`}>
                      {option.score}점
                    </span>
                    <span className={`text-sm ${
                      selectedAnswer === option.score ? 'text-gray-700' : 'text-gray-500'
                    }`}>
                      {option.label}
                    </span>
                  </div>
                </div>
                {selectedAnswer === option.score && (
                  <i className="fas fa-check-circle text-indigo-500 flex-shrink-0"></i>
                )}
              </button>
            ))}
          </div>
        </div>

        {/* 선택 상태 표시 */}
        {selectedAnswer !== null && (
          <div className="text-center mb-4 animate-fade-in">
            <p className="text-sm text-indigo-600 font-medium">
              <i className="fas fa-check mr-1"></i>
              {answerOptions[selectedAnswer - 1]?.label} 선택됨
            </p>
          </div>
        )}

        {/* 네비게이션 버튼 */}
        <div className="flex gap-3">
          <button
            onClick={handlePrev}
            className="flex-1 py-4 px-4 border-2 border-gray-200 rounded-2xl font-semibold text-gray-600 hover:border-gray-300 hover:bg-gray-50 transition-all flex items-center justify-center gap-2"
          >
            <i className="fas fa-chevron-left text-sm"></i>
            <span>{currentIndex === 0 ? '처음으로' : '이전'}</span>
          </button>
          
          <button
            onClick={handleNext}
            disabled={selectedAnswer === null}
            className={`flex-[2] py-4 px-6 rounded-2xl font-bold text-base transition-all flex items-center justify-center gap-2 ${
              selectedAnswer !== null
                ? 'text-white shadow-md hover:shadow-lg hover:-translate-y-0.5'
                : 'bg-gray-100 text-gray-400 cursor-not-allowed'
            }`}
            style={selectedAnswer !== null ? {
              background: `linear-gradient(135deg, ${
                currentQuestion.axis === 'US' ? '#3B82F6, #EC4899' :
                currentQuestion.axis === 'TC' ? '#10B981, #F59E0B' :
                currentQuestion.axis === 'FE' ? '#EF4444, #A855F7' :
                '#9CA3AF, #FBBF24'
              })`
            } : {}}
          >
            {currentIndex === totalQuestions - 1 ? (
              <>
                <span>결과 보기</span>
                <span>🎯</span>
              </>
            ) : (
              <>
                <span>다음</span>
                <i className="fas fa-chevron-right text-sm"></i>
              </>
            )}
          </button>
        </div>

        {/* 키보드 안내 (데스크탑) */}
        <p className="text-center text-xs text-gray-400 mt-4 hidden sm:block">
          💡 키보드 단축키: 숫자 1-5로 선택, Enter로 다음, ← 이전
        </p>

        {/* 이전에 답한 문항 미니맵 */}
        <div className="mt-8 bg-white/60 rounded-2xl p-4 border border-gray-100">
          <p className="text-xs font-semibold text-gray-500 mb-3">진행 현황</p>
          <div className="flex flex-wrap gap-1.5">
            {questions.map((q, idx) => {
              const isAnswered = answers[q.id] !== undefined;
              const isCurrent = idx === currentIndex;
              return (
                <div
                  key={q.id}
                  title={`${idx + 1}번: ${isAnswered ? answers[q.id] + '점' : '미응답'}`}
                  className={`w-7 h-7 rounded-lg flex items-center justify-center text-xs font-bold transition-all cursor-default ${
                    isCurrent
                      ? 'bg-gradient-to-br from-indigo-500 to-purple-500 text-white ring-2 ring-indigo-300 scale-110'
                      : isAnswered
                        ? 'bg-indigo-100 text-indigo-600'
                        : 'bg-gray-100 text-gray-400'
                  }`}
                >
                  {idx + 1}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
};
