// js/components/LandingPage.jsx
// 랜딩 페이지 + 제품 정보 입력 폼

window.LandingPage = function({ onStart }) {
  const { useState, useCallback } = React;
  const helpers = window.PCODE_HELPERS;

  const [formData, setFormData] = useState({
    productName: '',
    category: '',
    price: '',
    productLink: ''
  });

  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});

  // 유효성 검사
  const validate = useCallback((data) => {
    const newErrors = {};
    
    if (!data.productName.trim()) {
      newErrors.productName = '제품명을 입력해주세요.';
    } else if (data.productName.trim().length > 50) {
      newErrors.productName = '제품명은 50자 이내로 입력해주세요.';
    }
    
    if (!data.category) {
      newErrors.category = '카테고리를 선택해주세요.';
    }
    
    if (!data.price) {
      newErrors.price = '가격을 입력해주세요.';
    } else if (Number(data.price) <= 0) {
      newErrors.price = '유효한 가격을 입력해주세요.';
    }
    
    if (data.productLink && !helpers.isValidUrl(data.productLink)) {
      newErrors.productLink = '유효한 URL 형식으로 입력해주세요. (예: https://...)';
    }

    return newErrors;
  }, [helpers]);

  // 폼이 유효한지 확인
  const isFormValid = useCallback(() => {
    const errs = validate(formData);
    return Object.keys(errs).length === 0;
  }, [formData, validate]);

  // 입력 변경 핸들러
  const handleChange = useCallback((field, value) => {
    const newData = { ...formData, [field]: value };
    setFormData(newData);
    
    if (touched[field]) {
      const newErrors = validate(newData);
      setErrors(prev => ({
        ...prev,
        [field]: newErrors[field] || null
      }));
    }
  }, [formData, touched, validate]);

  // 블러 핸들러
  const handleBlur = useCallback((field) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    const newErrors = validate(formData);
    setErrors(prev => ({
      ...prev,
      [field]: newErrors[field] || null
    }));
  }, [formData, validate]);

  // 폼 제출
  const handleSubmit = useCallback((e) => {
    e.preventDefault();
    
    // 모든 필드 터치 표시
    setTouched({ productName: true, category: true, price: true, productLink: true });
    
    const validationErrors = validate(formData);
    setErrors(validationErrors);
    
    if (Object.keys(validationErrors).length === 0) {
      onStart(formData);
    }
  }, [formData, validate, onStart]);

  // 최근 결과 불러오기
  const recentResults = helpers.storage.getResults().slice(0, 3);

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50">
      {/* Hero Section */}
      <div className="relative overflow-hidden">
        {/* Background decorations */}
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          <div className="absolute -top-40 -right-40 w-80 h-80 bg-purple-200 rounded-full opacity-30 blur-3xl"></div>
          <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-indigo-200 rounded-full opacity-30 blur-3xl"></div>
          <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-96 h-96 bg-pink-100 rounded-full opacity-20 blur-3xl"></div>
        </div>

        <div className="relative max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pt-12 pb-8">
          {/* Header */}
          <div className="text-center mb-12 animate-fade-in">
            <div className="inline-flex items-center gap-2 bg-white/80 backdrop-blur-sm border border-indigo-100 rounded-full px-4 py-2 mb-6 shadow-sm">
              <span className="text-sm font-medium text-indigo-600">제조사/브랜드 대표 전용</span>
              <span className="w-1.5 h-1.5 bg-indigo-400 rounded-full"></span>
              <span className="text-sm text-gray-500">무료 진단</span>
            </div>
            
            <h1 className="text-4xl sm:text-5xl lg:text-6xl font-black text-gray-900 mb-4 tracking-tight">
              What's Your
              <span className="block mt-1" style={{
                background: 'linear-gradient(135deg, #6B7AF7 0%, #EC4899 100%)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
                backgroundClip: 'text'
              }}>
                P-CODE? 🎯
              </span>
            </h1>
            
            <p className="text-lg sm:text-xl text-indigo-600 font-semibold mb-3">
              제품의 MBTI를 만나세요
            </p>
            
            <p className="text-base sm:text-lg text-gray-600 max-w-2xl mx-auto leading-relaxed">
              P-CODE는 제품의 성향을 분석해주는 <strong>16가지 유형 진단 시스템</strong>입니다.<br className="hidden sm:block" />
              당신의 제품이 어떤 성격을 지녔는지 알아보세요.
            </p>
          </div>

          {/* Feature Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-10">
            {[
              { icon: '🎯', title: '16가지 유형', desc: 'MBTI처럼 4축으로 분석하는 제품 성향 진단' },
              { icon: '📊', title: '24개 문항', desc: '4개 핵심 축을 정밀하게 측정하는 전문 질문' },
              { icon: '🚀', title: '전략 가이드', desc: '유형별 마케팅 전략과 채널 추천 제공' },
            ].map((item, i) => (
              <div key={i} className="bg-white/70 backdrop-blur-sm rounded-2xl p-5 border border-white shadow-sm card-hover">
                <div className="text-3xl mb-3">{item.icon}</div>
                <h3 className="font-bold text-gray-800 mb-1">{item.title}</h3>
                <p className="text-sm text-gray-500">{item.desc}</p>
              </div>
            ))}
          </div>

          {/* 축 설명 */}
          <div className="bg-white/80 backdrop-blur-sm rounded-2xl p-6 border border-white shadow-sm mb-10">
            <h3 className="font-bold text-gray-700 mb-4 text-center text-sm uppercase tracking-wider">P-CODE 분석 4개 축</h3>
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              {[
                { axis: 'U ↔ S', name: '실용성 vs 스타일', color: 'from-blue-400 to-pink-400' },
                { axis: 'T ↔ C', name: '트렌드 vs 클래식', color: 'from-green-400 to-yellow-400' },
                { axis: 'F ↔ E', name: '기능 vs 감성', color: 'from-red-400 to-purple-400' },
                { axis: 'P ↔ G', name: '개인용 vs 선물용', color: 'from-gray-400 to-yellow-400' },
              ].map((item, i) => (
                <div key={i} className="text-center">
                  <div className={`inline-block bg-gradient-to-r ${item.color} text-white text-xs font-bold px-3 py-1 rounded-full mb-2`}>
                    {item.axis}
                  </div>
                  <p className="text-xs text-gray-600">{item.name}</p>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Form Section */}
      <div className="max-w-2xl mx-auto px-4 sm:px-6 pb-16">
        <div className="bg-white rounded-3xl shadow-xl border border-gray-100 overflow-hidden">
          <div className="bg-gradient-to-r from-indigo-500 to-purple-500 px-8 py-6">
            <h2 className="text-xl font-bold text-white">제품 정보 입력</h2>
            <p className="text-indigo-100 text-sm mt-1">진단을 시작하기 전에 제품 기본 정보를 입력해주세요</p>
          </div>

          <form onSubmit={handleSubmit} className="p-6 sm:p-8 space-y-6">
            {/* 제품명 */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                제품명 <span className="text-red-400">*</span>
              </label>
              <input
                type="text"
                value={formData.productName}
                onChange={(e) => handleChange('productName', e.target.value)}
                onBlur={() => handleBlur('productName')}
                placeholder="예: 프리미엄 무선 이어폰 X100"
                maxLength={50}
                className={`w-full px-4 py-3 border-2 rounded-xl text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-300 transition-all ${
                  errors.productName ? 'border-red-300 bg-red-50' : 'border-gray-200 focus:border-indigo-400'
                }`}
              />
              <div className="flex justify-between mt-1">
                {errors.productName ? (
                  <p className="text-xs text-red-500 flex items-center gap-1">
                    <i className="fas fa-exclamation-circle"></i> {errors.productName}
                  </p>
                ) : <span></span>}
                <span className="text-xs text-gray-400">{formData.productName.length}/50</span>
              </div>
            </div>

            {/* 카테고리 */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                카테고리 <span className="text-red-400">*</span>
              </label>
              <select
                value={formData.category}
                onChange={(e) => handleChange('category', e.target.value)}
                onBlur={() => handleBlur('category')}
                className={`w-full px-4 py-3 border-2 rounded-xl text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-300 transition-all appearance-none bg-white cursor-pointer ${
                  errors.category ? 'border-red-300 bg-red-50' : 'border-gray-200 focus:border-indigo-400'
                } ${!formData.category ? 'text-gray-400' : 'text-gray-800'}`}
                style={{ backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236B7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E\")", backgroundRepeat: 'no-repeat', backgroundPosition: 'right 12px center', backgroundSize: '20px' }}
              >
                {helpers.CATEGORIES.map(cat => (
                  <option key={cat.value} value={cat.value}>{cat.label}</option>
                ))}
              </select>
              {errors.category && (
                <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                  <i className="fas fa-exclamation-circle"></i> {errors.category}
                </p>
              )}
            </div>

            {/* 가격 */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                가격 <span className="text-red-400">*</span>
              </label>
              <div className="relative">
                <input
                  type="number"
                  value={formData.price}
                  onChange={(e) => handleChange('price', e.target.value)}
                  onBlur={() => handleBlur('price')}
                  placeholder="예: 89000"
                  min="1"
                  className={`w-full px-4 py-3 pr-12 border-2 rounded-xl text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-300 transition-all ${
                    errors.price ? 'border-red-300 bg-red-50' : 'border-gray-200 focus:border-indigo-400'
                  }`}
                />
                <span className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 font-medium text-sm">원</span>
              </div>
              {formData.price && !errors.price && (
                <p className="mt-1 text-xs text-indigo-500">
                  = {helpers.formatPrice(formData.price)}원
                </p>
              )}
              {errors.price && (
                <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                  <i className="fas fa-exclamation-circle"></i> {errors.price}
                </p>
              )}
            </div>

            {/* 제품 링크 (선택) */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                제품 링크 <span className="text-gray-400 font-normal">(선택)</span>
              </label>
              <input
                type="url"
                value={formData.productLink}
                onChange={(e) => handleChange('productLink', e.target.value)}
                onBlur={() => handleBlur('productLink')}
                placeholder="https://www.example.com/product"
                className={`w-full px-4 py-3 border-2 rounded-xl text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-300 transition-all ${
                  errors.productLink ? 'border-red-300 bg-red-50' : 'border-gray-200 focus:border-indigo-400'
                }`}
              />
              {errors.productLink && (
                <p className="mt-1 text-xs text-red-500 flex items-center gap-1">
                  <i className="fas fa-exclamation-circle"></i> {errors.productLink}
                </p>
              )}
            </div>

            {/* 진단 시작 버튼 */}
            <div className="pt-2">
              <button
                type="submit"
                disabled={!isFormValid()}
                className={`w-full py-4 px-6 rounded-2xl font-bold text-lg transition-all duration-200 flex items-center justify-center gap-3 ${
                  isFormValid()
                    ? 'text-white shadow-lg hover:shadow-xl hover:-translate-y-0.5'
                    : 'text-gray-400 bg-gray-100 cursor-not-allowed'
                }`}
                style={isFormValid() ? {
                  background: 'linear-gradient(135deg, #6B7AF7 0%, #EC4899 100%)',
                } : {}}
              >
                <span>진단 시작하기</span>
                <span className="text-xl">{isFormValid() ? '🚀' : '🔒'}</span>
              </button>
              
              {!isFormValid() && (
                <p className="text-center text-xs text-gray-400 mt-2">
                  필수 항목(제품명, 카테고리, 가격)을 모두 입력하면 활성화됩니다
                </p>
              )}
            </div>

            {/* 안내 */}
            <div className="bg-indigo-50 rounded-xl p-4">
              <div className="flex items-start gap-3">
                <span className="text-lg">ℹ️</span>
                <div>
                  <p className="text-sm font-semibold text-indigo-700 mb-1">진단 안내</p>
                  <ul className="text-xs text-indigo-600 space-y-1">
                    <li>• 24개의 질문에 5점 척도로 답변합니다</li>
                    <li>• 솔직하고 현재 상황에 맞게 답변할수록 정확도가 높아집니다</li>
                    <li>• 소요 시간: 약 5-10분</li>
                    <li>• 모든 문항에 반드시 답변해야 합니다</li>
                  </ul>
                </div>
              </div>
            </div>
          </form>
        </div>

        {/* 최근 진단 결과 */}
        {recentResults.length > 0 && (
          <div className="mt-8">
            <h3 className="text-sm font-semibold text-gray-500 mb-3 text-center">최근 진단 기록</h3>
            <div className="space-y-2">
              {recentResults.map(r => (
                <div key={r.id} className="bg-white/70 backdrop-blur-sm rounded-xl p-4 border border-gray-100 flex items-center justify-between">
                  <div>
                    <span className="font-semibold text-gray-800 text-sm">{r.productName}</span>
                    <span className="text-xs text-gray-400 ml-2">{r.category}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-bold" style={{
                      background: 'linear-gradient(135deg, #6B7AF7, #EC4899)',
                      WebkitBackgroundClip: 'text',
                      WebkitTextFillColor: 'transparent',
                      backgroundClip: 'text'
                    }}>
                      {window.PCODE_TYPES[r.pcode]?.emoji} {r.pcode}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
