// 돼지엄마 — Info Aggregator (정보 어그리게이터)
// 기획서 § "각종 어학연수, 유학박람회 등 모든 정보 제공" 준수
// 3개 sub-tab: 박람회·설명회 / 장학금 / 입시 일정

function InfoScreen({ t }) {
  const [tab, setTab] = useState('fairs');
  const [filter, setFilter] = useState('all');
  const [view, setView] = useState('list'); // list | calendar
  const [items, setItems] = useState(D.infoEvents);

  const toggleSubscribe = (id) => {
    setItems(items.map((it) => it.id === id ? { ...it, registered: !it.registered } : it));
  };

  // Filter logic: tab + region/topic filter
  const filtered = items.filter((it) => {
    if (it.cat !== tab) return false;
    if (filter === 'all') return true;
    return (it.tags || []).includes(filter);
  });

  // Sort by date ascending; urgent items first within same day
  const sorted = [...filtered].sort((a, b) => {
    if (a.urgent && !b.urgent) return -1;
    if (!a.urgent && b.urgent) return 1;
    return (a.daysLeft || 0) - (b.daysLeft || 0);
  });

  const subscribedCount = items.filter((it) => it.registered).length;

  return (
    <div style={{ background: 'var(--c-bg-secondary)', minHeight: '100%' }}>
      <TopBar title="정보" showSearch={true} showBell={true} badge={subscribedCount > 0 ? String(subscribedCount) : null} />

      {/* Hero — 학부모님께 추천 */}
      <div style={{ padding: '12px 16px 0' }}>
        <Card padding={14} style={{ background: 'linear-gradient(135deg, rgba(44,91,255,.06), rgba(0,200,150,.04))', border: '1px solid rgba(44,91,255,.12)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
            <Icon name="sparkle" size={16} color="var(--c-primary)" stroke={2.4} />
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--c-primary)' }}>고2 자녀 학부모님께 추천</div>
          </div>
          <div style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--c-text-primary)', textWrap: 'pretty' }}>
            <b>EducationUSA Fair (5/3 토)</b>와 <b>Common App 마감 D-30 점검회 (10/1 목)</b>이 자녀 학년에 가장 적합합니다.
          </div>
        </Card>
      </div>

      {/* Sub-tabs */}
      <div style={{ padding: '14px 16px 0', display: 'flex', gap: 6 }}>
        {D.infoTabs.map((t2) => {
          const on = tab === t2.id;
          const count = D.infoEvents.filter((it) => it.cat === t2.id).length;
          return (
            <button key={t2.id} onClick={() => { setTab(t2.id); setFilter('all'); }} style={{
              flex: 1, padding: '10px 8px', borderRadius: 10, cursor: 'pointer',
              border: `2px solid ${on ? 'var(--c-primary)' : 'var(--c-border)'}`,
              background: on ? 'rgba(44,91,255,.04)' : 'var(--c-bg-primary)',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
            }}>
              <span style={{ fontSize: 18 }}>{t2.icon}</span>
              <span style={{ fontSize: 12, fontWeight: 700, color: on ? 'var(--c-primary)' : 'var(--c-text-primary)' }}>{t2.label}</span>
              <span style={{ fontSize: 10, color: 'var(--c-text-tertiary)', fontVariantNumeric: 'tabular-nums' }}>{count}건</span>
            </button>
          );
        })}
      </div>

      {/* Filter chips */}
      <div style={{ padding: '14px 16px 0', overflowX: 'auto', whiteSpace: 'nowrap', scrollbarWidth: 'none' }}>
        <div style={{ display: 'inline-flex', gap: 6 }}>
          {D.infoFilters.map((f) => {
            const on = filter === f.id;
            return (
              <button key={f.id} onClick={() => setFilter(f.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',
              }}>{f.label}</button>
            );
          })}
        </div>
      </div>

      {/* Result count + view toggle */}
      <div style={{ padding: '14px 16px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 12, color: 'var(--c-text-sub)' }}>
          전체 <b style={{ color: 'var(--c-text-primary)', fontVariantNumeric: 'tabular-nums' }}>{sorted.length}</b>건
          {subscribedCount > 0 && <span style={{ marginLeft: 8, color: 'var(--c-primary)', fontWeight: 700 }}>· 구독 {subscribedCount}건</span>}
        </div>
        <div style={{ display: 'flex', gap: 4, padding: 2, background: 'var(--c-bg-primary)', borderRadius: 6, border: '1px solid var(--c-border)' }}>
          {['list', 'calendar'].map((v) => (
            <button key={v} onClick={() => setView(v)} style={{
              padding: '4px 10px', borderRadius: 4, border: 0, cursor: 'pointer',
              background: view === v ? 'var(--c-primary)' : 'transparent',
              color: view === v ? '#fff' : 'var(--c-text-sub)',
              fontSize: 11.5, fontWeight: 600,
            }}>{v === 'list' ? '리스트' : '캘린더'}</button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div style={{ padding: '8px 16px 100px' }}>
        {sorted.length === 0 && (
          <div style={{ padding: '60px 20px', textAlign: 'center', color: 'var(--c-text-tertiary)' }}>
            <div style={{ fontSize: 40, marginBottom: 10 }}>📭</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--c-text-sub)' }}>해당 조건의 정보가 없어요</div>
          </div>
        )}

        {view === 'list' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {sorted.map((it) => (
              <InfoCard key={it.id} it={it} onSubscribe={() => toggleSubscribe(it.id)} t={t} />
            ))}
          </div>
        )}

        {view === 'calendar' && (
          <CalendarView items={sorted} onSubscribe={toggleSubscribe} t={t} />
        )}
      </div>
    </div>
  );
}

// ───────── Info Card ─────────
function InfoCard({ it, onSubscribe, t }) {
  const isFair = it.cat === 'fair';
  const isSchol = it.cat === 'scholarship';
  const isSched = it.cat === 'schedule';

  return (
    <Card padding={14} style={{ borderLeft: `3px solid ${it.color}`, position: 'relative' }}>
      {it.urgent && (
        <div style={{ position: 'absolute', top: 8, right: 8, padding: '2px 7px', borderRadius: 4, background: 'var(--c-danger)', color: '#fff', fontSize: 10, fontWeight: 800, letterSpacing: '0.04em' }}>오늘 마감</div>
      )}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 8 }}>
        <div style={{
          width: 56, flexShrink: 0, padding: '8px 4px', borderRadius: 8,
          background: it.color + '15', textAlign: 'center',
        }}>
          <div style={{ fontSize: 18, fontWeight: 800, color: it.color, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
            {it.dateLabel.split(/[일~/(]/)[0].replace(/[월화수목금토]/g, '').trim() || it.dateLabel.match(/\d+/)?.[0]}
          </div>
          <div style={{ fontSize: 10, color: it.color, marginTop: 2, fontWeight: 700 }}>
            {it.dateLabel.includes('월') ? '월' : it.dateLabel.includes('~') ? '기간' : '일'}
          </div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginBottom: 3, flexWrap: 'wrap' }}>
            {it.region && <span style={{ fontSize: 10.5, padding: '2px 6px', borderRadius: 4, background: it.color + '15', color: it.color, fontWeight: 700 }}>{it.region}</span>}
            {isFair && (it.isOnline ? <span style={{ fontSize: 10.5, padding: '2px 6px', borderRadius: 4, background: 'rgba(0,200,150,.12)', color: 'var(--c-verified)', fontWeight: 700 }}>온라인</span> : <span style={{ fontSize: 10.5, padding: '2px 6px', borderRadius: 4, background: 'rgba(44,91,255,.10)', color: 'var(--c-primary)', fontWeight: 700 }}>오프라인</span>)}
            {it.free && <span style={{ fontSize: 10.5, padding: '2px 6px', borderRadius: 4, background: 'rgba(0,200,150,.12)', color: 'var(--c-verified)', fontWeight: 700 }}>무료</span>}
            {isSched && it.importance === 'critical' && <span style={{ fontSize: 10.5, padding: '2px 6px', borderRadius: 4, background: 'rgba(229,62,62,.10)', color: 'var(--c-danger)', fontWeight: 700 }}>★ 필수</span>}
          </div>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--c-text-primary)', lineHeight: 1.4, marginBottom: 4, letterSpacing: '-0.01em', textWrap: 'pretty' }}>{it.title}</div>
          <div style={{ fontSize: 12, color: 'var(--c-text-sub)', marginBottom: 6 }}>
            <b>{it.org}</b>
            {it.time && <span> · {it.time}</span>}
            {it.loc && <span> · {it.loc}</span>}
          </div>
          {it.preview && (
            <div style={{ fontSize: 12.5, lineHeight: 1.5, color: 'var(--c-text-sub)', marginBottom: 8, textWrap: 'pretty' }}>{it.preview}</div>
          )}
          {isSchol && (
            <div style={{ display: 'flex', gap: 12, padding: '8px 10px', background: 'var(--c-bg-secondary)', borderRadius: 6, marginBottom: 8 }}>
              <div>
                <div style={{ fontSize: 10, color: 'var(--c-text-sub)' }}>지원 금액</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-text-primary)' }}>{it.amount}</div>
              </div>
              <div>
                <div style={{ fontSize: 10, color: 'var(--c-text-sub)' }}>대상</div>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-text-primary)' }}>{it.target}</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Footer actions */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, paddingTop: 8, borderTop: '1px solid var(--c-border-soft)' }}>
        <div style={{ fontSize: 11.5, color: it.daysLeft <= 3 ? 'var(--c-danger)' : 'var(--c-text-tertiary)', fontWeight: it.daysLeft <= 3 ? 700 : 500 }}>
          {it.daysLeft === 0 ? '🔥 오늘' : `D-${it.daysLeft}`}
          {it.audience && <span style={{ marginLeft: 6, color: 'var(--c-text-tertiary)' }}>· {it.audience}</span>}
        </div>
        <button onClick={onSubscribe} style={{
          padding: '6px 12px', borderRadius: 16, cursor: 'pointer',
          border: '1px solid ' + (it.registered ? 'var(--c-verified)' : 'var(--c-border)'),
          background: it.registered ? 'rgba(0,200,150,.12)' : 'var(--c-bg-primary)',
          color: it.registered ? 'var(--c-verified)' : 'var(--c-text-primary)',
          fontSize: 12, fontWeight: 700, display: 'inline-flex', alignItems: 'center', gap: 4,
        }}>
          {it.registered ? '✓ 구독중' : '+ 알림 받기'}
        </button>
      </div>
    </Card>
  );
}

// ───────── Calendar View ─────────
function CalendarView({ items, onSubscribe, t }) {
  // Group by month
  const byMonth = {};
  items.forEach((it) => {
    const monthKey = it.date ? it.date.substring(0, 7) : 'unknown';
    if (!byMonth[monthKey]) byMonth[monthKey] = [];
    byMonth[monthKey].push(it);
  });
  const monthLabels = {
    '2026-04': '2026년 4월', '2026-05': '2026년 5월', '2026-06': '2026년 6월',
    '2026-07': '2026년 7월', '2026-08': '2026년 8월', '2026-09': '2026년 9월',
    '2026-10': '2026년 10월', '2026-11': '2026년 11월', '2026-12': '2026년 12월',
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {Object.entries(byMonth).map(([month, monthItems]) => (
        <div key={month}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 4px 8px' }}>
            <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--c-text-primary)', letterSpacing: '-0.01em' }}>
              {monthLabels[month] || month}
            </div>
            <div style={{ fontSize: 11, color: 'var(--c-text-tertiary)', fontVariantNumeric: 'tabular-nums' }}>{monthItems.length}건</div>
          </div>
          <Card padding={0}>
            {monthItems.map((it, i) => (
              <div key={it.id} onClick={() => onSubscribe(it.id)} style={{
                padding: '12px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--c-border-soft)',
                display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
              }}>
                <div style={{
                  width: 44, flexShrink: 0, padding: '6px 4px', borderRadius: 6,
                  background: it.color + '15', textAlign: 'center',
                }}>
                  <div style={{ fontSize: 14, fontWeight: 800, color: it.color, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
                    {it.date ? it.date.substring(8, 10) : '?'}
                  </div>
                  <div style={{ fontSize: 9, color: it.color, marginTop: 2, fontWeight: 700 }}>일</div>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-text-primary)', marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {it.title}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--c-text-sub)' }}>
                    {it.org}{it.loc && ` · ${it.loc}`}
                  </div>
                </div>
                {it.registered && <span style={{ color: 'var(--c-verified)', fontSize: 14 }}>✓</span>}
              </div>
            ))}
          </Card>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { InfoScreen });
