// Profile (내정보) + Notifications · night theme
// Reuses MainAvatar + AVATAR_STAGES from home-night.jsx (loaded earlier).

const { useState: pfState } = React;

// =================== Profile / 내정보 ===================
function ProfileScreen({ onTab, onAbout, onGrowth, onHistory, onLifeVerse, onNotifications, onSettings, onLogout, currentXP = 220 }) {
  const stages = window.AVATAR_STAGES || [];
  const [confirmLogout, setConfirmLogout] = pfState(false);
  const stageData = stages.find(s => currentXP >= s.xpFrom && currentXP <= s.xpTo) || stages[0];
  const nextStage = stages.find(s => s.stage === (stageData?.stage || 1) + 1);
  const fromXP = stageData?.xpFrom ?? 0;
  const toXP = nextStage ? nextStage.xpFrom : (stageData?.xpTo ?? 100);
  const progress = Math.min(1, (currentXP - fromXP) / (toXP - fromXP));

  const STATS = [
    { icon: '📓', num: 42, label: '기도 기록' },
    { icon: '🔥', num: 7,  label: '연속 출석' },
    { icon: '💬', num: 18, label: '멘토 대화' },
    { icon: '💛', num: 24, label: '받은 응원' },
  ];

  const MENU = [
    { id: 'growth',   icon: '🌱', label: '내 캐릭터 성장',  desc: `${stageData?.name || ''} · ${currentXP} XP` },
    { id: 'lifeverse',icon: '📖', label: '나의 인생 구절',   desc: '시간순 구절 기록 보기' },
    { id: 'history',  icon: '💬', label: '멘토 대화 기록',   desc: '지난 대화 이어보기' },
    { id: 'notif',    icon: '🔔', label: '알림 설정',        desc: '기도 리마인더 · 멘토 응답' },
    { id: 'about',    icon: '⛪', label: '중문교회 소개',     desc: 'About · 교회 정보' },
    { id: 'theme',    icon: '🎨', label: '화면 테마',         desc: '밝게 / 어둡게' },
    { id: 'backup',   icon: '☁️', label: '기록 백업',         desc: '클라우드 동기화' },
    { id: 'help',     icon: '❓', label: '도움말 · 문의',     desc: 'support@aimen.app' },
  ];

  return (
    <>
      <NightSky showMoon={false} />
      <div className="welcome-shell profile-screen">
        <div className="home-night-topbar">
          <div className="hnt-brand"><span>내정보</span></div>
          <button className="hnt-icon" aria-label="알림" onClick={onNotifications}>
            <Icon name="bell" />
          </button>
        </div>

        {/* Profile header */}
        <div className="pf-header">
          <div className="pf-avatar">
            <div className="ma-floating">
              <MainAvatar stage={stageData?.stage || 1} size={96} />
            </div>
          </div>
          <div className="pf-meta">
            <div className="pf-name">은혜님</div>
            <div className="pf-email">grace@example.com</div>
            <div className="pf-badge">{stageData?.emoji} Lv.{stageData?.stage} · {stageData?.name}</div>
          </div>
        </div>

        {/* Level bar */}
        <div className="pf-level">
          <div className="pf-level-top">
            <span className="pf-level-name">{stageData?.emoji} {stageData?.name}</span>
            <span className="pf-level-xp"><strong>{currentXP}</strong> XP</span>
          </div>
          <div className="pf-bar">
            <div className="pf-fill" style={{ width: `${progress * 100}%` }} />
          </div>
          <div className="pf-next">
            {nextStage
              ? <>다음 단계 <strong>{nextStage.name}</strong>까지 {toXP - currentXP} XP</>
              : <>최종 단계 도달 · 동행자</>}
          </div>
        </div>

        {/* Stats grid */}
        <div className="pf-stats">
          {STATS.map((s, i) => (
            <div key={i} className="pf-stat">
              <div className="pfs-icon">{s.icon}</div>
              <div className="pfs-num">{s.num}</div>
              <div className="pfs-label">{s.label}</div>
            </div>
          ))}
        </div>

        {/* Menu list */}
        <div className="pf-menu">
          {MENU.map(m => (
            <button
              key={m.id}
              className="pf-menu-item"
              onClick={() => {
                if (m.id === 'about') onAbout && onAbout();
                else if (m.id === 'growth') onGrowth && onGrowth();
                else if (m.id === 'lifeverse') onLifeVerse && onLifeVerse();
                else if (m.id === 'history') onHistory && onHistory();
                else onSettings && onSettings(m.id);
              }}
            >
              <span className="pfm-icon">{m.icon}</span>
              <span className="pfm-body">
                <span className="pfm-label">{m.label}</span>
                <span className="pfm-desc">{m.desc}</span>
              </span>
              <span className="pfm-chev"><Icon name="chev-right" size={18} stroke={2} /></span>
            </button>
          ))}
        </div>

        <button className="pf-logout" onClick={() => setConfirmLogout(true)}>로그아웃</button>

        <ChurchFooter inverse />
      </div>

      {confirmLogout && (
        <div className="confirm-scrim" onClick={() => setConfirmLogout(false)}>
          <div className="confirm-sheet" onClick={e => e.stopPropagation()}>
            <div className="cs-title">로그아웃 할까요?</div>
            <div className="cs-desc">다시 로그인하면 기록과 캐릭터는 그대로 있어요.</div>
            <div className="cs-actions">
              <button className="cs-btn ghost" onClick={() => setConfirmLogout(false)}>취소</button>
              <button className="cs-btn danger" onClick={() => { setConfirmLogout(false); onLogout && onLogout(); }}>로그아웃</button>
            </div>
          </div>
        </div>
      )}

      <BottomTabs active="me" themeKey="sky" onTab={onTab} />
    </>
  );
}

// =================== Notifications ===================
const NOTIF_DATA = [
  { id: 'n1', icon: '📖', accent: '#4A9CD8', title: '아브라함 멘토의 답장', body: '오늘 나눈 기도에 멘토가 응답했어요.', time: '5분 전', unread: true },
  { id: 'n2', icon: '💛', accent: '#E0517E', title: '응원을 받았어요', body: '익명의 동행님이 회원님의 간증에 응원을 보냈어요.', time: '1시간 전', unread: true },
  { id: 'n3', icon: '🔥', accent: '#F0CF6A', title: '7일 연속 출석!', body: '꾸준한 동행에 +25 XP를 드렸어요.', time: '3시간 전', unread: false },
  { id: 'n4', icon: '🌱', accent: '#58CC02', title: '곧 레벨업이에요', body: '기도나무까지 80 XP 남았어요. 오늘도 한 줄 기록해보세요.', time: '오늘', unread: false },
  { id: 'n5', icon: '💬', accent: '#4A9CD8', title: '새 댓글', body: '회원님의 묵상 글에 새 댓글이 달렸어요.', time: '어제', unread: false },
  { id: 'n6', icon: '⛪', accent: '#C99A2E', title: '중문교회 주일 안내', body: '이번 주 주일예배는 오전 9시·11시·오후 2시입니다.', time: '2일 전', unread: false },
];

function NotificationsScreen({ onBack, empty = false }) {
  const [notifs, setNotifs] = pfState(empty ? [] : NOTIF_DATA);
  const markAllRead = () => setNotifs(prev => prev.map(n => ({ ...n, unread: false })));

  return (
    <>
      <NightSky showMoon={false} />
      <div className="welcome-shell notif-screen">
        <div className="home-night-topbar">
          <button className="hnt-icon" aria-label="Back" onClick={onBack}><Icon name="chev-left" /></button>
          <div className="hnt-brand"><span>알림</span></div>
          {notifs.length > 0
            ? <button className="notif-readall" onClick={markAllRead}>모두 읽음</button>
            : <div style={{ width: 34 }} />}
        </div>

        {notifs.length === 0 ? (
          <div className="empty-state dark">
            <div className="es-art" aria-hidden="true">🔔</div>
            <div className="es-title">아직 알림이 없어요</div>
            <div className="es-desc">멘토의 답장, 받은 응원, 출석 보상 소식이<br/>이곳에 모여요.</div>
          </div>
        ) : (
        <div className="notif-list">
          {notifs.map(n => (
            <button
              key={n.id}
              className={`notif-item ${n.unread ? 'unread' : ''}`}
              onClick={() => setNotifs(prev => prev.map(x => x.id === n.id ? { ...x, unread: false } : x))}
            >
              <span className="notif-icon" style={{ background: `${n.accent}22`, border: `1px solid ${n.accent}66` }}>
                {n.icon}
              </span>
              <span className="notif-body">
                <span className="notif-title">
                  {n.title}
                  {n.unread && <span className="notif-dot" />}
                </span>
                <span className="notif-text">{n.body}</span>
                <span className="notif-time">{n.time}</span>
              </span>
            </button>
          ))}
        </div>
        )}
      </div>
    </>
  );
}

window.ProfileScreen = ProfileScreen;
window.NotificationsScreen = NotificationsScreen;

// =================== Settings detail (알림·테마·백업·도움말) ===================
function Toggle({ on, onChange }) {
  return (
    <button className={`set-switch ${on ? 'on' : ''}`} onClick={() => onChange(!on)} aria-pressed={on}>
      <span className="set-knob" />
    </button>
  );
}

function SettingsScreen({ section = 'notif', onBack }) {
  const TITLES = { notif: '알림 설정', theme: '화면 테마', backup: '기록 백업', help: '도움말 · 문의' };

  // notif toggles
  const [reminder, setReminder] = pfState(true);
  const [mentorReply, setMentorReply] = pfState(true);
  const [cheer, setCheer] = pfState(true);
  const [church, setChurch] = pfState(false);
  const [reminderTime, setReminderTime] = pfState('오전 6:30');
  // theme
  const [theme, setTheme] = pfState('dark');
  // backup
  const [sync, setSync] = pfState(true);
  const [backedUp, setBackedUp] = pfState(false);

  return (
    <>
      <NightSky showMoon={false} />
      <div className="welcome-shell settings-screen">
        <div className="home-night-topbar">
          <button className="hnt-icon" aria-label="Back" onClick={onBack}><Icon name="chev-left" /></button>
          <div className="hnt-brand"><span>{TITLES[section]}</span></div>
          <div style={{ width: 34 }} />
        </div>

        <div className="set-body">
          {section === 'notif' && (
            <>
              <div className="set-group">
                <div className="set-row">
                  <div className="set-rl">
                    <div className="set-rt">기도 리마인더</div>
                    <div className="set-rd">매일 정해진 시간에 알려드려요</div>
                  </div>
                  <Toggle on={reminder} onChange={setReminder} />
                </div>
                {reminder && (
                  <div className="set-subrow">
                    <span className="set-rd">알림 시간</span>
                    <div className="set-times">
                      {['오전 6:30', '오전 9:00', '오후 9:00'].map(t => (
                        <button key={t} className={`set-chip ${reminderTime === t ? 'on' : ''}`} onClick={() => setReminderTime(t)}>{t}</button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              <div className="set-group">
                <div className="set-row">
                  <div className="set-rl"><div className="set-rt">멘토 응답 알림</div><div className="set-rd">멘토가 답장하면 알려드려요</div></div>
                  <Toggle on={mentorReply} onChange={setMentorReply} />
                </div>
                <div className="set-row">
                  <div className="set-rl"><div className="set-rt">응원·출석 알림</div><div className="set-rd">받은 응원과 출석 보상 소식</div></div>
                  <Toggle on={cheer} onChange={setCheer} />
                </div>
                <div className="set-row">
                  <div className="set-rl"><div className="set-rt">교회 공지</div><div className="set-rd">주일 예배·교회 소식</div></div>
                  <Toggle on={church} onChange={setChurch} />
                </div>
              </div>
            </>
          )}

          {section === 'theme' && (
            <div className="set-group">
              {[
                { v: 'dark',   emoji: '🌙', label: '어둡게', desc: '밤하늘 테마 (기본)' },
                { v: 'light',  emoji: '☀️', label: '밝게',   desc: '환한 화면' },
                { v: 'system', emoji: '⚙️', label: '시스템 따름', desc: '기기 설정에 맞춤' },
              ].map(o => (
                <button key={o.v} className={`set-radio ${theme === o.v ? 'on' : ''}`} onClick={() => setTheme(o.v)}>
                  <span className="set-remoji">{o.emoji}</span>
                  <span className="set-rl"><span className="set-rt">{o.label}</span><span className="set-rd">{o.desc}</span></span>
                  <span className={`set-radio-dot ${theme === o.v ? 'on' : ''}`} />
                </button>
              ))}
            </div>
          )}

          {section === 'backup' && (
            <>
              <div className="set-group">
                <div className="set-row">
                  <div className="set-rl"><div className="set-rt">자동 동기화</div><div className="set-rd">기록을 클라우드에 안전하게 백업해요</div></div>
                  <Toggle on={sync} onChange={setSync} />
                </div>
              </div>
              <div className="set-backup-card">
                <div className="sbc-icon">☁️</div>
                <div className="sbc-stat">마지막 백업</div>
                <div className="sbc-time">{backedUp ? '방금 전' : '오늘 오전 6:24'}</div>
                <button className={`sbc-btn ${backedUp ? 'done' : ''}`} onClick={() => setBackedUp(true)}>
                  {backedUp ? '✓ 백업 완료' : '지금 백업하기'}
                </button>
              </div>
              <div className="set-note">총 42개 기록 · 약 1.2MB</div>
            </>
          )}

          {section === 'help' && (
            <>
              <div className="set-group">
                {[
                  ['기록은 어떻게 백업되나요?', '클라우드 자동 동기화를 켜면 안전하게 보관돼요.'],
                  ['멘토는 실제 사람인가요?', 'AI가 성경 인물의 관점으로 함께 묵상해드려요.'],
                  ['캐릭터는 어떻게 자라나요?', '기도·감사·말씀을 기록하면 XP가 쌓여 레벨업해요.'],
                ].map((f, i) => (
                  <div key={i} className="set-faq">
                    <div className="set-faq-q">Q. {f[0]}</div>
                    <div className="set-faq-a">{f[1]}</div>
                  </div>
                ))}
              </div>
              <button className="set-contact" onClick={() => window.open('mailto:support@aimen.app')}>
                ✉️ 문의하기 · support@aimen.app
              </button>
              <div className="set-note">앱 버전 1.0 MVP · 중문교회</div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

window.SettingsScreen = SettingsScreen;
