// 돼지엄마 — 평가 비교 도구 (Institution Comparison)
// 기획서 § "비교 도구 — 유학원 A vs B, 학원 A vs B 1:1 비교 (Job Planet에는 없는 기능)"

function CompareScreen({ onBack, t }) {
  // Initialize: pre-pick 강남○○유학원 (rv1) on left, allow user to pick right
  const [leftId, setLeftId] = useState('rv1');
  const [rightId, setRightId] = useState('rv4');
  const [pickerSide, setPickerSide] = useState(null); // 'left' | 'right' | null

  const findInst = (id) => D.reviewSearch.find((r) => r.id === id);
  const left = findInst(leftId);
  const right = findInst(rightId);

  // Use full reviewDetail for left (only one detailed mock available)
  const leftDetail = leftId === 'rv1' ? D.reviewDetail : null;

  if (pickerSide) {
    return (
      <PickerOverlay
        title={pickerSide === 'left' ? '비교할 기관 1 선택' : '비교할 기관 2 선택'}
        excludeId={pickerSide === 'left' ? rightId : leftId}
        onPick={(id) => {
          if (pickerSide === 'left') setLeftId(id); else setRightId(id);
          setPickerSide(null);
        }}
        onCancel={() => setPickerSide(null)}
      />
    );
  }

  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <TopBar showBack onBack={onBack} title="기관 비교" showSearch={false} showBell={false} />

      <div style={{ padding: '12px 16px 0' }}>
        <Card padding={12} style={{ background: 'rgba(44,91,255,.06)', border: '1px solid rgba(44,91,255,.18)' }}>
          <div style={{ fontSize: 12.5, lineHeight: 1.55, color: 'var(--c-text-primary)', textWrap: 'pretty' }}>
            🤖 <b>두 기관을 1:1 비교</b>합니다. 학부모 평가·가격·합격 사례를 한눈에. (다른 평가 사이트에는 없는 돼지엄마 차별 기능)
          </div>
        </Card>
      </div>

      {/* Header — 두 기관 선택 */}
      <div style={{ padding: '12px 16px 0' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 32px 1fr', gap: 8, alignItems: 'stretch' }}>
          <InstitutionCardSlot inst={left} onPickAnother={() => setPickerSide('left')} side="A" color="var(--c-primary)" />
          <div style={{ display: 'grid', placeItems: 'center', fontSize: 18, fontWeight: 800, color: 'var(--c-text-tertiary)' }}>VS</div>
          <InstitutionCardSlot inst={right} onPickAnother={() => setPickerSide('right')} side="B" color="var(--c-secondary)" />
        </div>
      </div>

      {/* Comparison rows */}
      <div style={{ padding: '12px 16px 100px', display: 'flex', flexDirection: 'column', gap: 10 }}>

        {/* 종합 평점 */}
        <CompareRow title="⭐ 종합 평점">
          <CompareCell value={`${left.rating}`} sub={`(${left.count}건)`} highlight={left.rating > right.rating} />
          <CompareCell value={`${right.rating}`} sub={`(${right.count}건)`} highlight={right.rating > left.rating} />
        </CompareRow>

        {/* 가격대 */}
        <CompareRow title="💰 가격대">
          <CompareCell value={left.priceRange || '-'} sub="평균" small />
          <CompareCell value={right.priceRange || '-'} sub="평균" small />
        </CompareRow>

        {/* 학원가 */}
        <CompareRow title="📍 학원가">
          <CompareCell value={left.loc} small />
          <CompareCell value={right.loc} small />
        </CompareRow>

        {/* 카테고리 */}
        <CompareRow title="🏷 카테고리">
          <CompareCell value={left.catLabel || left.cat} small />
          <CompareCell value={right.catLabel || right.cat} small />
        </CompareRow>

        {/* 세부 평점 (left만 detailed) */}
        {leftDetail && (
          <CompareRow title="📊 세부 평점 비교">
            <SubRatingBars detail={leftDetail.breakdown} />
            <SubRatingBars detail={{ price: 4.0, counsel: 4.4, accuracy: 4.3, result: 4.5 }} dim />
          </CompareRow>
        )}

        {/* AI 요약 — 추천 대상 비교 */}
        {leftDetail?.aiSummary && (
          <Card padding={14} style={{ borderLeft: '3px solid var(--c-primary)' }}>
            <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--c-text-primary)', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 4 }}>
              🤖 AI 추천 대상 비교
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <div>
                <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--c-primary)', marginBottom: 6 }}>{left.name}</div>
                <ul style={{ margin: 0, padding: 0, listStyle: 'none', fontSize: 12, lineHeight: 1.5, color: 'var(--c-text-primary)' }}>
                  {leftDetail.aiSummary.recommendedFor.map((it, i) => (
                    <li key={i} style={{ display: 'flex', gap: 4, marginBottom: 4 }}>
                      <span style={{ color: 'var(--c-primary)' }}>•</span>
                      <span style={{ flex: 1, textWrap: 'pretty' }}>{it}</span>
                    </li>
                  ))}
                </ul>
              </div>
              <div>
                <div style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--c-secondary)', marginBottom: 6 }}>{right.name}</div>
                <ul style={{ margin: 0, padding: 0, listStyle: 'none', fontSize: 12, lineHeight: 1.5, color: 'var(--c-text-primary)' }}>
                  <li style={{ display: 'flex', gap: 4, marginBottom: 4 }}>
                    <span style={{ color: 'var(--c-secondary)' }}>•</span>
                    <span style={{ flex: 1 }}>내신 2.0대 상위권 자녀</span>
                  </li>
                  <li style={{ display: 'flex', gap: 4, marginBottom: 4 }}>
                    <span style={{ color: 'var(--c-secondary)' }}>•</span>
                    <span style={{ flex: 1 }}>국내 명문대 수학 집중</span>
                  </li>
                  <li style={{ display: 'flex', gap: 4 }}>
                    <span style={{ color: 'var(--c-secondary)' }}>•</span>
                    <span style={{ flex: 1 }}>{right.region === 'gangnam' ? '강남·대치' : '지역'} 거주 학부모</span>
                  </li>
                </ul>
              </div>
            </div>
          </Card>
        )}

        {/* AI 종합 — 어느 쪽이 더 적합? */}
        <Card padding={14} style={{ background: 'linear-gradient(135deg, rgba(44,91,255,.04), rgba(0,200,150,.03))', border: '1px solid rgba(44,91,255,.12)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <Icon name="sparkle" size={16} color="var(--c-primary)" stroke={2.4} />
            <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--c-text-primary)' }}>AI 종합 의견</div>
          </div>
          <div style={{ fontSize: 13, lineHeight: 1.65, color: 'var(--c-text-primary)', textWrap: 'pretty', marginBottom: 12 }}>
            <b style={{ color: 'var(--c-primary)' }}>{left.name}</b>은 <b>해외 학부 진학</b>이 목표라면 강점이 큽니다 (가격 대비 합격 사례 多). 반면 <b style={{ color: 'var(--c-secondary)' }}>{right.name}</b>은 <b>국내 입시·내신 관리</b>에 더 적합합니다.
            <br /><br />
            <b>자녀의 진로</b>가 결정 기준입니다 — 미국 학부 = A, 의대·SKY = B.
          </div>
          <div style={{ fontSize: 11, color: 'var(--c-text-tertiary)' }}>학부모 평가 {left.count + right.count}건 + 합격 데이터 기반 · 매주 갱신</div>
        </Card>

        {/* CTA */}
        <Button kind="primary" full onClick={onBack} leading={<Icon name="arrowR" size={16} stroke={2.4} />}>비교 결과 저장하고 나가기</Button>
      </div>
    </div>
  );
}

// ───────── Helpers ─────────

function InstitutionCardSlot({ inst, onPickAnother, side, color }) {
  if (!inst) {
    return (
      <button onClick={onPickAnother} style={{
        padding: '20px 14px', borderRadius: 12, border: '2px dashed var(--c-border)', background: 'var(--c-bg-primary)',
        cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      }}>
        <Icon name="plus" size={20} color="var(--c-text-tertiary)" stroke={2.2} />
        <span style={{ fontSize: 12, color: 'var(--c-text-sub)', fontWeight: 600 }}>기관 {side} 선택</span>
      </button>
    );
  }
  return (
    <Card padding={12} style={{ borderTop: `3px solid ${color}`, position: 'relative' }}>
      <div style={{ position: 'absolute', top: 8, right: 8, width: 22, height: 22, borderRadius: 11, background: color, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 800 }}>{side}</div>
      <div style={{ width: 36, height: 36, borderRadius: 8, background: 'var(--c-bg-secondary)', display: 'grid', placeItems: 'center', fontSize: 16, marginBottom: 8 }}>🏢</div>
      <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--c-text-primary)', lineHeight: 1.3, marginBottom: 4, paddingRight: 24, textWrap: 'pretty' }}>{inst.name}</div>
      <div style={{ fontSize: 11, color: 'var(--c-text-sub)', marginBottom: 8 }}>{inst.catLabel || inst.cat} · {inst.loc.split(' ')[1] || inst.loc}</div>
      <button onClick={onPickAnother} style={{ width: '100%', padding: '6px 8px', borderRadius: 6, border: '1px solid var(--c-border)', background: 'transparent', cursor: 'pointer', fontSize: 11, color: 'var(--c-text-sub)', fontWeight: 600 }}>다른 기관 선택</button>
    </Card>
  );
}

function CompareRow({ title, children }) {
  return (
    <div>
      <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--c-text-sub)', marginBottom: 6, padding: '0 4px' }}>{title}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {children}
      </div>
    </div>
  );
}

function CompareCell({ value, sub, highlight, small }) {
  return (
    <Card padding={12} style={{
      textAlign: 'center',
      ...(highlight ? { background: 'rgba(255,184,0,.08)', border: '1px solid rgba(255,184,0,.30)' } : {}),
    }}>
      <div style={{ fontSize: small ? 13 : 22, fontWeight: 800, color: highlight ? '#A77A00' : 'var(--c-text-primary)', lineHeight: 1.2, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>
        {value}
        {highlight && <span style={{ marginLeft: 4, fontSize: 11 }}>👑</span>}
      </div>
      {sub && <div style={{ fontSize: 10.5, color: 'var(--c-text-tertiary)', marginTop: 3 }}>{sub}</div>}
    </Card>
  );
}

function SubRatingBars({ detail, dim }) {
  const labels = { price: '가격', counsel: '상담', accuracy: '정확성', result: '결과' };
  return (
    <Card padding={12}>
      {Object.entries(detail).map(([k, v]) => (
        <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, marginBottom: 4 }}>
          <div style={{ width: 32, color: 'var(--c-text-sub)' }}>{labels[k]}</div>
          <div style={{ flex: 1, height: 4, borderRadius: 2, background: 'var(--c-border)', overflow: 'hidden' }}>
            <div style={{ width: `${v / 5 * 100}%`, height: '100%', background: dim ? 'var(--c-secondary)' : 'var(--c-primary)' }} />
          </div>
          <div style={{ width: 22, textAlign: 'right', fontWeight: 700, color: 'var(--c-text-primary)', fontVariantNumeric: 'tabular-nums' }}>{v}</div>
        </div>
      ))}
    </Card>
  );
}

function PickerOverlay({ title, excludeId, onPick, onCancel }) {
  const [q, setQ] = useState('');
  const [cat, setCat] = useState('all');
  const list = D.reviewSearch.filter((r) => {
    if (r.id === excludeId) return false;
    if (cat !== 'all' && r.cat !== cat) return false;
    if (q && !r.name.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <TopBar showBack onBack={onCancel} title={title} showSearch={false} showBell={false} />
      <div style={{ padding: 16, position: 'sticky', top: 52, background: 'var(--c-bg-secondary)', zIndex: 9 }}>
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="기관명 검색"
          style={{ width: '100%', height: 44, padding: '0 14px', borderRadius: 10, border: '1px solid var(--c-border)', background: 'var(--c-bg-primary)', fontSize: 14, outline: 'none' }} />
        <div style={{ display: 'flex', gap: 6, marginTop: 10, overflowX: 'auto', scrollbarWidth: 'none' }}>
          {(D.reviewCategories || []).map((c) => {
            const on = cat === c.id;
            return (
              <button key={c.id} onClick={() => setCat(c.id)} style={{
                padding: '6px 12px', borderRadius: 16, fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
                border: '1px solid ' + (on ? 'var(--c-primary)' : 'var(--c-border)'),
                background: on ? 'var(--c-primary)' : 'var(--c-bg-primary)',
                color: on ? '#fff' : 'var(--c-text-sub)', whiteSpace: 'nowrap',
              }}>{c.label}</button>
            );
          })}
        </div>
      </div>
      <div style={{ padding: '0 16px 100px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {list.map((r) => (
          <Card key={r.id} padding={14} onClick={() => onPick(r.id)}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ width: 40, height: 40, borderRadius: 8, background: 'var(--c-bg-secondary)', display: 'grid', placeItems: 'center', fontSize: 18 }}>🏢</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--c-text-primary)' }}>{r.name}</div>
                <div style={{ fontSize: 11.5, color: 'var(--c-text-sub)', marginTop: 2 }}>{r.catLabel || r.cat} · {r.loc} · ★ {r.rating}</div>
              </div>
              <Icon name="chevR" size={16} color="var(--c-text-tertiary)" />
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CompareScreen });
