// Модалка профиля — аватарка (загрузка) + ник + статистика навыков
const ProfileModal = ({ profile, setProfile, skills, onClose }) => {
  const [editingName, setEditingName] = React.useState(false);
  const [name, setName] = React.useState(profile.name || "");
  const [avatarMenu, setAvatarMenu] = React.useState(false);
  const fileRef = React.useRef(null);

  const pct = Math.round(((profile.xp||0) / (profile.xpToNext||100)) * 100);
  const skillsCount = (skills||[]).length;
  const skillsList = (skills||[]).slice(0, 6);

  const saveName = () => {
    if (name.trim()) setProfile(p => ({ ...p, name: name.trim() }));
    setEditingName(false);
  };

  const handleAvatarUpload = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!/^image\/(jpeg|jpg|png)$/.test(file.type)) {
      alert("Поддерживаются только JPG и PNG"); return;
    }
    if (file.size > 2 * 1024 * 1024) {
      alert("Файл должен быть до 2 МБ"); return;
    }
    const reader = new FileReader();
    reader.onload = ev => {
      setProfile(p => ({ ...p, customAvatar: ev.target.result }));
      setAvatarMenu(false);
    };
    reader.readAsDataURL(file);
  };

  const removeAvatar = () => {
    setProfile(p => { const np = {...p}; delete np.customAvatar; return np; });
    setAvatarMenu(false);
  };

  // Светящийся ободок: каждые 5 уровней — новый эффект
  const aura = profile.level >= 25 ? "legend"
            : profile.level >= 20 ? "purple"
            : profile.level >= 15 ? "gold"
            : profile.level >= 10 ? "blue"
            : profile.level >= 5  ? "green"
            : "none";
  const auraColors = {
    none:   { c1:"transparent", c2:"transparent", anim:"none" },
    green:  { c1:"#4ade80", c2:"#10b981", anim:"auraGreen 3s linear infinite" },
    blue:   { c1:"#60a5fa", c2:"#3b82f6", anim:"auraBlue 2.5s linear infinite" },
    gold:   { c1:"#fbbf24", c2:"#f59e0b", anim:"auraGold 2s linear infinite" },
    purple: { c1:"#a855f7", c2:"#ec4899", anim:"auraPurple 1.8s linear infinite" },
    legend: { c1:"#f43f5e", c2:"#fbbf24", anim:"auraLegend 1.4s linear infinite" },
  }[aura];

  return (
    <div className="ss-modal-backdrop" onClick={e=>e.target===e.currentTarget && onClose()} style={{ alignItems:"flex-start", paddingTop:60 }}>
      <div style={{
        width: "100%", maxWidth: 480, background:"var(--bg-3)", borderRadius:16, overflow:"hidden",
        boxShadow:"0 20px 60px rgba(0,0,0,0.5)", position:"relative"
      }}>
        {/* Шапка с градиентом */}
        <div style={{
          background: "linear-gradient(135deg, #6366f1, #a855f7)",
          padding: "32px 24px 64px", textAlign:"center", position:"relative"
        }}>
          <button onClick={onClose} style={{
            position:"absolute", top:16, right:16, width:34, height:34, borderRadius:"50%",
            background:"rgba(255,255,255,0.15)", border:"none", color:"white", cursor:"pointer",
            fontSize:18, display:"flex", alignItems:"center", justifyContent:"center"
          }}>✕</button>

          {/* Аватарка с эффектом */}
          <div style={{ position:"relative", display:"inline-block" }}>
            {aura !== "none" && (
              <div style={{
                position:"absolute", inset:-8, borderRadius:"50%",
                background: `conic-gradient(from 0deg, ${auraColors.c1}, ${auraColors.c2}, ${auraColors.c1})`,
                animation: auraColors.anim,
                filter: "blur(4px)", zIndex:0
              }}/>
            )}
            <div onClick={()=>setAvatarMenu(true)}
              style={{
                position:"relative", width:120, height:120, borderRadius:"50%", overflow:"hidden",
                border:"4px solid rgba(255,255,255,0.2)", cursor:"pointer", margin:"0 auto",
                background: profile.customAvatar ? `url(${profile.customAvatar}) center/cover` : "linear-gradient(135deg, #fbbf24, #f59e0b)",
                display:"flex", alignItems:"center", justifyContent:"center", zIndex:1
              }}>
              {!profile.customAvatar && (
                <div style={{ fontSize:60 }}>👤</div>
              )}
            </div>
          </div>

          {/* Имя */}
          <div style={{ marginTop: 16 }}>
            {editingName ? (
              <input value={name} autoFocus
                onChange={e=>setName(e.target.value)}
                onBlur={saveName}
                onKeyDown={e=>e.key==="Enter"&&saveName()}
                style={{
                  background: "rgba(255,255,255,0.15)", border: "1px solid rgba(255,255,255,0.3)",
                  borderRadius: 10, padding: "8px 14px", color:"white", fontSize:24, fontWeight:700,
                  textAlign:"center", outline:"none", width:"80%", maxWidth:300
                }}/>
            ) : (
              <h1 onClick={()=>{ setName(profile.name||""); setEditingName(true); }}
                style={{ margin:0, color:"white", fontSize:30, fontWeight:700, cursor:"pointer" }}>
                {profile.name || "Без имени"}
              </h1>
            )}
            <div style={{ marginTop:10, display:"inline-block",
              background:"rgba(255,255,255,0.2)", padding:"6px 18px", borderRadius:20,
              color:"white", fontSize:13, fontWeight:600 }}>
              Уровень {profile.level || 1}
            </div>
          </div>
        </div>

        {/* Тело */}
        <div style={{ padding: "20px 24px", marginTop: -32, position:"relative" }}>
          {/* XP bar */}
          <div style={{ marginBottom:18 }}>
            <div style={{ display:"flex", justifyContent:"space-between", marginBottom:6 }}>
              <span style={{ fontSize:12, color:"var(--text-3)" }}>Опыт</span>
              <span className="num" style={{ fontSize:12, fontWeight:600 }}>{profile.xp||0} / {profile.xpToNext||100}</span>
            </div>
            <div style={{ height:6, background:"var(--bg-2)", borderRadius:3, overflow:"hidden" }}>
              <div style={{ height:"100%", width:`${pct}%`,
                background: pct >= 75 ? "linear-gradient(90deg, #fbbf24, #f59e0b)" : "linear-gradient(90deg, #6366f1, #a855f7)",
                transition:"width 0.4s, background 0.3s",
                boxShadow: pct >= 75 ? "0 0 10px rgba(251,191,36,0.5)" : "none"
              }}/>
            </div>
          </div>

          <div style={{ display:"flex", justifyContent:"space-between", padding:"10px 0", borderBottom:"1px solid var(--line-1)" }}>
            <span style={{ color:"var(--text-3)", fontSize:13 }}>Всего опыта</span>
            <span className="num" style={{ fontWeight:700, fontSize:14 }}>{(profile.totalXp||0).toLocaleString("ru")}</span>
          </div>

          <div style={{ display:"flex", gap:8, marginTop:14, marginBottom:14 }}>
            <div style={{ flex:1, padding:"10px 14px", background:"var(--bg-4)", borderRadius:10, border:"1px solid var(--line-2)" }}>
              <div style={{ fontSize:10, color:"var(--text-4)", textTransform:"uppercase" }}>Аура</div>
              <div style={{ fontSize:13, fontWeight:600, marginTop:2 }}>
                {aura==="none"?"—":aura==="green"?"💚 Изумруд":aura==="blue"?"💎 Сапфир":aura==="gold"?"⭐ Золото":aura==="purple"?"🔮 Аметист":"🔥 Легенда"}
              </div>
            </div>
            <div style={{ flex:1, padding:"10px 14px", background:"var(--bg-4)", borderRadius:10, border:"1px solid var(--line-2)" }}>
              <div style={{ fontSize:10, color:"var(--text-4)", textTransform:"uppercase" }}>Навыков</div>
              <div style={{ fontSize:13, fontWeight:600, marginTop:2 }}>⚔ {skillsCount}</div>
            </div>
          </div>

          {/* Навыки списком */}
          {skillsList.length > 0 && (
            <div>
              <div style={{ textAlign:"center", color:"var(--text-3)", fontSize:13, marginBottom:10, marginTop:18 }}>Навыки</div>
              <div style={{ display:"flex", flexWrap:"wrap", gap:6, justifyContent:"center" }}>
                {skillsList.map(s => {
                  const totalXp = (s.nodes||[]).reduce((sum,n)=>sum+((n.sessions||0)>=(n.requiredSessions||5)?(n.xpReward||100):0), 0);
                  const lvl = Math.floor(totalXp/100)+1;
                  const tier = lvl>=10?"S":lvl>=7?"A":lvl>=5?"B":lvl>=3?"C":"D";
                  return (
                    <div key={s.id} style={{
                      display:"flex", alignItems:"center", gap:6, padding:"6px 12px",
                      background:`color-mix(in oklab, ${s.color} 25%, var(--bg-4))`,
                      borderRadius:20, fontSize:12
                    }}>
                      <span style={{
                        width:18, height:18, background:"rgba(0,0,0,0.3)", borderRadius:"50%",
                        display:"flex", alignItems:"center", justifyContent:"center",
                        color:"white", fontSize:10, fontWeight:700
                      }}>{tier}</span>
                      <span style={{ color:"white", fontWeight:600 }}>{s.title}</span>
                      <span style={{ color:"rgba(255,255,255,0.7)", fontSize:11 }}>Ур. {lvl}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Кнопки управления */}
          <div style={{ display:"flex", justifyContent:"center", gap:10, marginTop:20 }}>
            <button onClick={()=>{ setName(profile.name||""); setEditingName(true); }}
              style={{
                width:46, height:46, borderRadius:10, background:"var(--bg-4)",
                border:"1px solid var(--line-2)", cursor:"pointer",
                display:"flex", alignItems:"center", justifyContent:"center",
                color:"#a855f7", fontSize:18
              }}>✎</button>
          </div>
        </div>

        {/* Меню аватарки */}
        {avatarMenu && (
          <div onClick={e=>e.target===e.currentTarget&&setAvatarMenu(false)} style={{
            position:"absolute", inset:0, background:"rgba(0,0,0,0.5)", zIndex:5,
            display:"flex", alignItems:"center", justifyContent:"center", padding:20
          }}>
            <div style={{ background:"var(--bg-4)", borderRadius:14, padding:"20px 24px", minWidth:240, textAlign:"center" }}>
              <div style={{ fontSize:14, fontWeight:600, marginBottom:14, color:"white" }}>Аватарка</div>
              <input ref={fileRef} type="file" accept="image/jpeg,image/jpg,image/png"
                onChange={handleAvatarUpload} style={{ display:"none" }}/>
              <button onClick={()=>fileRef.current?.click()} className="ss-btn"
                style={{ width:"100%", marginBottom:8 }}>Изменить</button>
              {profile.customAvatar && (
                <button onClick={removeAvatar} style={{
                  width:"100%", padding:"10px", borderRadius:8,
                  background:"transparent", border:"none", color:"var(--crimson)",
                  cursor:"pointer", fontSize:14
                }}>Удалить</button>
              )}
              <button onClick={()=>setAvatarMenu(false)} style={{
                width:"100%", padding:"10px", marginTop:6, borderRadius:8,
                background:"var(--bg-3)", border:"1px solid var(--line-2)", color:"var(--text-2)",
                cursor:"pointer", fontSize:13
              }}>Отмена</button>
            </div>
          </div>
        )}
      </div>

      {/* Анимации ауры */}
      <style>{`
        @keyframes auraGreen  { 0%{transform:rotate(0deg)} 100%{transform:rotate(360deg)} }
        @keyframes auraBlue   { 0%{transform:rotate(0deg)} 100%{transform:rotate(360deg)} }
        @keyframes auraGold   { 0%{transform:rotate(0deg)} 100%{transform:rotate(360deg)} }
        @keyframes auraPurple { 0%{transform:rotate(0deg)} 100%{transform:rotate(360deg)} }
        @keyframes auraLegend { 0%{transform:rotate(0deg)} 100%{transform:rotate(360deg)} }
      `}</style>
    </div>
  );
};
