/* ============================================================
   collected.jsx — URL-mode "수집된 배너 / 패턴 묶음" 화면
   분석 결과의 [수집된 배너] 통계에서 진입. 사이트에서 수집한
   배너 전체를 보여주고, 디자인 유사도(톤·레이아웃)로 패턴 묶음을
   자동 구성한다. (이미지로 만들기의 그룹 확인과 동일한 개념)
   사용자는 묶음을 선택해 가이드로 만들 수 있다.
   ============================================================ */

// 수집 배너를 배너 타입(규격)으로 클러스터링 — 사용자 업로드 실제 배너 사용
function clusterCollected() {
  const mk = (arr, prefix) => (arr || []).map((src, i) => ({ id: prefix + '-' + i, src }));
  const groups = [
    { id: 't-h1', ref: 'guide-a', name: '상품배너 H1', desc: '776×388 · 가로형 상품 배너', banners: mk(window.H1_IMG, 'h1'), confidence: 92 },
    { id: 't-push', ref: 'guide-b', name: '앱푸시', desc: '720×380 · 앱푸시 알림 배너', banners: mk(window.PUSH_IMG, 'push'), confidence: 89 },
    { id: 't-550', ref: 'guide-c', name: '상품배너 550', desc: '550×550 · 정사각 상품 배너', banners: mk(window.G550_IMG, 'g550'), confidence: 90 }];
  return groups.filter((g) => g.banners.length > 0);
}

function _palette(grp) {
  const out = [];
  grp.banners.forEach((b) => {if (!out.includes(b.accent)) out.push(b.accent);});
  return out.slice(0, 6);
}

function CollectedBanners({ url, collected = [], onBack, onGenerate }) {
  const groups = React.useMemo(() => clusterCollected(collected), [collected]);
  const [picked, setPicked] = React.useState(() => groups.map((g) => g.id));
  const toggle = (id) =>
  setPicked((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
  const selected = groups.filter((g) => picked.includes(g.id));
  const total = collected.length;

  return (
    <div className="content"><div className="content-pad" style={{ maxWidth: 940 }}>
      <div className="page-head" style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <h1 className="page-title">수집된 배너</h1>
          <span className="pill green"><span className="pill-dot" /> {total}개 수집</span>
        </div>
        <p className="page-sub" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <S2Icon name="globe" size={14} /> https://{url} 에서 수집한 배너를 디자인 패턴으로 묶었어요. <b style={{ color: 'var(--text-2)' }}>가이드로 만들 묶음을 선택</b>하세요.
        </p>
      </div>

      <div className="grp-bar">
        <div className="grp-summary" style={{ marginLeft: 0 }}>
          <S2Icon name="sparkles" size={15} />
          <span>배너 <b>{total}개</b> · 패턴 <b style={{ color: 'var(--accent-text)' }}>{groups.length}개</b> 감지</span>
        </div>
        <div className="grp-summary" style={{ marginLeft: 'auto' }}>
          <span>선택 <b style={{ color: 'var(--accent-text)' }}>{selected.length}</b> / {groups.length}</span>
        </div>
      </div>

      <div className="grp-list">
        {groups.map((g, gi) => {
            const on = picked.includes(g.id);
            return (
              <div key={g.id}
              className={`grp-card grp-sel fade-up ${on ? 'sel' : ''}`}
              style={{ animationDelay: `${gi * 60}ms` }}
              role="button" aria-pressed={on}
              onClick={() => toggle(g.id)}>
              <div className="grp-head">
                <span className="grp-selbox">{on && <S2Icon name="check" size={13} strokeWidth={3} />}</span>
                <span className="grp-name-static">{g.name}</span>
                <span className="pill accent" style={{ flexShrink: 0 }}>신뢰도 {g.confidence}%</span>
                <span className="grp-count">{g.banners.length}개</span>
                <div className="grp-pal">
                  {_palette(g).map((c, i) =>
                    <i key={i} style={{ background: c, borderColor: c.toUpperCase() === '#FFFFFF' ? 'var(--border-strong)' : 'rgba(0,0,0,0.08)' }} />
                    )}
                </div>
              </div>
              <div className="grp-desc">{g.desc}</div>
              <div className="grp-imgs">
                {g.banners.map((b) => {
                    const ar = b.w / b.h;
                    return (
                      <div key={b.id} className="grp-thumb cb-thumb"
                      style={{ width: Math.round(76 * ar) }}
                      title={`${b.cat} · ${b.head}`}>
                      <BannerMock d={b} scale={0.32} showProduct={ar < 4} />
                    </div>);
                  })}
              </div>
            </div>);
          })}
      </div>

      <div className="grp-foot">
        <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>
          {selected.length > 0 ?
            `선택한 ${selected.length}개 묶음으로 편집 가능한 가이드를 만듭니다.` :
            '하나 이상의 묶음을 선택해 주세요.'}
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 10 }}>
          <button className="btn btn-secondary" onClick={onBack} style={{ borderRadius: "6px" }}><S2Icon name="arrowLeft" size={15} /> 분석 결과</button>
          <button className="btn btn-primary" disabled={selected.length === 0}
            onClick={() => onGenerate(selected)} style={{ borderRadius: "6px" }}>
            <S2Icon name="sparkles" size={16} /> 묶음으로 가이드 {selected.length}개 만들기
          </button>
        </div>
      </div>
    </div></div>);

}

Object.assign(window, { CollectedBanners, clusterCollected });