// help.jsx — Help & FAQ screen

const HP = window.__cpMakeTheme();

const HELP_CATEGORIES = [
  { id: 'start',     label: '시작하기',     icon: '👋', desc: '처음 사용하기' },
  { id: 'cards',     label: '씨앗 관리',    icon: '📇', desc: '담기·편집·삭제' },
  { id: 'coll',      label: '주머니',       icon: '📁', desc: '폴더처럼 정리' },
  { id: 'share',     label: '공유·친구',    icon: '🤝', desc: '주머니·넛지' },
  { id: 'quota',     label: '한도·결제',    icon: '💳', desc: '볼주머니 한도' },
  { id: 'account',   label: '계정·데이터',  icon: '🔑', desc: '로그인·동기화' },
];

const FAQ_ITEMS = [
  {
    id: 'q1', category: 'start',
    q: '어떻게 시작하나요?',
    a: '홈 우상단 + 버튼을 눌러 한국어로 표현을 적으면, AI가 외국어로 옮기고 발음까지 만들어줘요. 입력 화면에서 언어·톤·카테고리도 미리 정할 수 있어요.',
  },
  {
    id: 'q2', category: 'cards',
    q: '스크린샷에서 표현을 담을 수도 있나요?',
    a: '네. 입력 화면 하단의 "스크린샷" 버튼을 누르면 사진 보관함에서 골라 텍스트를 자동으로 감지해요. 원하는 문장만 골라 한꺼번에 담을 수 있어요.',
  },
  {
    id: 'q3', category: 'cards',
    q: '씨앗의 번역이나 발음이 어색해요',
    a: '씨앗 상세 화면에서 우상단 ⋯ 메뉴를 통해 다시 생성하거나, 직접 수정할 수 있어요. 씨앗별로 톤도 따로 정할 수 있어요.',
  },
  {
    id: 'q4', category: 'coll',
    q: '주머니는 어떻게 만드나요?',
    a: '홈의 주머니 그리드 끝에 있는 점선 "+ 새 주머니" 타일을 누르면 새 주머니 시트가 열려요. 이름·색상·표지를 정할 수 있어요.',
  },
  {
    id: 'q5', category: 'coll',
    q: '주머니를 홈 위쪽에 고정할 수 있나요?',
    a: '주머니 상세 화면의 ⋯ 메뉴에서 "홈에 고정"을 선택하면 홈에서 "고정됨" 섹션에 따로 표시돼요.',
  },
  {
    id: 'q6', category: 'share',
    q: '친구에게 주머니를 어떻게 공유하나요?',
    a: '주머니 상세 → ⋯ → 공유를 누르면 QR 코드와 링크가 나와요. 받는 사람도 편집할 수 있게 할지 토글로 선택해요.',
  },
  {
    id: 'q7', category: 'share',
    q: '넛지는 어떤 기능인가요?',
    a: '친구에게 "오늘 한 장 어때?" 같은 가벼운 알림을 보내는 기능이에요. 친구 탭에서 친구 옆 화살표 버튼을 누르면 보낼 수 있어요.',
  },
  {
    id: 'q8', category: 'quota',
    q: '볼주머니 한도는 뭔가요?',
    a: '무료 가입 시 30개까지 담을 수 있어요. 친구를 초대하거나 광고를 보면 늘릴 수 있고, Pro로 업그레이드하면 무제한이에요.',
  },
  {
    id: 'q9', category: 'quota',
    q: 'Pro 구독을 해지하면 씨앗은 어떻게 되나요?',
    a: '씨앗은 모두 그대로 남아있어요. 다만 새 씨앗을 담을 때는 무료 한도(30개 + 추가로 늘린 양)만큼만 추가할 수 있어요.',
  },
  {
    id: 'q10', category: 'account',
    q: '다른 기기에서도 같은 씨앗을 볼 수 있나요?',
    a: '설정 > 데이터에서 iCloud 동기화를 켜두면 모든 기기에서 같은 주머니를 볼 수 있어요. 같은 계정으로 로그인되어 있어야 해요.',
  },
  {
    id: 'q11', category: 'account',
    q: '계정을 삭제하고 싶어요',
    a: '설정 > 도움말 & 정보 > 문의하기를 통해 요청해주시면 모든 데이터를 안전하게 삭제해드려요.',
  },
];

function HelpScreen({ accent, onBack }) {
  const [q, setQ] = React.useState('');
  const [openId, setOpenId] = React.useState(null);
  const [activeCategory, setActiveCategory] = React.useState(null);

  const query = q.trim().toLowerCase();
  const filteredFaqs = React.useMemo(() => {
    let items = FAQ_ITEMS;
    if (activeCategory) items = items.filter(it => it.category === activeCategory);
    if (query) {
      items = items.filter(it =>
        it.q.toLowerCase().includes(query) ||
        it.a.toLowerCase().includes(query)
      );
    }
    return items;
  }, [query, activeCategory]);

  return (
    <div style={{ paddingBottom: 60 }}>
      {/* Top bar — sticky */}
      <div style={{
        position: 'sticky', top: 0, zIndex: 30,
        background: HP.bg,
        padding: '54px 14px 8px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 38,
          background: 'transparent', border: 'none', padding: 0,
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
          WebkitTapHighlightColor: 'transparent',
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            <path d="M14 4L7 11l7 7" stroke={HP.ink} strokeWidth="1.8"
                  strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{
          fontSize: 16, fontWeight: 600, color: HP.ink,
          letterSpacing: '-0.01em', whiteSpace: 'nowrap',
        }}>도움말</div>
        <div style={{ width: 38 }} />
      </div>

      {/* Heading */}
      <div style={{ padding: '12px 24px 0' }}>
        <div style={{
          fontSize: 28, fontWeight: 700, color: HP.ink,
          letterSpacing: '-0.03em', lineHeight: 1.15,
          textWrap: 'balance',
        }}>어떻게<br/>도와드릴까요?</div>
      </div>

      {/* Search */}
      <div style={{ padding: '20px 22px 0' }}>
        <div style={{
          height: 44, borderRadius: 12,
          background: HP.surface,
          border: `0.5px solid ${HP.hairline}`,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '0 14px',
        }}>
          <svg width="16" height="16" viewBox="0 0 20 20" fill="none">
            <circle cx="9" cy="9" r="6.2" stroke={HP.ink3} strokeWidth="1.6"/>
            <path d="M13.6 13.6L17 17" stroke={HP.ink3} strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
          <input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="궁금한 점을 검색해보세요"
            style={{
              flex: 1, height: '100%',
              background: 'transparent', border: 'none', outline: 'none',
              fontFamily: 'inherit', fontSize: 15, color: HP.ink,
              letterSpacing: '-0.01em',
            }}
          />
          {q && (
            <button onClick={() => setQ('')} style={{
              width: 20, height: 20, borderRadius: 20, padding: 0,
              background: 'rgba(60,42,20,0.18)', border: 'none',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer',
            }}>
              <svg width="9" height="9" viewBox="0 0 10 10">
                <path d="M2 2l6 6M8 2l-6 6" stroke="#FFF" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
            </button>
          )}
        </div>
      </div>

      {/* Categories — only show if not searching */}
      {!query && (
        <>
          <div style={{ padding: '24px 22px 12px',
            fontSize: 11, fontWeight: 600, color: HP.ink3,
            letterSpacing: '0.08em', textTransform: 'uppercase',
          }}>주제별로 보기</div>
          <div style={{
            padding: '0 22px',
            display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
          }}>
            {HELP_CATEGORIES.map(c => {
              const on = activeCategory === c.id;
              return (
                <button key={c.id}
                  onClick={() => setActiveCategory(on ? null : c.id)}
                  style={{
                    padding: '12px 10px',
                    background: on ? `${accent}14` : HP.surface,
                    border: on ? `1.5px solid ${accent}` : `0.5px solid ${HP.hairline}`,
                    borderRadius: 14,
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                    cursor: 'pointer', fontFamily: 'inherit',
                    WebkitTapHighlightColor: 'transparent',
                    minHeight: 88,
                  }}>
                  <span style={{ fontSize: 22, lineHeight: 1, marginBottom: 4 }}>{c.icon}</span>
                  <span style={{
                    fontSize: 12.5, fontWeight: on ? 700 : 600,
                    color: on ? accent : HP.ink,
                    letterSpacing: '-0.01em', whiteSpace: 'nowrap',
                  }}>{c.label}</span>
                  <span style={{
                    fontSize: 10.5, color: HP.ink3,
                    letterSpacing: '-0.01em', whiteSpace: 'nowrap',
                  }}>{c.desc}</span>
                </button>
              );
            })}
          </div>
        </>
      )}

      {/* FAQ list */}
      <div style={{
        padding: '24px 22px 12px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{
          fontSize: 11, fontWeight: 600, color: HP.ink3,
          letterSpacing: '0.08em', textTransform: 'uppercase',
        }}>
          {query ? `검색 결과 ${filteredFaqs.length}개` :
           activeCategory ? `${HELP_CATEGORIES.find(c => c.id === activeCategory).label} · ${filteredFaqs.length}개` :
           `자주 묻는 질문 · ${filteredFaqs.length}개`}
        </div>
        {activeCategory && !query && (
          <button onClick={() => setActiveCategory(null)} style={{
            fontSize: 11, fontWeight: 600, color: accent,
            background: 'transparent', border: 'none', padding: 0,
            cursor: 'pointer', letterSpacing: '-0.01em',
          }}>전체 보기</button>
        )}
      </div>

      <div style={{ padding: '0 22px',
        display: 'flex', flexDirection: 'column', gap: 8,
      }}>
        {filteredFaqs.length === 0 ? (
          <div style={{
            padding: '36px 18px',
            border: '1px dashed rgba(60,42,20,0.18)',
            borderRadius: 14,
            textAlign: 'center',
            color: HP.ink3, fontSize: 14, letterSpacing: '-0.01em',
          }}>찾으시는 답변이 없어요. 직접 문의해보세요.</div>
        ) : filteredFaqs.map(it => (
          <FaqItem key={it.id} item={it} accent={accent}
                   open={openId === it.id}
                   onToggle={() => setOpenId(openId === it.id ? null : it.id)} />
        ))}
      </div>

      {/* Contact CTA */}
      <div style={{ padding: '32px 22px 0' }}>
        <div style={{
          padding: '20px',
          background: `linear-gradient(135deg, ${accent}14 0%, ${accent}06 100%)`,
          border: `0.5px solid ${accent}30`,
          borderRadius: 16,
          textAlign: 'center',
        }}>
          {window.CheekPouch &&
            <div style={{ display: 'inline-block' }}>
              <window.CheekPouch count={3} accent={accent} size={56}
                                  animateOnChange={false} face="basic" />
            </div>}
          <div style={{
            marginTop: 8,
            fontSize: 14, fontWeight: 600, color: HP.ink,
            letterSpacing: '-0.01em',
          }}>찾으시는 답변이 없으세요?</div>
          <div style={{
            marginTop: 4,
            fontSize: 12, color: HP.ink2,
            letterSpacing: '-0.01em', lineHeight: 1.5,
          }}>보통 하루 안에 답변드려요</div>
          <button style={{
            marginTop: 14,
            height: 38, padding: '0 20px', borderRadius: 999,
            background: accent, color: '#FFF',
            border: 'none',
            fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
            letterSpacing: '-0.01em', cursor: 'pointer',
            WebkitTapHighlightColor: 'transparent',
          }}>직접 문의하기</button>
        </div>
      </div>
    </div>
  );
}

function FaqItem({ item, accent, open, onToggle }) {
  return (
    <div style={{
      background: HP.surface,
      border: `0.5px solid ${HP.hairline}`,
      borderRadius: 14,
      overflow: 'hidden',
    }}>
      <button onClick={onToggle} style={{
        width: '100%',
        padding: '14px 16px',
        background: 'transparent', border: 'none',
        display: 'flex', alignItems: 'center', gap: 12,
        cursor: 'pointer', fontFamily: 'inherit',
        textAlign: 'left',
        WebkitTapHighlightColor: 'transparent',
      }}>
        <span style={{
          flex: 1, minWidth: 0,
          fontSize: 14.5, fontWeight: 600, color: HP.ink,
          letterSpacing: '-0.01em', lineHeight: 1.4,
        }}>{item.q}</span>
        <span style={{
          width: 24, height: 24, borderRadius: 24,
          background: open ? accent : 'rgba(60,42,20,0.06)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
          transition: 'background 0.18s ease, transform 0.22s ease',
          transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
        }}>
          <svg width="11" height="7" viewBox="0 0 11 7" fill="none">
            <path d="M1 1l4.5 4.5L10 1" stroke={open ? '#FFF' : HP.ink2}
                  strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </span>
      </button>
      {open && (
        <div style={{
          padding: '0 16px 16px',
          fontSize: 13.5, color: HP.ink2,
          letterSpacing: '-0.01em', lineHeight: 1.6,
          animation: 'cp-fade-in 0.2s ease',
        }}>{item.a}</div>
      )}
    </div>
  );
}

Object.assign(window, { HelpScreen });
