// Profile + streak calendar + badges + settings.
function StreakDot({ done, today, label }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
      <div style={{
        width: 38, height: 38, borderRadius: '50%',
        background: done ? OA_THEME.sage : '#E6DFD3',
        border: today ? `2.5px solid ${OA_THEME.gold}` : `2px solid ${done ? OA_THEME.sageDeep : OA_THEME.line}`,
        display:'flex', alignItems:'center', justifyContent:'center',
        color: '#fff', fontSize: 18,
        boxShadow: done ? `0 2px 0 ${OA_THEME.sageDeep}` : 'none',
      }}>{done ? '✓' : today ? '●' : ''}</div>
      <div style={{ fontSize: 14, fontWeight: 700, color: today ? OA_THEME.goldDeep : OA_THEME.inkSoft }}>{label}</div>
    </div>
  );
}

const ALL_BADGES = [
  { id: 'memory_first', icon: '🌸', name: 'Memori Bunga', sub: 'Latihan pertama' },
  { id: 'streak_3',     icon: '🌅', name: 'Tiga Hari',    sub: '3 hari' },
  { id: 'streak_7',     icon: '🌅', name: 'Pagi Awal',    sub: '7 hari' },
  { id: 'streak_14',    icon: '🍵', name: 'Sore Tenang',  sub: '14 hari' },
  { id: 'streak_30',    icon: '🌙', name: 'Bulan Penuh',  sub: '30 hari' },
  { id: 'lessons_10',   icon: '🪴', name: 'Bertumbuh',    sub: '10 latihan' },
  { id: 'lessons_50',   icon: '🌳', name: 'Pohon Tegak',  sub: '50 latihan' },
  { id: 'pembaca',      icon: '📖', name: 'Pembaca',      sub: '50 peribahasa' },
  { id: 'kupu_cermat',  icon: '🦋', name: 'Kupu Cermat',  sub: '100% akurat' },
];

function lastSevenDays(history, todayISO) {
  const days = [];
  const dayLabels = ['M','S','S','R','K','J','S']; // Sun-Sat
  for (let i = 6; i >= 0; i--) {
    const d = new Date(todayISO + 'T00:00:00');
    d.setDate(d.getDate() - i);
    const iso = OAStorage.isoDay(d);
    days.push({ iso, done: !!history[iso], today: i === 0, label: dayLabels[d.getDay()] });
  }
  return days;
}

function Profile({ profile, onBack, onUpdateSettings, onChangeName, onResetData }) {
  const today = OAStorage.isoDay();
  const days = lastSevenDays(profile.history || {}, today);
  const earnedCount = Object.keys(profile.badges || {}).length;
  const [editName, setEditName] = React.useState(false);
  const [nameDraft, setNameDraft] = React.useState(profile.name);
  const [confirmReset, setConfirmReset] = React.useState(false);

  const settingItems = [
    {
      i: '🔠', l: 'Ukuran tulisan',
      v: profile.settings.fontScale === 'sangat-besar' ? 'Sangat besar' : profile.settings.fontScale === 'besar' ? 'Besar' : 'Normal',
      onClick: () => {
        const order = ['normal', 'besar', 'sangat-besar'];
        const next = order[(order.indexOf(profile.settings.fontScale) + 1) % order.length];
        onUpdateSettings({ fontScale: next });
      },
    },
    {
      i: '🎨', l: 'Warna tampilan',
      v: OA_PALETTES[profile.settings.palette].name,
      onClick: () => {
        const order = ['sage', 'sky', 'rose'];
        const next = order[(order.indexOf(profile.settings.palette) + 1) % order.length];
        onUpdateSettings({ palette: next });
      },
    },
    {
      i: '🔊', l: 'Suara',
      v: profile.settings.soundsOn ? 'Aktif' : 'Mati',
      onClick: () => onUpdateSettings({ soundsOn: !profile.settings.soundsOn }),
    },
  ];

  return (
    <div style={{ minHeight: '100dvh', background: OA_THEME.cream, paddingBottom: 130 }}>
      <div style={{ paddingTop: 'max(20px, env(safe-area-inset-top))' }}>
        <TopBar title="Profil" onBack={onBack} />

        <div style={{ padding: '8px 22px 0', textAlign: 'center' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 8 }}>
            <div style={{
              width: 110, height: 110, borderRadius: '50%',
              background: OA_THEME.card, border: `3px solid ${OA_THEME.sage}`,
              display:'flex', alignItems:'flex-end', justifyContent:'center',
              boxShadow: `0 4px 0 ${OA_THEME.sage}40`, overflow: 'hidden',
            }}>
              <Mascot size={120} mood="happy" />
            </div>
          </div>
          {editName ? (
            <div style={{ display: 'flex', gap: 8, justifyContent: 'center', alignItems: 'center', marginBottom: 4 }}>
              <input
                value={nameDraft}
                onChange={e => setNameDraft(e.target.value.slice(0, 30))}
                autoFocus
                style={{
                  fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600, fontSize: 24,
                  textAlign: 'center', color: OA_THEME.ink,
                  background: OA_THEME.card,
                  border: `2px solid ${OA_THEME.sage}`,
                  borderRadius: 14, padding: '8px 12px',
                  outline: 'none', maxWidth: 220,
                }}
              />
              <button onClick={() => { onChangeName((nameDraft || '').trim() || profile.name); setEditName(false); }} className="oa-no-tap" style={{
                background: OA_THEME.sage, color: '#fff', border: 'none', borderRadius: 12,
                padding: '8px 14px', fontWeight: 800, fontSize: 16, cursor: 'pointer',
              }}>Simpan</button>
            </div>
          ) : (
            <div onClick={() => { setNameDraft(profile.name); setEditName(true); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
              <div style={{ fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600, fontSize: 28, color: OA_THEME.ink }}>{profile.name}</div>
              <span style={{ fontSize: 18, color: OA_THEME.inkSoft }}>✎</span>
            </div>
          )}
          <div style={{ fontSize: 16, color: OA_THEME.inkSoft }}>Bergabung sejak {formatJoinDate(profile.joined)}</div>
        </div>

        <div style={{ margin: '18px 18px 14px', background: OA_THEME.card, borderRadius: 22, padding: '16px 18px', border: `1.5px solid ${OA_THEME.line}`, boxShadow: '0 2px 0 rgba(60,82,76,0.06)' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 10 }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 800, color: OA_THEME.inkSoft, letterSpacing: 0.6, textTransform: 'uppercase' }}>Streak</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span style={{ fontSize: 38, fontWeight: 900, color: OA_THEME.roseDeep, fontFamily: 'Lora, serif', fontStyle: 'italic' }}>🔥 {profile.streak}</span>
                <span style={{ fontSize: 18, color: OA_THEME.inkSoft, fontWeight: 700 }}>hari</span>
              </div>
            </div>
            {profile.bestStreak > 0 && (
              <div style={{
                background: '#FCEFE9', color: OA_THEME.roseDeep,
                border: `1.5px solid ${OA_THEME.rose}`,
                borderRadius: 14, padding: '8px 12px',
                fontSize: 14, fontWeight: 800,
                textAlign: 'center', lineHeight: 1.2,
              }}>Rekor: {profile.bestStreak} hari</div>
            )}
          </div>
          <div style={{ display:'flex', justifyContent:'space-between' }}>
            {days.map((d, i) => <StreakDot key={d.iso} done={d.done} today={d.today} label={d.label} />)}
          </div>
        </div>

        <div style={{ display:'flex', gap: 10, padding: '0 18px 14px' }}>
          <StatTile icon="🌟" label="Poin" value={profile.totalXp} color={OA_THEME.sageDeep} />
          <StatTile icon="📚" label="Latihan" value={profile.lessonsDone} color={OA_THEME.skyDeep} />
          <StatTile icon="🏅" label="Lencana" value={`${earnedCount}/${ALL_BADGES.length}`} color={OA_THEME.goldDeep} />
        </div>

        <div style={{ padding: '4px 18px 14px' }}>
          <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 10 }}>
            <div style={{ fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600, fontSize: 22, color: OA_THEME.ink }}>Lencana</div>
            <div style={{ fontSize: 14, color: OA_THEME.inkSoft, fontWeight: 700 }}>{earnedCount} dari {ALL_BADGES.length}</div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap: 10 }}>
            {ALL_BADGES.map(b => (
              <Badge key={b.id} icon={b.icon} name={b.name} sub={b.sub} earned={!!profile.badges[b.id]} />
            ))}
          </div>
        </div>

        <div style={{ padding: '4px 18px 14px' }}>
          <div style={{ fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600, fontSize: 22, color: OA_THEME.ink, marginBottom: 10 }}>Pengaturan</div>
          <div style={{ background: OA_THEME.card, borderRadius: 18, border: `1.5px solid ${OA_THEME.line}`, overflow: 'hidden' }}>
            {settingItems.map((r, i, arr) => (
              <button key={r.l} onClick={() => { OASound.tap(); r.onClick(); }} className="oa-no-tap" style={{
                width: '100%', display:'flex', alignItems:'center', gap: 12, padding: '14px 16px',
                borderBottom: i < arr.length - 1 ? `1px solid ${OA_THEME.line}` : 'none',
                background: 'transparent', border: 'none', textAlign: 'left', cursor: 'pointer',
              }}>
                <div style={{ width: 42, height: 42, borderRadius: 12, background: '#EAF1EB', display:'flex', alignItems:'center', justifyContent:'center', fontSize: 22, flexShrink: 0 }}>{r.i}</div>
                <div style={{ flex: 1, fontSize: 19, fontWeight: 700, color: OA_THEME.ink }}>{r.l}</div>
                <div style={{ fontSize: 16, color: OA_THEME.inkSoft, fontWeight: 700 }}>{r.v}</div>
                <div style={{ fontSize: 22, color: OA_THEME.inkSoft }}>›</div>
              </button>
            ))}
          </div>
        </div>

        <div style={{ padding: '4px 18px 36px' }}>
          {confirmReset ? (
            <div style={{ background: OA_THEME.card, border: `2px solid ${OA_THEME.rose}`, borderRadius: 18, padding: '14px 16px' }}>
              <div style={{ fontSize: 17, color: OA_THEME.ink, marginBottom: 12 }}>Hapus semua data dan mulai dari awal?</div>
              <div style={{ display: 'flex', gap: 10 }}>
                <OABigButton color={OA_THEME.rose} onClick={() => { onResetData(); setConfirmReset(false); }} style={{ minHeight: 52, fontSize: 17 }}>Ya, hapus</OABigButton>
                <OABigButton color={OA_THEME.sage} onClick={() => setConfirmReset(false)} style={{ minHeight: 52, fontSize: 17 }}>Batal</OABigButton>
              </div>
            </div>
          ) : (
            <button onClick={() => { OASound.tap(); setConfirmReset(true); }} className="oa-no-tap" style={{
              width: '100%', padding: '14px 16px', borderRadius: 16,
              background: 'transparent', border: `1.5px solid ${OA_THEME.line}`,
              fontSize: 16, fontWeight: 700, color: OA_THEME.inkSoft, cursor: 'pointer',
            }}>Mulai dari awal lagi</button>
          )}
        </div>
      </div>
    </div>
  );
}

function formatJoinDate(iso) {
  if (!iso) return '';
  const months = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
  const d = new Date(iso + 'T00:00:00');
  return `${months[d.getMonth()]} ${d.getFullYear()}`;
}

window.Profile = Profile;
