// js/components/ResultPage.jsx
// 결과 페이지 - 탭 없는 순차 스크롤 구조 / 파스텔톤 배경 / 이미지저장+카카오공유

window.ResultPage = function({ result, onRestart }) {
  const { useState, useCallback, useEffect } = React;
  const helpers = window.PCODE_HELPERS;

  const [feedback, setFeedback]       = useState(null);   // 'good' | 'bad' | null
  const [isCapturing, setIsCapturing] = useState(false);  // 이미지 저장 로딩

  const { typeData, productName, category, price, pcode, scores, axes } = result;

  // 스크롤 상단으로
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  // Recharts
  const { RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis,
          Radar, ResponsiveContainer, Tooltip } = Recharts;

  // 레이더 데이터
  const radarData = [
    { axis: 'U/S', value: scores.us, fullMark: 100 },
    { axis: 'T/C', value: scores.tc, fullMark: 100 },
    { axis: 'F/E', value: scores.fe, fullMark: 100 },
    { axis: 'P/G', value: scores.pg, fullMark: 100 },
  ];

  // 4축 바 데이터
  const axisData = [
    { id:'us', code:axes.us.code, percentage:scores.us,
      leftLabel:'U (실용)',  rightLabel:'S (스타일)',
      leftColor:'#3B82F6',  rightColor:'#EC4899',
      description: helpers.getAxisDescription('US', axes.us.code, scores.us) },
    { id:'tc', code:axes.tc.code, percentage:scores.tc,
      leftLabel:'T (트렌드)', rightLabel:'C (클래식)',
      leftColor:'#10B981',  rightColor:'#F59E0B',
      description: helpers.getAxisDescription('TC', axes.tc.code, scores.tc) },
    { id:'fe', code:axes.fe.code, percentage:scores.fe,
      leftLabel:'F (기능)',  rightLabel:'E (감성)',
      leftColor:'#EF4444',  rightColor:'#A855F7',
      description: helpers.getAxisDescription('FE', axes.fe.code, scores.fe) },
    { id:'pg', code:axes.pg.code, percentage:scores.pg,
      leftLabel:'P (개인용)', rightLabel:'G (선물용)',
      leftColor:'#9CA3AF',  rightColor:'#FBBF24',
      description: helpers.getAxisDescription('PG', axes.pg.code, scores.pg) },
  ];

  // 커스텀 레이더 레이블
  const CustomAxisTick = ({ x, y, payload }) => {
    const C = { 'U/S':'#6B7AF7','T/C':'#10B981','F/E':'#EF4444','P/G':'#F59E0B' };
    return (
      <g>
        <text x={x} y={y} textAnchor="middle" dominantBaseline="middle"
          fill={C[payload.value] || '#666'} fontSize="12" fontWeight="bold"
          fontFamily="Noto Sans KR, sans-serif">
          {payload.value}
        </text>
      </g>
    );
  };

  /* ════════════════════════════════════════
     📷  이미지 저장 (html2canvas)
  ════════════════════════════════════════ */
  const handleDownloadImage = useCallback(async () => {
    setIsCapturing(true);
    try {
      // html2canvas 동적 로드
      if (!window.html2canvas) {
        await new Promise((resolve, reject) => {
          const s = document.createElement('script');
          s.src = 'https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js';
          s.onload = resolve;
          s.onerror = reject;
          document.head.appendChild(s);
        });
      }

      // 캡처 대상: 전체 결과 페이지
      const target = document.getElementById('result-capture-area');
      if (!target) { alert('캡처 영역을 찾을 수 없습니다.'); return; }

      const canvas = await window.html2canvas(target, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff',
        scrollY: -window.scrollY,
        windowWidth: document.documentElement.scrollWidth,
        windowHeight: document.documentElement.scrollHeight,
      });

      // PNG 다운로드
      const link = document.createElement('a');
      const safeProductName = productName.replace(/[^가-힣a-zA-Z0-9]/g, '_');
      link.download = `${safeProductName}_${pcode}_PCODE결과.png`;
      link.href = canvas.toDataURL('image/png');
      link.click();
    } catch (err) {
      console.error('이미지 저장 실패:', err);
      alert('이미지 저장에 실패했습니다.\n브라우저의 인쇄(Ctrl+P) 기능으로 PDF를 저장해보세요.');
    } finally {
      setIsCapturing(false);
    }
  }, [productName, pcode]);

  /* ════════════════════════════════════════
     💬  카카오톡 공유
     – Kakao SDK 없이 카카오 링크 공유 페이지를 이용
     – 실제 배포 환경에서는 Kakao SDK + 앱 키를 세팅하세요
  ════════════════════════════════════════ */
  const handleKakaoShare = useCallback(() => {
    const msg = [
      `🎯 [P-CODE 진단 결과]`,
      ``,
      `제품명: ${productName}`,
      `카테고리: ${category} | 가격: ${helpers.formatPrice(price)}원`,
      ``,
      `${typeData?.emoji}  P-CODE: ${pcode}`,
      `유형: The ${typeData?.name} (${typeData?.name_kr})`,
      ``,
      `"${typeData?.description?.substring(0, 80)}..."`,
      ``,
      `💡 핵심 메시지: ${typeData?.marketing_tone?.core}`,
      ``,
      `👉 지금 당신의 제품 P-CODE를 진단해보세요!`,
    ].join('\n');

    // Kakao SDK가 로드된 경우 SDK 공유, 아니면 텍스트 복사로 fallback
    if (window.Kakao && window.Kakao.isInitialized && window.Kakao.isInitialized()) {
      window.Kakao.Share.sendDefault({
        objectType: 'text',
        text: msg,
        link: { mobileWebUrl: window.location.href, webUrl: window.location.href },
      });
    } else {
      // fallback: 클립보드 복사 후 안내
      if (navigator.clipboard) {
        navigator.clipboard.writeText(msg).then(() => {
          alert('📋 결과 내용이 클립보드에 복사되었습니다!\n카카오톡을 열어 붙여넣기(Ctrl+V) 해주세요.');
        }).catch(() => {
          // 최후 fallback: kakaolink 웹 공유
          const encoded = encodeURIComponent(msg.substring(0, 500));
          window.open(`https://sharer.kakao.com/talk/friends/picker/link?app_key=YOUR_APP_KEY&text=${encoded}`, '_blank', 'width=500,height=600');
        });
      } else {
        const encoded = encodeURIComponent(msg.substring(0, 500));
        window.open(`https://sharer.kakao.com/talk/friends/picker/link?app_key=YOUR_APP_KEY&text=${encoded}`, '_blank', 'width=500,height=600');
      }
    }
  }, [productName, category, price, pcode, typeData, helpers]);

  /* ════════════════════════════════════════
     공통 컴포넌트
  ════════════════════════════════════════ */
  const SectionHeader = ({ emoji, title, subtitle }) => (
    <div className="mb-6">
      <h2 style={{ fontSize:'1.6rem', fontWeight:900, color:'#1F2937',
                   display:'flex', alignItems:'center', gap:'8px', margin:0 }}>
        <span>{emoji}</span><span>{title}</span>
      </h2>
      {subtitle && (
        <p style={{ fontSize:'0.85rem', color:'#6B7280', marginTop:'4px', marginLeft:'36px' }}>
          {subtitle}
        </p>
      )}
    </div>
  );

  const SubHeader = ({ emoji, title, color }) => (
    <h3 style={{ fontSize:'1rem', fontWeight:700, color: color||'#374151',
                 display:'flex', alignItems:'center', gap:'6px',
                 marginBottom:'12px', marginTop:0 }}>
      <span>{emoji}</span><span>{title}</span>
    </h3>
  );

  // 카드 공통 스타일
  const card = {
    background:'#fff', borderRadius:'20px',
    border:'1px solid #E5E7EB', padding:'24px',
    marginBottom:'16px', boxShadow:'0 1px 4px rgba(0,0,0,0.04)'
  };

  return (
    <div style={{ minHeight:'100vh', background:'#F9FAFB', fontFamily:'Noto Sans KR,Inter,sans-serif' }}>

      {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          1️⃣  최상단 헤더 — 파스텔 보라 배경
      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
      <div id="section-result-header" style={{ background:'#F0E6FF', borderBottom:'2px solid #E9D5FF' }}>
        <div style={{ maxWidth:'768px', margin:'0 auto', padding:'40px 20px 36px' }}>

          {/* 상단 레이블 */}
          <p style={{ textAlign:'center', fontSize:'0.78rem', fontWeight:600,
                      letterSpacing:'0.1em', color:'#7C3AED', marginBottom:'20px',
                      textTransform:'uppercase' }}>
            당신의 제품 P-CODE 결과 보고서
          </p>

          {/* 제품 정보 행 */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)',
                        gap:'8px', marginBottom:'24px',
                        background:'#fff', borderRadius:'16px',
                        border:'1px solid #E9D5FF', padding:'16px 20px' }}>
            {[
              { label:'제품명',    value: productName },
              { label:'카테고리', value: category },
              { label:'가격',      value: helpers.formatPrice(price)+'원' },
            ].map(({ label, value }) => (
              <div key={label} style={{ textAlign:'center' }}>
                <p style={{ fontSize:'0.7rem', color:'#A78BFA', marginBottom:'2px', fontWeight:600 }}>{label}</p>
                <p style={{ fontSize:'0.85rem', fontWeight:700, color:'#1F2937',
                            overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{value}</p>
              </div>
            ))}
          </div>

          {/* P-CODE 메인 박스 */}
          <div style={{ background:'#fff', border:'2px solid #E9D5FF',
                        borderRadius:'24px', padding:'36px 24px', textAlign:'center' }}>
            <div style={{ fontSize:'64px', marginBottom:'12px' }}>{typeData?.emoji || '🎯'}</div>

            <div style={{ fontSize:'clamp(48px,10vw,80px)', fontWeight:900,
                          letterSpacing:'0.15em', color:'#6D28D9', lineHeight:1.1,
                          marginBottom:'10px' }}>
              {pcode}
            </div>

            <div style={{ fontSize:'clamp(18px,4vw,24px)', fontWeight:700,
                          color:'#4C1D95', marginBottom:'8px' }}>
              The {typeData?.name}
            </div>

            <div style={{ display:'inline-flex', alignItems:'center',
                          background:'#F0E6FF', border:'1px solid #DDD6FE',
                          borderRadius:'999px', padding:'6px 20px',
                          marginBottom:'16px' }}>
              <span style={{ fontSize:'0.9rem', fontWeight:600, color:'#6D28D9' }}>
                {typeData?.name_kr}
              </span>
            </div>

            <p style={{ fontSize:'0.9rem', color:'#4B5563', lineHeight:1.7,
                        maxWidth:'480px', margin:'0 auto' }}>
              {typeData?.description?.substring(0, 130)}...
            </p>
          </div>

          {/* 4축 미니 스코어 */}
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)',
                        gap:'8px', marginTop:'16px' }}>
            {axisData.map(item => (
              <div key={item.id} style={{ background:'#fff', border:'1px solid #E9D5FF',
                                          borderRadius:'14px', padding:'12px 8px', textAlign:'center' }}>
                <div style={{ fontSize:'1.1rem', fontWeight:900, color:'#6D28D9', marginBottom:'4px' }}>
                  {item.code}
                </div>
                <div style={{ width:'100%', height:'6px', background:'#EDE9FE',
                              borderRadius:'3px', overflow:'hidden', marginBottom:'4px' }}>
                  <div style={{ height:'100%', width:`${item.percentage}%`,
                                background:'linear-gradient(90deg,#8B5CF6,#EC4899)',
                                borderRadius:'3px', transition:'width 1s' }} />
                </div>
                <div style={{ fontSize:'0.7rem', color:'#7C3AED', fontWeight:600 }}>
                  {item.percentage}%
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── 본문 캡처 대상 영역 시작 ── */}
      <div id="result-capture-area">
        <div style={{ maxWidth:'768px', margin:'0 auto', padding:'0 16px' }}>

          {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              2️⃣  레이더 차트
          ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
          <section id="section-radar" style={{ marginTop:'32px' }}>
            <div style={card}>
              <SubHeader emoji="📡" title="4축 성향 분석" color="#4F46E5" />
              <div style={{ display:'grid', gridTemplateColumns:'1fr', gap:'24px' }}
                   className="sm-grid-2col">
                <div style={{ height:'260px' }}>
                  <ResponsiveContainer width="100%" height="100%">
                    <RadarChart data={radarData} margin={{ top:10,right:20,bottom:10,left:20 }}>
                      <PolarGrid stroke="#E5E7EB" />
                      <PolarAngleAxis dataKey="axis" tick={<CustomAxisTick />} tickLine={false} />
                      <PolarRadiusAxis angle={90} domain={[0,100]}
                        tick={{ fontSize:9, fill:'#9CA3AF' }} tickCount={5} />
                      <Radar name="P-CODE 점수" dataKey="value"
                        stroke="#6B7AF7" fill="#6B7AF7" fillOpacity={0.22} strokeWidth={2.5} />
                      <Tooltip content={({ payload }) => {
                        if (!payload?.[0]) return null;
                        return (
                          <div style={{ background:'#fff', border:'1px solid #E5E7EB',
                                        borderRadius:8, padding:'6px 10px', fontSize:12,
                                        boxShadow:'0 4px 12px rgba(0,0,0,0.08)' }}>
                            <p style={{ fontWeight:700, color:'#374151', margin:0 }}>
                              {payload[0].payload.axis}
                            </p>
                            <p style={{ color:'#6B7AF7', margin:0 }}>{payload[0].value}%</p>
                          </div>
                        );
                      }} />
                    </RadarChart>
                  </ResponsiveContainer>
                </div>

                <div style={{ display:'flex', flexDirection:'column', gap:'16px' }}>
                  {axisData.map(item => (
                    <div key={item.id}>
                      <div style={{ display:'flex', justifyContent:'space-between',
                                    fontSize:'0.75rem', fontWeight:600, marginBottom:'6px' }}>
                        <span style={{ color:item.leftColor }}>{item.leftLabel}</span>
                        <span style={{ color:item.rightColor }}>{item.rightLabel}</span>
                      </div>
                      <div style={{ position:'relative', width:'100%', height:'20px',
                                    background:'#F3F4F6', borderRadius:'10px', overflow:'hidden' }}>
                        <div style={{
                          height:'100%', width:`${item.percentage}%`,
                          background:`linear-gradient(90deg,${item.leftColor},${item.rightColor})`,
                          borderRadius:'10px', display:'flex', alignItems:'center',
                          justifyContent:'flex-end', paddingRight:'8px',
                          transition:'width 1s'
                        }}>
                          <span style={{ color:'#fff', fontSize:'0.7rem',
                                         fontWeight:900, textShadow:'0 1px 2px rgba(0,0,0,0.3)' }}>
                            {item.code}
                          </span>
                        </div>
                      </div>
                      <p style={{ fontSize:'0.72rem', color:'#6B7280', marginTop:'4px' }}>
                        {item.description}
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </section>

          {/* 구분선 */}
          <div style={{ borderTop:'2px solid #E5E7EB', margin:'40px 0' }} />

          {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              3️⃣  유형 분석  — 연한 노란 배경 섹션
          ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
          <section id="section-type-analysis">
            <SectionHeader emoji="✨" title="유형 분석"
              subtitle={`${pcode} 유형의 특성과 소비자 프로필을 확인하세요`} />

            {/* 유형 카드 */}
            <div style={card}>
              <div style={{ display:'flex', alignItems:'center', gap:'16px', marginBottom:'16px' }}>
                <div style={{ width:'56px', height:'56px', borderRadius:'16px', flexShrink:0,
                              background:`${typeData?.color||'#6B7AF7'}18`,
                              display:'flex', alignItems:'center', justifyContent:'center',
                              fontSize:'28px' }}>
                  {typeData?.emoji}
                </div>
                <div>
                  <h3 style={{ fontSize:'1.2rem', fontWeight:900, color:'#1F2937', margin:0 }}>
                    The {typeData?.name}
                    <span style={{ marginLeft:'8px', fontSize:'0.9rem',
                                   fontWeight:600, color:'#9CA3AF' }}>({pcode})</span>
                  </h3>
                  <p style={{ fontSize:'0.85rem', color:'#6D28D9',
                               fontWeight:600, margin:'2px 0 0' }}>{typeData?.name_kr}</p>
                </div>
              </div>
              <p style={{ color:'#374151', lineHeight:1.75, fontSize:'0.9rem' }}>
                {typeData?.description}
              </p>
            </div>

            {/* 소비자 프로필 */}
            <div style={card}>
              <SubHeader emoji="👤" title="소비자 프로필" color="#2563EB" />
              <div style={{ background:'#EFF6FF', border:'1px solid #BFDBFE',
                            borderRadius:'14px', padding:'16px 20px' }}>
                <p style={{ color:'#374151', lineHeight:1.75, fontSize:'0.9rem', margin:0 }}>
                  {typeData?.consumer_profile}
                </p>
              </div>
            </div>

            {/* 코드 해석 */}
            <div style={card}>
              <SubHeader emoji="🔍" title="코드 해석" color="#7C3AED" />
              <div style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)',
                            gap:'10px' }} className="sm-grid-4col">
                {[
                  { code:axes.us.code, axis:'U/S', labels:{ U:'실용 중심', S:'스타일 중심' }, color:'#3B82F6' },
                  { code:axes.tc.code, axis:'T/C', labels:{ T:'트렌드 지향', C:'클래식 지향' }, color:'#10B981' },
                  { code:axes.fe.code, axis:'F/E', labels:{ F:'기능 우선', E:'감성 우선' }, color:'#EF4444' },
                  { code:axes.pg.code, axis:'P/G', labels:{ P:'개인용', G:'선물용' }, color:'#F59E0B' },
                ].map((item, i) => (
                  <div key={i} style={{ borderRadius:'14px', padding:'16px', textAlign:'center',
                                        border:`1px solid ${item.color}30`,
                                        background:`${item.color}0A` }}>
                    <div style={{ fontSize:'2rem', fontWeight:900, color:item.color,
                                  marginBottom:'4px' }}>{item.code}</div>
                    <div style={{ fontSize:'0.7rem', color:'#9CA3AF',
                                  marginBottom:'4px' }}>{item.axis}축</div>
                    <div style={{ fontSize:'0.78rem', fontWeight:700, color:'#374151' }}>
                      {item.labels[item.code]}
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* 핵심 인사이트 */}
            <div style={{ ...card, background:'#FEFCE8', border:'1px solid #FEF08A' }}>
              <SubHeader emoji="💡" title="핵심 인사이트" color="#B45309" />
              <p style={{ color:'#374151', lineHeight:1.75, fontSize:'0.9rem', margin:0 }}>
                {typeData?.insight}
              </p>
            </div>
          </section>

          {/* 구분선 */}
          <div style={{ borderTop:'2px solid #E5E7EB', margin:'40px 0' }} />

          {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              4️⃣  전략 가이드  — 연한 초록 배경 섹션
          ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
          <section id="section-strategy">
            <SectionHeader emoji="📊" title="전략 가이드"
              subtitle="이 유형에 최적화된 마케팅 전략과 카피를 활용하세요" />

            {/* 4-1 추천 전략 */}
            <div style={card}>
              <SubHeader emoji="✅" title="추천 전략" color="#059669" />
              <div style={{ display:'flex', flexDirection:'column', gap:'10px' }}>
                {typeData?.recommended_strategies?.map((strategy, i) => {
                  const dotIdx = strategy.indexOf('. ');
                  const title  = dotIdx > 0 ? strategy.substring(0, dotIdx+1) : strategy;
                  const detail = dotIdx > 0 ? strategy.substring(dotIdx+2) : '';
                  return (
                    <div key={i} style={{ display:'flex', gap:'12px',
                                          background:'#F0FDF4', border:'1px solid #BBF7D0',
                                          borderRadius:'14px', padding:'14px 16px' }}>
                      <span style={{ flexShrink:0, width:'24px', height:'24px',
                                     borderRadius:'50%', background:'#22C55E',
                                     color:'#fff', fontSize:'0.7rem', fontWeight:900,
                                     display:'flex', alignItems:'center',
                                     justifyContent:'center', marginTop:'2px' }}>
                        {i+1}
                      </span>
                      <div>
                        <p style={{ fontWeight:700, color:'#1F2937',
                                    fontSize:'0.9rem', margin:0 }}>{title}</p>
                        {detail && (
                          <p style={{ color:'#4B5563', fontSize:'0.85rem',
                                      lineHeight:1.65, marginTop:'4px', marginBottom:0 }}>
                            {detail}
                          </p>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* 4-2 마케팅 톤 */}
            <div style={card}>
              <SubHeader emoji="💬" title="마케팅 톤 & 카피" color="#7C3AED" />

              <div style={{ background:'linear-gradient(135deg,#F5F3FF,#EEF2FF)',
                            border:'1px solid #DDD6FE', borderRadius:'14px',
                            padding:'18px 20px', marginBottom:'14px' }}>
                <p style={{ fontSize:'0.7rem', color:'#7C3AED', fontWeight:700,
                             letterSpacing:'0.08em', textTransform:'uppercase',
                             marginBottom:'6px' }}>💡 핵심 메시지</p>
                <p style={{ fontSize:'1.1rem', fontWeight:900, color:'#1F2937',
                             lineHeight:1.4, margin:0 }}>
                  "{typeData?.marketing_tone?.core}"
                </p>
              </div>

              <p style={{ fontSize:'0.85rem', fontWeight:700, color:'#374151',
                          marginBottom:'10px' }}>✍️ 추천 카피 예시</p>
              <div style={{ display:'flex', flexDirection:'column', gap:'8px' }}>
                {typeData?.marketing_tone?.examples?.map((ex, i) => (
                  <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:'10px',
                                        background:'#FAFAFA', border:'1px solid #E5E7EB',
                                        borderRadius:'12px', padding:'12px 14px' }}>
                    <span style={{ color:'#A78BFA', fontWeight:700, flexShrink:0, marginTop:'1px' }}>•</span>
                    <p style={{ color:'#374151', fontSize:'0.9rem', fontStyle:'italic',
                                lineHeight:1.65, margin:0 }}>"{ex}"</p>
                  </div>
                ))}
              </div>
            </div>

            {/* 4-3 패키징 */}
            <div style={card}>
              <SubHeader emoji="📦" title="패키징 / 기획전 컨셉" color="#EA580C" />
              <div style={{ background:'#FFF7ED', border:'1px solid #FED7AA',
                            borderRadius:'14px', padding:'16px 18px' }}>
                <p style={{ color:'#374151', fontSize:'0.9rem', lineHeight:1.7, margin:0 }}>
                  {typeData?.packaging_concept}
                </p>
              </div>
            </div>
          </section>

          {/* 구분선 */}
          <div style={{ borderTop:'2px solid #E5E7EB', margin:'40px 0' }} />

          {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              5️⃣  시장 데이터  — 연한 분홍 배경 섹션
          ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
          <section id="section-market">
            <SectionHeader emoji="📈" title="시장 데이터 & 채널 전략"
              subtitle="어디서, 누구에게 팔아야 하는지 확인하세요" />

            {/* 5-1 채널 */}
            <div style={card}>
              <SubHeader emoji="🏪" title="추천 판매 채널" color="#2563EB" />
              <div style={{ background:'#EFF6FF', border:'1px solid #BFDBFE',
                            borderRadius:'14px', padding:'14px 18px', marginBottom:'14px' }}>
                <p style={{ fontSize:'0.7rem', color:'#3B82F6', fontWeight:700,
                             letterSpacing:'0.08em', textTransform:'uppercase',
                             marginBottom:'4px' }}>🎯 1순위 채널</p>
                <p style={{ fontWeight:700, color:'#1F2937', fontSize:'0.95rem', margin:0 }}>
                  {typeData?.channel_priority}
                </p>
              </div>
              <p style={{ fontSize:'0.75rem', fontWeight:700, color:'#6B7280',
                          marginBottom:'10px' }}>📱 전체 추천 채널</p>
              <div style={{ display:'flex', flexWrap:'wrap', gap:'8px' }}>
                {typeData?.recommended_channels?.map((ch, i) => (
                  <span key={i} style={i === 0 ? {
                    background:'linear-gradient(135deg,#EEF2FF,#FAF5FF)',
                    border:'1px solid #818CF8', color:'#4F46E5',
                    boxShadow:'0 0 0 2px #C7D2FE', borderRadius:'999px',
                    padding:'6px 14px', fontSize:'0.85rem', fontWeight:700
                  } : {
                    background:'#F9FAFB', border:'1px solid #E5E7EB',
                    color:'#4B5563', borderRadius:'999px',
                    padding:'6px 14px', fontSize:'0.85rem', fontWeight:600
                  }}>
                    {i === 0 && '⭐ '}{ch}
                  </span>
                ))}
              </div>
            </div>

            {/* 5-2 유사 제품 */}
            <div style={card}>
              <SubHeader emoji="🛍️" title="같은 유형 제품 예시" color="#059669" />
              <p style={{ fontSize:'0.8rem', color:'#6B7280', marginBottom:'10px' }}>
                이 유형과 유사한 성공 제품들
              </p>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)',
                            gap:'8px' }} className="sm-grid-4col">
                {typeData?.product_examples?.map((ex, i) => (
                  <div key={i} style={{ background:'#F0FDF4', border:'1px solid #BBF7D0',
                                        borderRadius:'12px', padding:'10px',
                                        textAlign:'center' }}>
                    <p style={{ color:'#1F2937', fontSize:'0.85rem',
                                fontWeight:600, margin:0 }}>• {ex}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* 5-3 페르소나 */}
            <div style={card}>
              <SubHeader emoji="👤" title="소비자 페르소나" color="#B45309" />
              <div style={{ background:'#FFFBEB', border:'1px solid #FDE68A',
                            borderRadius:'14px', padding:'16px 18px', marginBottom:'14px' }}>
                <p style={{ fontSize:'0.7rem', color:'#B45309', fontWeight:700,
                             marginBottom:'6px' }}>핵심 소비자</p>
                <p style={{ fontWeight:700, color:'#1F2937',
                             fontSize:'1rem', lineHeight:1.6, margin:0 }}>
                  "{typeData?.consumer_persona}"
                </p>
              </div>
              <p style={{ fontSize:'0.75rem', fontWeight:700, color:'#6B7280',
                          marginBottom:'8px' }}>이들의 특징</p>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'8px' }}>
                {[
                  typeData?.consumer_profile?.split('. ')[0] + '.',
                  typeData?.consumer_profile?.split('. ')[1]
                    ? typeData?.consumer_profile?.split('. ')[1] + '.' : null,
                  `${typeData?.marketing_tone?.core}에 강하게 반응합니다.`,
                  `주요 채널: ${typeData?.recommended_channels?.slice(0,2).join(', ')}`,
                ].filter(Boolean).map((feat, i) => (
                  <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:'8px',
                                        background:'#F9FAFB', border:'1px solid #E5E7EB',
                                        borderRadius:'12px', padding:'10px 12px' }}>
                    <span style={{ flexShrink:0, width:'20px', height:'20px',
                                   borderRadius:'50%', background:'#FBBF24',
                                   color:'#fff', fontSize:'0.65rem', fontWeight:900,
                                   display:'flex', alignItems:'center',
                                   justifyContent:'center', marginTop:'1px' }}>{i+1}</span>
                    <p style={{ color:'#374151', fontSize:'0.8rem',
                                lineHeight:1.55, margin:0 }}>{feat}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* 5-4 시장 통찰 */}
            <div style={card}>
              <SubHeader emoji="🔭" title="시장 통찰" color="#DC2626" />
              <div style={{ display:'flex', flexDirection:'column', gap:'12px' }}>
                {[
                  { icon:'📊', label:'시장 규모 및 성향', color:'#DC2626', bg:'#FEF2F2', border:'#FECACA',
                    text: typeData?.insight },
                  { icon:'🌐', label:'주요 활동 플랫폼', color:'#2563EB', bg:'#EFF6FF', border:'#BFDBFE',
                    text: `${typeData?.channel_priority} 채널에서 가장 높은 전환율을 보입니다. ${typeData?.recommended_channels?.slice(0,3).join(', ')} 순서로 마케팅 예산을 배분하세요.` },
                  { icon:'💼', label:'기업을 위한 조언', color:'#7C3AED', bg:'#FAF5FF', border:'#E9D5FF',
                    text: `"${typeData?.marketing_tone?.core}"를 핵심 메시지로 삼아 모든 채널에서 일관되게 전달하세요. 소비자 페르소나인 "${typeData?.consumer_persona}"를 중심으로 타겟 마케팅을 설계하면 전환율 극대화가 가능합니다.` },
                ].map((item, i) => (
                  <div key={i} style={{ display:'flex', gap:'14px', padding:'14px 16px',
                                        background:item.bg, border:`1px solid ${item.border}`,
                                        borderRadius:'14px' }}>
                    <span style={{ fontSize:'1.2rem', flexShrink:0 }}>{item.icon}</span>
                    <div>
                      <p style={{ fontSize:'0.72rem', fontWeight:700, color:item.color,
                                   marginBottom:'4px' }}>{item.label}</p>
                      <p style={{ color:'#374151', fontSize:'0.85rem',
                                   lineHeight:1.65, margin:0 }}>{item.text}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </section>

          {/* 구분선 */}
          <div style={{ borderTop:'2px solid #E5E7EB', margin:'40px 0' }} />

          {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              6️⃣  다음 단계  — 연한 파랑 배경 섹션
          ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
          <section id="section-next-steps">
            <SectionHeader emoji="🚀" title="다음 단계"
              subtitle="P-CODE 결과를 바탕으로 더 깊이 성장하세요" />

            {/* 6-1 심화 AI 진단 */}
            <div style={card}>
              <SubHeader emoji="📊" title="심화 AI 진단이란?" color="#4F46E5" />
              <p style={{ color:'#4B5563', fontSize:'0.9rem', lineHeight:1.7,
                          marginBottom:'16px' }}>
                P-CODE 기반의 기초 진단을 넘어, AI가 귀사 제품의&nbsp;
                <strong style={{ color:'#1F2937' }}>상품 경쟁력 · 콘텐츠 완성도 · 판매 구조</strong>를
                심층 분석합니다. 더 정밀한 데이터 인사이트와 맞춤 전략 보고서를 제공합니다.
              </p>

              <div style={{ display:'flex', flexDirection:'column', gap:'10px', marginBottom:'20px' }}>
                {[
                  { check:'상품 경쟁력 분석',   detail:'동일 카테고리 경쟁사 대비 가격·기능·포지셔닝 분석, 차별화 포인트 도출' },
                  { check:'콘텐츠 완성도 분석', detail:'상세페이지·SNS·광고 소재의 P-CODE 정합성 진단 및 개선 방향 제시' },
                  { check:'판매 구조 분석',      detail:'유통 채널 구성, 가격 설정, 프로모션 전략의 적합성 종합 평가' },
                ].map((item, i) => (
                  <div key={i} style={{ display:'flex', gap:'10px', padding:'12px 14px',
                                        background:'#EEF2FF', border:'1px solid #C7D2FE',
                                        borderRadius:'12px' }}>
                    <span style={{ flexShrink:0, width:'20px', height:'20px',
                                   borderRadius:'50%', background:'#6366F1',
                                   color:'#fff', fontSize:'0.65rem', fontWeight:900,
                                   display:'flex', alignItems:'center', justifyContent:'center',
                                   marginTop:'2px' }}>✓</span>
                    <div>
                      <p style={{ fontWeight:700, color:'#1F2937', fontSize:'0.9rem', margin:0 }}>
                        {item.check}
                      </p>
                      <p style={{ color:'#4B5563', fontSize:'0.82rem',
                                   lineHeight:1.6, marginTop:'2px', marginBottom:0 }}>
                        {item.detail}
                      </p>
                    </div>
                  </div>
                ))}
              </div>

              <div style={{ display:'flex', flexWrap:'wrap', gap:'16px',
                            marginBottom:'20px', fontSize:'0.85rem', color:'#6B7280' }}>
                <span>💰 <strong style={{ color:'#1F2937' }}>가격: 별도 문의</strong></span>
                <span>⏱️ <strong style={{ color:'#1F2937' }}>24시간 내 결과 제공</strong></span>
              </div>

              <button style={{
                padding:'14px 32px', background:'linear-gradient(135deg,#4F46E5,#7C3AED)',
                color:'#fff', fontWeight:700, fontSize:'0.95rem', border:'none',
                borderRadius:'14px', cursor:'pointer', display:'flex',
                alignItems:'center', gap:'8px',
                boxShadow:'0 4px 14px rgba(79,70,229,0.3)',
                transition:'all 0.2s'
              }}>
                <span>📊</span> 심화 진단 신청하기
              </button>
            </div>

            {/* 6-2 마케팅 컨설팅 */}
            <div style={card}>
              <SubHeader emoji="👨‍💼" title="전문가와의 1:1 컨설팅" color="#059669" />
              <p style={{ color:'#4B5563', fontSize:'0.9rem', lineHeight:1.7, marginBottom:'16px' }}>
                P-CODE 진단 결과를 토대로, 각 분야 전문가와 1:1로 실질적인 성장 전략을 수립합니다.
                이론이 아닌 <strong style={{ color:'#1F2937' }}>현장 경험 기반의 맞춤 솔루션</strong>을 제공합니다.
              </p>

              <p style={{ fontSize:'0.75rem', fontWeight:700, color:'#6B7280', marginBottom:'10px' }}>
                📍 분야별 전문가 연결
              </p>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr',
                            gap:'8px', marginBottom:'20px' }}>
                {[
                  { role:'MD 전문가',     desc:'유통 전략, 바이어 미팅, 채널 입점 가이드', icon:'🏬' },
                  { role:'마케팅 전문가', desc:'광고 소재, 캠페인 기획, 퍼포먼스 마케팅',  icon:'📣' },
                  { role:'브랜딩 전문가', desc:'브랜드 아이덴티티, 스토리텔링, 포지셔닝', icon:'🎨' },
                  { role:'유통 전문가',   desc:'오프라인/온라인 유통망 확장 전략 수립',    icon:'🚚' },
                ].map((item, i) => (
                  <div key={i} style={{ display:'flex', gap:'10px', padding:'12px 14px',
                                        background:'#F0FDF4', border:'1px solid #BBF7D0',
                                        borderRadius:'12px' }}>
                    <span style={{ fontSize:'1.1rem', flexShrink:0 }}>{item.icon}</span>
                    <div>
                      <p style={{ fontWeight:700, color:'#1F2937',
                                  fontSize:'0.85rem', margin:0 }}>{item.role}</p>
                      <p style={{ color:'#4B5563', fontSize:'0.78rem',
                                  lineHeight:1.5, marginTop:'2px', marginBottom:0 }}>
                        {item.desc}
                      </p>
                    </div>
                  </div>
                ))}
              </div>

              <button style={{
                padding:'14px 32px', background:'linear-gradient(135deg,#059669,#10B981)',
                color:'#fff', fontWeight:700, fontSize:'0.95rem', border:'none',
                borderRadius:'14px', cursor:'pointer', display:'flex',
                alignItems:'center', gap:'8px',
                boxShadow:'0 4px 14px rgba(5,150,105,0.3)',
                transition:'all 0.2s'
              }}>
                <span>📅</span> 마케팅 컨설팅 예약하기
              </button>
            </div>

            {/* ─────────────────────────────────────────
                6-3  결과 저장 및 공유  ← 수정 핵심 영역
            ───────────────────────────────────────── */}
            <div style={card}>
              <SubHeader emoji="📥" title="결과 저장 및 공유" color="#6D28D9" />

              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr',
                            gap:'14px' }} className="mobile-stack">

                {/* 버튼 1: 이미지로 저장하기 */}
                <button
                  onClick={handleDownloadImage}
                  disabled={isCapturing}
                  style={{
                    display:'flex', alignItems:'center', justifyContent:'center',
                    gap:'8px', padding:'16px 20px',
                    background: isCapturing ? '#EDE9FE' : '#DDD6FE',
                    color:'#6D28D9', border:'1px solid #C4B5FD',
                    borderRadius:'14px', fontWeight:700, fontSize:'0.95rem',
                    cursor: isCapturing ? 'not-allowed' : 'pointer',
                    transition:'all 0.25s',
                    boxShadow:'0 2px 8px rgba(109,40,217,0.08)',
                  }}
                  onMouseEnter={e => { if (!isCapturing) {
                    e.currentTarget.style.background = '#C4B5FD';
                    e.currentTarget.style.transform  = 'translateY(-2px)';
                    e.currentTarget.style.boxShadow  = '0 6px 16px rgba(109,40,217,0.18)';
                  }}}
                  onMouseLeave={e => { if (!isCapturing) {
                    e.currentTarget.style.background = '#DDD6FE';
                    e.currentTarget.style.transform  = 'translateY(0)';
                    e.currentTarget.style.boxShadow  = '0 2px 8px rgba(109,40,217,0.08)';
                  }}}
                >
                  {isCapturing
                    ? <><span style={{ display:'inline-block', width:'16px', height:'16px',
                                       border:'2px solid #6D28D9', borderTopColor:'transparent',
                                       borderRadius:'50%', animation:'spin 0.8s linear infinite' }} />
                        저장 중...</>
                    : <><span>📷</span> 이미지로 저장하기</>
                  }
                </button>

                {/* 버튼 2: 카카오톡으로 보내기 */}
                <button
                  onClick={handleKakaoShare}
                  style={{
                    display:'flex', alignItems:'center', justifyContent:'center',
                    gap:'8px', padding:'16px 20px',
                    background:'#FEF08A', color:'#78350F',
                    border:'1px solid #FDE047',
                    borderRadius:'14px', fontWeight:700, fontSize:'0.95rem',
                    cursor:'pointer', transition:'all 0.25s',
                    boxShadow:'0 2px 8px rgba(251,191,36,0.15)',
                  }}
                  onMouseEnter={e => {
                    e.currentTarget.style.background  = '#FDE047';
                    e.currentTarget.style.transform   = 'translateY(-2px)';
                    e.currentTarget.style.boxShadow   = '0 6px 16px rgba(251,191,36,0.3)';
                  }}
                  onMouseLeave={e => {
                    e.currentTarget.style.background  = '#FEF08A';
                    e.currentTarget.style.transform   = 'translateY(0)';
                    e.currentTarget.style.boxShadow   = '0 2px 8px rgba(251,191,36,0.15)';
                  }}
                >
                  <span>💬</span> 카카오톡으로 보내기
                </button>
              </div>

              <p style={{ textAlign:'center', fontSize:'0.75rem', color:'#9CA3AF',
                          marginTop:'14px', marginBottom:0 }}>
                💾 이 결과는 브라우저에 자동 저장되었습니다 (최근 10개 유지)
              </p>
            </div>
          </section>

          {/* 구분선 */}
          <div style={{ borderTop:'2px solid #E5E7EB', margin:'40px 0' }} />

          {/* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
              7️⃣  피드백 & 하단 액션
          ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ */}
          <section id="section-feedback" style={{ marginBottom:'64px' }}>
            <div style={card}>
              {/* 피드백 */}
              <div style={{ textAlign:'center', marginBottom:'28px' }}>
                <p style={{ fontSize:'1.1rem', fontWeight:900, color:'#1F2937',
                             marginBottom:'4px' }}>이 결과가 도움이 되었나요?</p>
                <p style={{ fontSize:'0.85rem', color:'#6B7280', marginBottom:'16px' }}>
                  솔직한 피드백이 더 나은 진단을 만듭니다
                </p>
                <div style={{ display:'flex', gap:'12px', justifyContent:'center' }}>
                  {[
                    { key:'good', label:'👍 정확함',
                      active:{ background:'#F0FDF4', borderColor:'#22C55E', color:'#15803D' },
                      inactive:{ background:'#fff', borderColor:'#E5E7EB', color:'#6B7280' } },
                    { key:'bad',  label:'👎 보완 필요',
                      active:{ background:'#FEF2F2', borderColor:'#EF4444', color:'#B91C1C' },
                      inactive:{ background:'#fff', borderColor:'#E5E7EB', color:'#6B7280' } },
                  ].map(btn => (
                    <button key={btn.key} onClick={() => setFeedback(btn.key)}
                      style={{
                        padding:'12px 24px', borderRadius:'12px', border:'2px solid',
                        fontWeight:700, fontSize:'0.9rem', cursor:'pointer',
                        transition:'all 0.2s',
                        ...(feedback === btn.key ? btn.active : btn.inactive)
                      }}>
                      {btn.label}
                    </button>
                  ))}
                </div>
                {feedback && (
                  <p style={{ marginTop:'10px', fontSize:'0.85rem', color:'#6B7280' }}>
                    {feedback === 'good'
                      ? '🙏 피드백 감사합니다! 계속 발전하겠습니다.'
                      : '📝 소중한 의견 감사합니다. 더 정확하게 개선하겠습니다!'}
                  </p>
                )}
              </div>

              <div style={{ borderTop:'1px solid #E5E7EB', paddingTop:'20px',
                            display:'flex', flexDirection:'column', gap:'10px' }}>
                {/* 다시 진단 */}
                <button onClick={onRestart} style={{
                  width:'100%', padding:'16px', borderRadius:'16px', border:'none',
                  background:'linear-gradient(135deg,#6B7AF7,#EC4899)',
                  color:'#fff', fontWeight:900, fontSize:'1rem',
                  cursor:'pointer', display:'flex', alignItems:'center',
                  justifyContent:'center', gap:'10px',
                  boxShadow:'0 6px 20px rgba(107,122,247,0.3)',
                  transition:'all 0.2s'
                }}>
                  <span>🔄</span> 다시 진단하기
                </button>

                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'10px' }}>
                  <button style={{
                    padding:'14px', borderRadius:'14px',
                    border:'2px solid #818CF8', background:'#EEF2FF',
                    color:'#4F46E5', fontWeight:700, fontSize:'0.88rem',
                    cursor:'pointer', display:'flex', alignItems:'center',
                    justifyContent:'center', gap:'6px', transition:'all 0.2s'
                  }}>
                    <span>📊</span> 심화 AI 진단 신청
                  </button>
                  <button style={{
                    padding:'14px', borderRadius:'14px',
                    border:'2px solid #6EE7B7', background:'#ECFDF5',
                    color:'#059669', fontWeight:700, fontSize:'0.88rem',
                    cursor:'pointer', display:'flex', alignItems:'center',
                    justifyContent:'center', gap:'6px', transition:'all 0.2s'
                  }}>
                    <span>📈</span> 마케팅 컨설팅 예약
                  </button>
                </div>
              </div>
            </div>

            <p style={{ textAlign:'center', fontSize:'0.75rem',
                        color:'#9CA3AF', marginTop:'12px' }}>
              진단 완료: {helpers.formatDate(result.timestamp)}
            </p>
          </section>

        </div>
      </div>{/* ── 캡처 영역 끝 ── */}

      {/* 반응형 + 스피너 인라인 스타일 */}
      <style>{`
        @media (min-width: 640px) {
          .sm-grid-2col { grid-template-columns: 1fr 1fr !important; }
          .sm-grid-4col { grid-template-columns: repeat(4,1fr) !important; }
        }
        @media (max-width: 480px) {
          .mobile-stack { grid-template-columns: 1fr !important; }
        }
        @keyframes spin {
          to { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
};
