// Admin push-notification composer + consumer notification inbox
function OwnerNotify() {
  const [target, setTarget] = useState('ALL');
  const [channels, setChannels] = useState({ push: true, app: true, email: false });
  const [template, setTemplate] = useState('DROP');
  const templates = {
    DROP: { title: '🔥 신상품 입고 · 필드 셔츠 V2', body: '오늘 11시 전국 152개 매장 동시 릴리즈. 지금 바로 확인하세요.' },
    SALE: { title: '⚡ 겨울 자켓 -12% 한정', body: '11/22까지. 회원 전용 가격으로 찜한 상품을 지금 만나보세요.' },
    EVENT: { title: '📍 성수 플래그십 팝업 오픈', body: '12.02 – 12.08 성수동 팝업. 선착순 50명 기념품 증정.' },
  };
  const t = templates[template];
  const reach = target === 'ALL' ? 48292 : target === 'FAV' ? 6120 : target === 'SEOUL' ? 21400 : 1840;

  return (
    <div className="wu" style={{ height: '100%', background: 'var(--wu-bg)', display: 'flex', overflow: 'hidden' }}>
      <div style={{ flex: 1, padding: 28, overflow: 'auto' }} className="wu-scroll">
        <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>PARTNER / NOTIFICATIONS</div>
        <div className="display" style={{ fontSize: 32, marginTop: 4 }}>알림 발송</div>
        <div className="kr" style={{ fontSize: 13, color: 'var(--wu-mute)', marginTop: 6 }}>관리자가 신상·세일·이벤트를 회원에게 푸시·앱 내 알림으로 보냅니다.</div>

        {/* Template chooser */}
        <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', letterSpacing: '0.08em', marginTop: 24 }}>01 · 템플릿</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 8 }}>
          {[['DROP','신상'],['SALE','세일'],['EVENT','이벤트']].map(([k, l]) => (
            <button key={k} onClick={() => setTemplate(k)} style={{ background: template === k ? 'var(--wu-ink)' : 'var(--wu-paper)', color: template === k ? 'var(--wu-paper)' : 'var(--wu-ink)', border: '1px solid ' + (template === k ? 'var(--wu-ink)' : 'var(--wu-line)'), padding: '14px 12px', textAlign: 'left' }}>
              <div className="mono" style={{ fontSize: 9, opacity: 0.7 }}>{k}</div>
              <div className="kr" style={{ fontSize: 13, fontWeight: 700, marginTop: 4 }}>{l} 알림</div>
            </button>
          ))}
        </div>

        {/* Composer */}
        <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', letterSpacing: '0.08em', marginTop: 24 }}>02 · 메시지</div>
        <div style={{ background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', marginTop: 8, padding: 16 }}>
          <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>제목 · 최대 60자</div>
          <input defaultValue={t.title} key={'t-' + template} className="kr" style={{ width: '100%', border: 0, borderBottom: '1px solid var(--wu-line)', outline: 0, padding: '8px 0', fontSize: 16, fontWeight: 700, background: 'transparent', marginBottom: 16 }} />
          <div className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>본문 · 최대 140자</div>
          <textarea defaultValue={t.body} key={'b-' + template} className="kr" rows={3} style={{ width: '100%', border: 0, outline: 0, padding: '8px 0', fontSize: 14, fontFamily: 'Pretendard', lineHeight: 1.5, resize: 'none', background: 'transparent' }} />
        </div>

        {/* Target */}
        <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', letterSpacing: '0.08em', marginTop: 24 }}>03 · 수신 대상</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8, marginTop: 8 }}>
          {[['ALL','전체 회원','48,292'],['FAV','찜 등록자','6,120'],['SEOUL','서울 지역','21,400'],['OWNER','점주 전용','1,840']].map(([k, l, n]) => (
            <button key={k} onClick={() => setTarget(k)} style={{ background: target === k ? 'var(--wu-lime)' : 'var(--wu-paper)', border: '1px solid ' + (target === k ? 'var(--wu-ink)' : 'var(--wu-line)'), padding: 12, textAlign: 'left' }}>
              <div className="kr" style={{ fontSize: 12, fontWeight: 700 }}>{l}</div>
              <div className="mono display" style={{ fontSize: 18, marginTop: 4 }}>{n}</div>
            </button>
          ))}
        </div>

        {/* Channels */}
        <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', letterSpacing: '0.08em', marginTop: 24 }}>04 · 발송 채널</div>
        <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
          {[['push','📱 모바일 푸시'],['app','🔔 앱 내 알림'],['email','✉︎ 이메일']].map(([k, l]) => (
            <button key={k} onClick={() => setChannels(c => ({ ...c, [k]: !c[k] }))} style={{ padding: '10px 14px', background: channels[k] ? 'var(--wu-ink)' : 'var(--wu-paper)', color: channels[k] ? 'var(--wu-paper)' : 'var(--wu-ink)', border: '1px solid ' + (channels[k] ? 'var(--wu-ink)' : 'var(--wu-line)') }} className="kr">
              <span style={{ fontSize: 12, fontWeight: 700 }}>{channels[k] ? '✓ ' : ''}{l}</span>
            </button>
          ))}
        </div>
      </div>

      {/* Preview panel */}
      <div style={{ width: 380, background: 'var(--wu-ink)', color: 'var(--wu-paper)', padding: 24, display: 'flex', flexDirection: 'column', flexShrink: 0 }}>
        <div className="mono" style={{ fontSize: 10, color: 'var(--wu-lime)' }}>● LIVE PREVIEW</div>
        <div className="display" style={{ fontSize: 22, marginTop: 4, color: 'var(--wu-paper)' }}>PUSH · LOCK SCREEN</div>

        {/* Phone lockscreen mock */}
        <div style={{ marginTop: 18, background: 'linear-gradient(180deg, #2A2A26, #0E0E0C)', borderRadius: 18, padding: 16, border: '1px solid #1A1A17' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', color: 'rgba(255,255,255,0.7)' }}>
            <span className="mono" style={{ fontSize: 11 }}>14:02</span>
            <span className="mono" style={{ fontSize: 11 }}>● 화 · 11.15</span>
          </div>
          <div style={{ background: 'rgba(255,255,255,0.08)', backdropFilter: 'blur(10px)', borderRadius: 14, padding: 12, marginTop: 40, border: '1px solid rgba(255,255,255,0.1)' }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
              <div style={{ width: 28, height: 28, borderRadius: 6, background: 'var(--wu-lime)', color: 'var(--wu-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Archivo Black', fontSize: 12, flexShrink: 0 }}>w</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.6)', letterSpacing: '0.06em' }}>WORKUP</span>
                  <span className="mono" style={{ fontSize: 9, color: 'rgba(255,255,255,0.5)' }}>지금</span>
                </div>
                <div className="kr" style={{ fontSize: 13, fontWeight: 700, marginTop: 4, lineHeight: 1.3 }}>{t.title}</div>
                <div className="kr" style={{ fontSize: 11, opacity: 0.75, marginTop: 4, lineHeight: 1.4 }}>{t.body}</div>
              </div>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 20, padding: 14, background: '#1A1A17', borderLeft: '3px solid var(--wu-lime)' }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>REACH ESTIMATE</div>
          <div className="display" style={{ fontSize: 30, color: 'var(--wu-lime)', marginTop: 4 }}>{reach.toLocaleString('ko-KR')}</div>
          <div className="kr mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginTop: 4 }}>예상 오픈율 24% · 약 {Math.round(reach * 0.24).toLocaleString('ko-KR')}회 오픈</div>
        </div>

        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="wu-btn ghost block" style={{ borderColor: 'var(--wu-paper)', color: 'var(--wu-paper)', fontSize: 11 }}>예약 발송</button>
          <button className="wu-btn lime block" style={{ fontSize: 11 }}>🚀 지금 발송</button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────
// Consumer NOTIFICATION INBOX (mobile) — Firestore 연동
// ────────────────────────────────────────────────────
function ConsumerNotifications({ variant = 'pill' }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pushStatus, setPushStatus] = useState('unknown'); // granted, denied, default, unsupported
  const [detail, setDetail] = useState(null); // 공지 상세 보기
  const readKey = 'wu-read-notices';

  // 읽음 상태 관리 (localStorage)
  const getReadIds = () => {
    try { return JSON.parse(localStorage.getItem(readKey) || '[]'); } catch(e) { return []; }
  };
  const markAllRead = () => {
    const ids = items.map(n => n.id);
    localStorage.setItem(readKey, JSON.stringify(ids));
    setItems([...items]); // force re-render
  };

  // 알림 권한 확인
  useEffect(() => {
    if (!('Notification' in window)) { setPushStatus('unsupported'); return; }
    setPushStatus(Notification.permission);
  }, []);

  // 알림 권한 요청
  const requestPush = async () => {
    if (!('Notification' in window)) return;
    const perm = await Notification.requestPermission();
    setPushStatus(perm);
  };

  // 공지 로드 — 역할별 필터링
  useEffect(() => {
    if (typeof getNotices === 'function') {
      getNotices().then(list => {
        const user = typeof getAuth === 'function' ? getAuth() : null;
        const role = user ? user.role : 'consumer';
        const filtered = list.filter(n => {
          if (!n.audience || n.audience === '전체') return true;
          if (n.audience === '점주만' && role === 'owner') return true;
          if (n.audience === '회원만' && role === 'consumer') return true;
          if (role === 'admin') return true; // 관리자는 전부 표시
          return false;
        });
        setItems(filtered);
        setLoading(false);
      }).catch(() => setLoading(false));
    } else { setLoading(false); }
  }, []);

  const readIds = getReadIds();
  const unreadCount = items.filter(n => !readIds.includes(n.id)).length;

  const timeAgo = (iso) => {
    if (!iso) return '';
    const diff = Date.now() - new Date(iso).getTime();
    const m = Math.floor(diff / 60000);
    if (m < 1) return '방금';
    if (m < 60) return m + '분 전';
    const h = Math.floor(m / 60);
    if (h < 24) return h + '시간 전';
    const d = Math.floor(h / 24);
    if (d < 7) return d + '일 전';
    return new Date(iso).toLocaleDateString('ko-KR');
  };

  const tagColor = (tag) => {
    if (tag === '긴급' || tag === '필독') return 'var(--wu-orange)';
    if (tag === '신상') return 'var(--wu-lime)';
    if (tag === '이벤트') return '#4A9EFF';
    return 'var(--wu-ink)';
  };

  const tagBg = (tag) => {
    if (tag === '긴급') return '#FF5A1F';
    if (tag === '신상') return '#1F2A1F';
    if (tag === '이벤트') return '#2A3A5A';
    if (tag === '운영') return '#3A3A36';
    return '#0E0E0C';
  };

  // 공지 상세 클릭
  const openDetail = (n) => {
    const ids = getReadIds();
    if (!ids.includes(n.id)) { ids.push(n.id); localStorage.setItem(readKey, JSON.stringify(ids)); setItems([...items]); }
    setDetail(n);
  };

  // ─── 상세 보기 화면 ───
  if (detail) {
    const n = detail;
    const detailDate = n.createdAt ? new Date(n.createdAt).toLocaleDateString('ko-KR', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'short' }) : '';
    return (
      <div className="wu wu-scroll" style={{ height: '100%', overflow: 'auto', background: 'var(--wu-bg)', paddingBottom: 70 }}>
        {/* 상단 바 */}
        <div style={{ position: 'sticky', top: 0, zIndex: 30, background: 'var(--wu-bg)', padding: 'calc(env(safe-area-inset-top, 20px) + 8px) 16px 10px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--wu-line)' }}>
          <button onClick={() => setDetail(null)} style={{ width: 36, height: 36, borderRadius: 999, background: '#fff', border: '1px solid var(--wu-line)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', fontSize: 16, flexShrink: 0 }}>←</button>
          <div className="kr" style={{ fontSize: 15, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>공지사항</div>
        </div>

        {/* 헤더 영역 */}
        <div style={{ padding: '24px 20px 16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <span style={{ padding: '4px 10px', borderRadius: 999, fontSize: 11, fontWeight: 700, fontFamily: 'var(--wu-mono)', background: tagBg(n.tag), color: '#fff' }}>{n.tag || '공지'}</span>
            {n.audience && n.audience !== '전체' && (
              <span style={{ padding: '4px 10px', borderRadius: 999, fontSize: 10, fontWeight: 600, fontFamily: 'Pretendard', background: 'var(--wu-line)', color: 'var(--wu-ink)' }}>{n.audience}</span>
            )}
          </div>
          <div className="kr" style={{ fontSize: 20, fontWeight: 800, lineHeight: 1.35, wordBreak: 'keep-all' }}>{n.title}</div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 10 }}>{detailDate}</div>
        </div>

        <div style={{ height: 1, background: 'var(--wu-line)', margin: '0 20px' }} />

        {/* 본문 */}
        <div style={{ padding: '20px 20px 24px' }}>
          <div className="kr" style={{ fontSize: 15, lineHeight: 1.75, color: 'var(--wu-ink)', whiteSpace: 'pre-wrap', wordBreak: 'keep-all' }}>{n.body || ''}</div>
        </div>

        {/* 이미지 갤러리 */}
        {n.photos && n.photos.length > 0 && (
          <div style={{ padding: '0 20px 24px' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {n.photos.map((url, i) => (
                <img key={i} src={url} alt="" style={{ width: '100%', borderRadius: 8, border: '1px solid var(--wu-line)', objectFit: 'cover' }} />
              ))}
            </div>
          </div>
        )}

        {/* 하단 이전 목록으로 버튼 */}
        <div style={{ padding: '8px 20px 24px', textAlign: 'center' }}>
          <button onClick={() => setDetail(null)} className="kr" style={{ padding: '12px 32px', background: 'var(--wu-ink)', color: 'var(--wu-paper)', border: 'none', borderRadius: 6, fontSize: 13, fontWeight: 700, cursor: 'pointer' }}>← 목록으로</button>
        </div>
      </div>
    );
  }

  return (
    <div className="wu wu-scroll" style={{ height: '100%', overflow: 'auto', background: 'var(--wu-bg)', paddingBottom: 70 }}>
      <div style={{ padding: 'calc(env(safe-area-inset-top, 20px) + 12px) 16px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>INBOX · {unreadCount > 0 ? unreadCount + ' NEW' : 'ALL READ'}</div>
          <div className="display" style={{ fontSize: 32, marginTop: 4 }}>ALERTS</div>
        </div>
        {unreadCount > 0 && <button onClick={markAllRead} className="mono" style={{ fontSize: 11, textDecoration: 'underline', color: 'var(--wu-mute)', background: 'none', border: 'none', cursor: 'pointer' }}>모두 읽음</button>}
      </div>

      {/* 푸시 알림 권한 배너 */}
      {pushStatus === 'default' && (
        <div style={{ margin: '0 16px 12px', padding: '12px 16px', background: 'var(--wu-ink)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <div className="kr" style={{ fontSize: 13, fontWeight: 700, color: 'var(--wu-paper)' }}>알림을 받으시겠습니까?</div>
            <div className="kr" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 2 }}>새 공지·이벤트를 푸시로 알려드립니다</div>
          </div>
          <button onClick={requestPush} className="wu-btn lime" style={{ fontSize: 11, padding: '8px 14px', flexShrink: 0 }}>허용</button>
        </div>
      )}

      <div style={{ padding: '0 16px' }}>
        {loading ? (
          <div className="kr" style={{ textAlign: 'center', padding: 40, color: 'var(--wu-mute)' }}>로딩 중...</div>
        ) : items.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 60 }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>🔔</div>
            <div className="kr" style={{ fontSize: 14, color: 'var(--wu-mute)' }}>아직 알림이 없습니다</div>
          </div>
        ) : (
          items.map(n => {
            const unread = !readIds.includes(n.id);
            return (
              <div key={n.id} onClick={() => openDetail(n)} style={{ display: 'flex', gap: 12, padding: '14px 12px', background: unread ? 'var(--wu-paper)' : 'transparent', borderLeft: '3px solid ' + (unread ? 'var(--wu-lime)' : 'transparent'), borderBottom: '1px solid var(--wu-line)', cursor: 'pointer', transition: 'background 0.15s' }}>
                <div style={{ width: 40, height: 40, flexShrink: 0, borderRadius: 8, background: `linear-gradient(160deg, ${tagBg(n.tag)}88, ${tagBg(n.tag)})`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <span style={{ fontFamily: 'Archivo Black', fontSize: 12, color: '#fff', opacity: 0.9 }}>{(n.tag || 'N')[0]}</span>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span className="mono" style={{ fontSize: 9, fontWeight: 700, color: tagColor(n.tag), letterSpacing: '0.08em' }}>● {n.tag || '공지'}</span>
                    <span className="mono" style={{ fontSize: 9, color: 'var(--wu-mute)' }}>{timeAgo(n.createdAt)}</span>
                  </div>
                  <div className="kr" style={{ fontSize: 13, fontWeight: 700, marginTop: 4, lineHeight: 1.35 }}>{n.title}</div>
                  {n.body && <div className="kr" style={{ fontSize: 11, color: 'var(--wu-mute)', marginTop: 3, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', whiteSpace: 'normal' }}>{n.body}</div>}
                  {n.photos && n.photos.length > 0 && (
                    <div style={{ display: 'flex', gap: 4, marginTop: 6 }}>
                      {n.photos.slice(0, 3).map((url, i) => (
                        <img key={i} src={url} alt="" style={{ width: 52, height: 52, objectFit: 'cover', borderRadius: 4, border: '1px solid var(--wu-line)', flexShrink: 0 }} />
                      ))}
                      {n.photos.length > 3 && <div style={{ width: 52, height: 52, borderRadius: 4, background: 'var(--wu-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><span className="mono" style={{ fontSize: 11, color: '#fff' }}>+{n.photos.length - 3}</span></div>}
                    </div>
                  )}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', flexShrink: 0 }}>
                  <svg width="14" height="14" viewBox="0 0 20 20" fill="none" stroke="var(--wu-mute)" strokeWidth="2"><path d="M7 4l6 6-6 6"/></svg>
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}

Object.assign(window, { OwnerNotify, ConsumerNotifications });
