// ═══════════════════════════════════════════════════════════════
// SKILLS — Древо навыков, создаваемое пользователем
// Каждый узел: sessions (счётчик 1сессия = 1ед.), требование для разблокировки,
// XP за разблокировку, награда, дочерние узлы (поднавыки)
// ═══════════════════════════════════════════════════════════════

const SKILL_ICONS = [
  "🌳","💪","🧠","💼","❤️","⚡","🎯","🔥","⭐","🏆",
  "📚","🎨","🎵","🏃","🧘","💎","🚀","⚔️","🛡️","🏋️",
  "🥊","🎸","🎹","🎭","🎬","📷","✍️","📖","🔬","🔭",
  "💻","🎮","♟️","🎲","🏊","🤸","🚴","⛷️","🥋","🤼",
  "🌱","🌊","☄️","🦁","🐉","🦅","🦊","🦝","🐺","🔮",
  "💡","🧩","🗝️","⚙️","🔑","🏅","🎪","🎡","🌈","✨",
  "🍎","🥑","🧃","🏰","🗺️","🧭","⚓","🌍","🎖️","🏯",
];

const NodeModal = ({ node, parentNode, onSave, onClose, onDelete }) => {
  const isEdit = node && node.id;
  const [form, setForm] = React.useState({
    title: "",
    description: "",
    requiredSessions: 5,
    xpReward: 100,
    reward: "",
    notes: "",
    parentId: parentNode?.id || null,
    ...(isEdit ? node : {}),
  });
  const set = (k, v) => setForm(f => ({...f, [k]: v}));

  return (
    <div className="ss-modal-backdrop" onClick={e => e.target===e.currentTarget && onClose()}>
      <div className="ss-modal" style={{ maxWidth: 460 }}>
        <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:16 }}>
          <h3 style={{ margin:0 }}>{isEdit ? "Редактировать узел" : parentNode ? `Поднавык от «${parentNode.title}»` : "Новый узел"}</h3>
          <button onClick={onClose} style={{ background:"none", border:"none", cursor:"pointer", color:"var(--text-3)", fontSize:20 }}>✕</button>
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Название узла</div>
          <input className="ss-input" style={{ width:"100%" }} autoFocus
            value={form.title} onChange={e=>set("title",e.target.value)}
            placeholder="Например: Базовая выносливость" />
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Описание</div>
          <textarea className="ss-input" style={{ width:"100%", fontFamily:"inherit", resize:"vertical" }} rows={2}
            value={form.description} onChange={e=>set("description",e.target.value)}
            placeholder="Что нужно делать чтобы прокачать узел..." />
        </div>
        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:10, marginBottom:12 }}>
          <div>
            <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Сессий до разблокировки</div>
            <input className="ss-input" style={{ width:"100%" }} type="number" min={1} max={500}
              value={form.requiredSessions} onChange={e=>set("requiredSessions",parseInt(e.target.value)||1)} />
          </div>
          <div>
            <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>XP при разблокировке</div>
            <input className="ss-input" style={{ width:"100%" }} type="number" min={10} max={5000} step={10}
              value={form.xpReward} onChange={e=>set("xpReward",parseInt(e.target.value)||100)} />
          </div>
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Личная награда (необязательно)</div>
          <input className="ss-input" style={{ width:"100%" }}
            value={form.reward} onChange={e=>set("reward",e.target.value)}
            placeholder="Например: купить новые перчатки" />
        </div>
        <div style={{ marginBottom:16 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>📝 Заметки</div>
          <textarea className="ss-input" style={{ width:"100%", fontFamily:"inherit", resize:"vertical" }} rows={3}
            value={form.notes} onChange={e=>set("notes",e.target.value)}
            placeholder="Любая информация связанная с этим узлом..." />
        </div>
        <div style={{ display:"flex", gap:8 }}>
          {isEdit && (
            <button onClick={()=>{ if(confirm("Удалить узел?")) onDelete(node.id); }}
              style={{ padding:"10px 14px", borderRadius:8, border:"1px solid rgba(220,50,50,0.3)", background:"rgba(220,50,50,0.1)", color:"var(--crimson)", cursor:"pointer", fontSize:12 }}>
              Удалить
            </button>
          )}
          <button onClick={onClose} style={{ flex:1, padding:"10px", borderRadius:8, border:"1px solid var(--line-2)", background:"var(--bg-3)", cursor:"pointer", color:"var(--text-2)" }}>Отмена</button>
          <button onClick={()=>{ if(form.title.trim()){ onSave({...form, id: isEdit ? form.id : "node_"+Date.now()}); onClose(); } }}
            className="ss-btn" style={{ flex:2 }}>
            {isEdit ? "Сохранить" : "Создать"}
          </button>
        </div>
      </div>
    </div>
  );
};

const SkillModal = ({ skill, onSave, onClose, onDelete }) => {
  const isEdit = skill && skill.id;
  const [form, setForm] = React.useState({
    title: "",
    description: "",
    icon: "🌳",
    color: "#4ade80",
    notes: "",
    xpButtonAmount: 25,  // XP за нажатие кнопки +XP
    ...(isEdit ? skill : {}),
  });
  const COLORS = ["#4ade80","#60a5fa","#f59e0b","#a855f7","#f97316","#ef4444","#06b6d4","#ec4899","#84cc16"];
  const set = (k,v) => setForm(f => ({...f, [k]: v}));

  return (
    <div className="ss-modal-backdrop" onClick={e=>e.target===e.currentTarget&&onClose()}>
      <div className="ss-modal" style={{ maxWidth:440 }}>
        <div style={{ display:"flex", justifyContent:"space-between", marginBottom:16 }}>
          <h3 style={{ margin:0 }}>{isEdit?"Редактировать навык":"Новый навык"}</h3>
          <button onClick={onClose} style={{ background:"none", border:"none", cursor:"pointer", color:"var(--text-3)", fontSize:20 }}>✕</button>
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Название</div>
          <input className="ss-input" style={{ width:"100%" }} autoFocus
            value={form.title} onChange={e=>set("title",e.target.value)}
            placeholder="Например: Здоровье, Программирование, Гитара..." />
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Описание</div>
          <textarea className="ss-input" style={{ width:"100%", fontFamily:"inherit" }} rows={2}
            value={form.description} onChange={e=>set("description",e.target.value)} />
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Иконка</div>
          <div style={{ display:"flex", gap:4, flexWrap:"wrap" }}>
            {SKILL_ICONS.map(ic=>(
              <button key={ic} onClick={()=>set("icon",ic)}
                style={{ width:36, height:36, fontSize:18, borderRadius:6, cursor:"pointer",
                  border: form.icon===ic ? `2px solid ${form.color}` : "1px solid var(--line-2)",
                  background: form.icon===ic ? "var(--bg-4)" : "var(--bg-3)" }}>{ic}</button>
            ))}
          </div>
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>Цвет ветки</div>
          <div style={{ display:"flex", gap:6 }}>
            {COLORS.map(c=>(
              <button key={c} onClick={()=>set("color",c)}
                style={{ width:30, height:30, borderRadius:"50%", cursor:"pointer", background:c,
                  border: form.color===c ? "3px solid white" : "2px solid var(--line-2)" }} />
            ))}
          </div>
        </div>
        <div style={{ marginBottom:12 }}>
          <div style={{ display:"flex", justifyContent:"space-between", marginBottom:4 }}>
            <span style={{ fontSize:11, color:"var(--text-3)" }}>XP за нажатие кнопки +XP</span>
            <span style={{ fontSize:13, fontWeight:600, color:form.color }}>{form.xpButtonAmount}</span>
          </div>
          <input type="range" min={5} max={200} step={5} value={form.xpButtonAmount}
            onChange={e=>set("xpButtonAmount",parseInt(e.target.value))}
            style={{ width:"100%", accentColor:form.color }} />
        </div>
        <div style={{ marginBottom:16 }}>
          <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:4 }}>📝 Заметки</div>
          <textarea className="ss-input" style={{ width:"100%", fontFamily:"inherit", resize:"vertical" }} rows={3}
            value={form.notes} onChange={e=>set("notes",e.target.value)}
            placeholder="Любая информация связанная с навыком..." />
        </div>
        <div style={{ display:"flex", gap:8 }}>
          {isEdit && (
            <button onClick={()=>{ if(confirm("Удалить весь навык со всеми узлами?")) onDelete(skill.id); }}
              style={{ padding:"10px 14px", borderRadius:8, border:"1px solid rgba(220,50,50,0.3)", background:"rgba(220,50,50,0.1)", color:"var(--crimson)", cursor:"pointer", fontSize:12 }}>
              Удалить
            </button>
          )}
          <button onClick={onClose} style={{ flex:1, padding:"10px", borderRadius:8, border:"1px solid var(--line-2)", background:"var(--bg-3)", cursor:"pointer", color:"var(--text-2)" }}>Отмена</button>
          <button onClick={()=>{ if(form.title.trim()){ onSave({...form, id: isEdit ? form.id : "skill_"+Date.now()}); onClose(); } }}
            className="ss-btn" style={{ flex:2 }}>{isEdit?"Сохранить":"Создать"}</button>
        </div>
      </div>
    </div>
  );
};

// Узел в виде карточки в дереве
const SkillNode = ({ node, allNodes, color, depth=0, onComplete, onAdjustXp, onAddChild, onEdit, parentUnlocked=true, flowActive, xpButtonAmount=25 }) => {
  const requiredSessions = node.requiredSessions || 5;
  const sessions = node.sessions || 0;
  const unlocked = sessions >= requiredSessions;
  const progress = Math.min(100, (sessions/requiredSessions)*100);
  const highlight = progress >= 75 && progress < 100;  // подсветка 75%
  const children = (allNodes || []).filter(n => n.parentId === node.id);
  const canInteract = parentUnlocked;

  return (
    <div style={{ marginLeft: depth * 24, marginBottom: 8 }}>
      <div style={{
        padding: "12px 14px", borderRadius: 10,
        background: unlocked ? `color-mix(in oklab, ${color} 15%, var(--bg-4))` : canInteract ? "var(--bg-4)" : "var(--bg-3)",
        border: unlocked ? `1px solid ${color}` : highlight ? "1px solid #fbbf24" : canInteract ? "1px solid var(--line-2)" : "1px solid var(--line-1)",
        opacity: canInteract ? 1 : 0.5,
        position: "relative",
        transition: "all 0.3s",
        boxShadow: highlight ? "0 0 14px rgba(251,191,36,0.25)" : "none"
      }}>
        <div style={{ display:"flex", alignItems:"flex-start", gap:10 }}>
          <div style={{
            width: 32, height: 32, borderRadius: "50%",
            display:"flex", alignItems:"center", justifyContent:"center",
            background: unlocked ? color : "var(--bg-3)",
            border: `2px solid ${unlocked ? color : "var(--line-2)"}`,
            color: unlocked ? "#000" : "var(--text-3)",
            fontSize: 16, fontWeight: 700, flexShrink: 0
          }}>
            {unlocked ? "✓" : depth+1}
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", gap:8, marginBottom:4 }}>
              <div style={{ fontSize:14, fontWeight:600, color:"var(--text-1)" }}>{node.title}</div>
              <div style={{ display:"flex", gap:4, flexShrink:0 }}>
                <button onClick={()=>onAddChild(node)} style={{ padding:"3px 8px", fontSize:11, background:"var(--bg-3)", border:"1px solid var(--line-2)", borderRadius:6, cursor:"pointer", color:"var(--text-2)" }} title="Добавить поднавык">+</button>
                <button onClick={()=>onEdit(node)} style={{ padding:"3px 8px", fontSize:11, background:"var(--bg-3)", border:"1px solid var(--line-2)", borderRadius:6, cursor:"pointer", color:"var(--text-2)" }}>✎</button>
              </div>
            </div>
            {node.description && <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:6 }}>{node.description}</div>}
            <div style={{ height:5, background:"var(--bg-2)", borderRadius:3, overflow:"hidden", marginBottom:5 }}>
              <div style={{ height:"100%", width:`${progress}%`,
                background: highlight ? "linear-gradient(90deg, #fbbf24, #f59e0b)" : color,
                transition:"width 0.4s, background 0.3s",
                boxShadow: unlocked ? `0 0 6px ${color}` : highlight ? "0 0 8px rgba(251,191,36,0.5)" : "none" }}/>
            </div>
            <div style={{ display:"flex", justifyContent:"space-between", fontSize:10, color:"var(--text-3)" }}>
              <span>{sessions}/{requiredSessions} сессий</span>
              <span style={{ color: unlocked ? color : highlight ? "#fbbf24" : "var(--accent)" }}>
                {highlight && "🔥 "}+{node.xpReward||100} XP
              </span>
            </div>
            {node.reward && (
              <div style={{ marginTop:6, fontSize:10, color:"var(--text-4)", fontStyle:"italic" }}>
                🎁 Награда: {node.reward}
              </div>
            )}
            {node.notes && (
              <div style={{ marginTop:6, fontSize:10, color:"var(--text-4)", padding:"6px 8px", background:"var(--bg-2)", borderRadius:6, borderLeft:"2px solid var(--text-4)" }}>
                📝 {node.notes}
              </div>
            )}
            {canInteract && !unlocked && (
              <div style={{ display:"flex", gap:6, marginTop:8, alignItems:"center" }}>
                <button onClick={()=>onComplete(node)} className="ss-btn"
                  style={{ fontSize:11, padding:"5px 12px" }}>
                  + Сессия {flowActive && <span style={{color:"#fff"}}>×2</span>}
                </button>
                <div style={{ flex:1 }}/>
                <button onClick={()=>onAdjustXp(node, +xpButtonAmount)}
                  style={{ padding:"5px 10px", fontSize:11, fontWeight:600,
                    background:"rgba(74,222,128,0.15)", border:"1px solid #4ade80",
                    borderRadius:6, cursor:"pointer", color:"#4ade80" }}
                  title={`+${xpButtonAmount} XP к узлу`}>
                  +{xpButtonAmount}
                </button>
                <button onClick={()=>onAdjustXp(node, -xpButtonAmount)}
                  style={{ padding:"5px 10px", fontSize:11, fontWeight:600,
                    background:"rgba(220,50,50,0.15)", border:"1px solid var(--crimson)",
                    borderRadius:6, cursor:"pointer", color:"var(--crimson)" }}
                  title={`-${xpButtonAmount} XP с узла`}>
                  −{xpButtonAmount}
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
      {/* Дочерние узлы (поднавыки) */}
      {children.map(c => (
        <SkillNode key={c.id} node={c} allNodes={allNodes} color={color} depth={depth+1}
          onComplete={onComplete} onAdjustXp={onAdjustXp} onAddChild={onAddChild} onEdit={onEdit}
          parentUnlocked={unlocked} flowActive={flowActive} xpButtonAmount={xpButtonAmount} />
      ))}
    </div>
  );
};

const SkillsPage = ({ skills, setSkills, profile, setProfile, logEvent, flow, setLevelUpPopup }) => {
  const [activeSkillId, setActiveSkillId] = React.useState(null);
  const [skillModal, setSkillModal] = React.useState(null);
  const [nodeModal, setNodeModal]   = React.useState(null);

  const flowActive = flow?.active;
  const activeSkill = (skills || []).find(s => s.id === activeSkillId);

  // Прогресс навыка = открытые узлы / все узлы
  const skillProgress = (s) => {
    const total = (s.nodes||[]).length;
    if (!total) return { done: 0, total: 0, pct: 0 };
    const done = (s.nodes||[]).filter(n => (n.sessions||0) >= (n.requiredSessions||5)).length;
    return { done, total, pct: Math.round(done/total*100) };
  };

  // Уровень навыка = floor(skillXP / 100), 100 XP на уровень
  const skillLevel = (s) => {
    const totalXp = (s.nodes||[]).reduce((sum, n) => {
      const unlocked = (n.sessions||0) >= (n.requiredSessions||5);
      return sum + (unlocked ? (n.xpReward||100) : 0);
    }, 0);
    const lvl = Math.floor(totalXp / 100) + 1;
    const curLvlXp = totalXp % 100;
    return { level: lvl, xp: curLvlXp, totalXp };
  };

  // +1 сессия в узел
  // Прямое +/- XP к узлу через кнопки
  const adjustNodeXp = (node, deltaXp) => {
    if (!activeSkill) return;
    // конвертируем XP в сессии: округляем до ближайшей сессии
    // 1 сессия = node.xpReward / requiredSessions XP
    const xpPerSession = (node.xpReward || 100) / (node.requiredSessions || 5);
    const sessionDelta = Math.round(deltaXp / xpPerSession);
    const wasUnlocked = (node.sessions||0) >= (node.requiredSessions||5);
    const newSessions = Math.max(0, (node.sessions||0) + sessionDelta);
    const nowUnlocked = newSessions >= (node.requiredSessions||5);

    setSkills(ss => ss.map(s => s.id === activeSkill.id
      ? { ...s, nodes: s.nodes.map(n => n.id === node.id ? {...n, sessions: newSessions} : n) }
      : s
    ));

    // Передаём XP в общий уровень персонажа
    if (deltaXp > 0) {
      setProfile(p => {
        const newP = SSEngine.addXp(p, deltaXp);
        if (newP.level > p.level) {
          if (setLevelUpPopup) setLevelUpPopup({ from: p.level, to: newP.level });
          if (window.playSound) window.playSound("levelup");
        }
        return newP;
      });
    } else if (deltaXp < 0) {
      setProfile(p => SSEngine.subtractXp(p, Math.abs(deltaXp)));
    }

    if (window.playSound) window.playSound(deltaXp > 0 ? "click" : "click");
    if (!wasUnlocked && nowUnlocked && window.playSound) window.playSound("unlock");
    logEvent(deltaXp > 0
      ? `+XP к узлу «${node.title}»`
      : `−XP с узла «${node.title}»`,
      `${deltaXp > 0 ? "+" : ""}${deltaXp} XP`);
  };

  const addSession = (node) => {
    if (!activeSkill) return;
    const wasUnlocked = (node.sessions||0) >= (node.requiredSessions||5);
    const newSessions = (node.sessions||0) + 1;
    const nowUnlocked = newSessions >= (node.requiredSessions||5);

    const updatedNodes = activeSkill.nodes.map(n =>
      n.id === node.id ? { ...n, sessions: newSessions, lastSession: new Date().toISOString() } : n
    );
    setSkills(ss => ss.map(s => s.id === activeSkill.id ? { ...s, nodes: updatedNodes } : s));

    // Звук + анимация
    playSound("click");

    // Если узел только что разблокирован — XP + popup
    if (!wasUnlocked && nowUnlocked) {
      const xp = (node.xpReward || 100) * (flowActive ? 2 : 1);
      setProfile(p => {
        const newP = SSEngine.addXp(p, xp);
        // Если уровень повысился — popup
        if (newP.level > p.level) {
          if (setLevelUpPopup) setLevelUpPopup({ from: p.level, to: newP.level });
          playSound("levelup");
        }
        return newP;
      });
      playSound("unlock");
      logEvent(`🌳 Узел открыт: ${node.title}${flowActive?" (Поток ×2)":""}`, `+${xp} XP`);
    } else {
      logEvent(`+1 сессия: ${node.title}`, "");
    }
  };

  const saveSkill = (skillData) => {
    const exists = (skills||[]).some(s => s.id === skillData.id);
    if (exists) setSkills(ss => ss.map(s => s.id === skillData.id ? { ...s, ...skillData } : s));
    else setSkills(ss => [...(ss||[]), { ...skillData, nodes: [] }]);
  };
  const deleteSkill = (id) => {
    setSkills(ss => ss.filter(s => s.id !== id));
    if (activeSkillId === id) setActiveSkillId(null);
  };
  const saveNode = (nodeData) => {
    if (!activeSkill) return;
    const exists = (activeSkill.nodes||[]).some(n => n.id === nodeData.id);
    const newNodes = exists
      ? activeSkill.nodes.map(n => n.id === nodeData.id ? { ...n, ...nodeData } : n)
      : [...(activeSkill.nodes||[]), { ...nodeData, sessions: 0 }];
    setSkills(ss => ss.map(s => s.id === activeSkill.id ? { ...s, nodes: newNodes } : s));
  };
  const deleteNode = (id) => {
    if (!activeSkill) return;
    // Удаляем сам узел и всех потомков
    const toDelete = new Set([id]);
    let changed = true;
    while (changed) {
      changed = false;
      activeSkill.nodes.forEach(n => {
        if (toDelete.has(n.parentId) && !toDelete.has(n.id)) {
          toDelete.add(n.id); changed = true;
        }
      });
    }
    const newNodes = activeSkill.nodes.filter(n => !toDelete.has(n.id));
    setSkills(ss => ss.map(s => s.id === activeSkill.id ? { ...s, nodes: newNodes } : s));
  };

  // Корневые узлы — у которых нет parentId
  const rootNodes = (activeSkill?.nodes || []).filter(n => !n.parentId);

  return (
    <div style={{ maxWidth: 980, margin:"0 auto", padding:"20px 16px" }}>
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:20 }}>
        <div>
          <div className="eyebrow">Древо развития</div>
          <h1 style={{ margin:"4px 0 0" }}>Навыки</h1>
        </div>
        <button className="ss-btn" onClick={()=>setSkillModal({ mode:"new" })}>+ Новый навык</button>
      </div>

      {flowActive && (
        <div style={{ marginBottom:16, padding:"10px 14px", background:"rgba(96,165,250,0.12)", border:"1px solid #60a5fa", borderRadius:10, fontSize:13, color:"#60a5fa" }}>
          🌊 Активен Поток — все XP за разблокировку узлов удваиваются ×2
        </div>
      )}

      {(!skills || skills.length === 0) && (
        <div style={{ textAlign:"center", padding:"60px 0", color:"var(--text-3)" }}>
          <div style={{ fontSize:48, marginBottom:12 }}>🌳</div>
          <div style={{ fontSize:15, marginBottom:8 }}>У тебя пока нет навыков</div>
          <div style={{ fontSize:12, marginBottom:16 }}>Создай первый — например, «Здоровье» или «Программирование»</div>
          <button className="ss-btn" onClick={()=>setSkillModal({ mode:"new" })}>+ Создать навык</button>
        </div>
      )}

      {/* Сетка навыков (если не выбран ни один — показываем все как карточки) */}
      {!activeSkillId && skills && skills.length > 0 && (
        <div style={{ display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(260px, 1fr))", gap:12 }}>
          {skills.map(s => {
            const prog = skillProgress(s);
            const lvl = skillLevel(s);
            return (
              <div key={s.id}
                onClick={()=>setActiveSkillId(s.id)}
                className="ss-card"
                style={{ padding:"16px 18px", cursor:"pointer", border:`1px solid ${s.color||"var(--line-2)"}`,
                  transition:"transform 0.15s, box-shadow 0.15s" }}
                onMouseEnter={e=>{ e.currentTarget.style.transform="translateY(-2px)"; e.currentTarget.style.boxShadow=`0 4px 16px ${s.color}40`; }}
                onMouseLeave={e=>{ e.currentTarget.style.transform="none"; e.currentTarget.style.boxShadow="none"; }}>
                <div style={{ display:"flex", alignItems:"center", gap:10, marginBottom:10 }}>
                  <div style={{ width:42, height:42, borderRadius:10, background:`color-mix(in oklab, ${s.color} 25%, transparent)`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:22 }}>
                    {s.icon || "🌳"}
                  </div>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:15, fontWeight:700 }}>{s.title}</div>
                    <div style={{ fontSize:11, color:"var(--text-3)" }}>Уровень {lvl.level} • {lvl.totalXp} XP</div>
                  </div>
                </div>
                {s.description && <div style={{ fontSize:11, color:"var(--text-3)", marginBottom:8 }}>{s.description}</div>}
                <div style={{ height:6, background:"var(--bg-2)", borderRadius:3, overflow:"hidden", marginBottom:5 }}>
                  <div style={{ height:"100%", width:`${prog.pct}%`, background:s.color, transition:"width 0.4s" }}/>
                </div>
                <div style={{ display:"flex", justifyContent:"space-between", fontSize:11, color:"var(--text-3)" }}>
                  <span>{prog.done}/{prog.total} узлов</span>
                  <span>{prog.pct}%</span>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Активный навык — древо */}
      {activeSkill && (
        <div>
          <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:16, padding:"14px 16px", background:`color-mix(in oklab, ${activeSkill.color} 10%, var(--bg-4))`, borderRadius:12, border:`1px solid ${activeSkill.color}` }}>
            <button onClick={()=>setActiveSkillId(null)}
              style={{ padding:"6px 10px", background:"var(--bg-3)", border:"1px solid var(--line-2)", borderRadius:6, cursor:"pointer", color:"var(--text-2)", fontSize:12 }}>← Назад</button>
            <div style={{ width:48, height:48, borderRadius:12, background:`color-mix(in oklab, ${activeSkill.color} 30%, transparent)`, display:"flex", alignItems:"center", justifyContent:"center", fontSize:26 }}>
              {activeSkill.icon}
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:18, fontWeight:700 }}>{activeSkill.title}</div>
              <div style={{ fontSize:12, color:"var(--text-3)" }}>
                Уровень {skillLevel(activeSkill).level} • {skillProgress(activeSkill).done}/{skillProgress(activeSkill).total} узлов открыто
              </div>
            </div>
            <button onClick={()=>setSkillModal({ mode:"edit", skill: activeSkill })}
              style={{ padding:"6px 12px", background:"var(--bg-3)", border:"1px solid var(--line-2)", borderRadius:6, cursor:"pointer", color:"var(--text-2)", fontSize:12 }}>✎ Редактировать</button>
            <button className="ss-btn" onClick={()=>setNodeModal({ mode:"new" })}>+ Узел</button>
          </div>

          {activeSkill.notes && (
            <div style={{ padding:"10px 14px", marginBottom:14, background:"var(--bg-4)", borderLeft:`3px solid ${activeSkill.color}`, borderRadius:6, fontSize:12, color:"var(--text-2)", whiteSpace:"pre-wrap" }}>
              📝 {activeSkill.notes}
            </div>
          )}

          {rootNodes.length === 0 && (
            <div style={{ textAlign:"center", padding:"50px 0", color:"var(--text-3)" }}>
              <div style={{ fontSize:36, marginBottom:8 }}>🌱</div>
              <div style={{ fontSize:14, marginBottom:14 }}>Нет узлов в этом навыке</div>
              <button className="ss-btn" onClick={()=>setNodeModal({ mode:"new" })}>+ Добавить первый узел</button>
            </div>
          )}

          {/* Дерево узлов */}
          <div>
            {rootNodes.map(n => (
              <SkillNode key={n.id} node={n} allNodes={activeSkill.nodes} color={activeSkill.color}
                onComplete={addSession} onAdjustXp={adjustNodeXp}
                onAddChild={(parent)=>setNodeModal({ mode:"child", parent })}
                onEdit={(node)=>setNodeModal({ mode:"edit", node })}
                flowActive={flowActive}
                xpButtonAmount={activeSkill.xpButtonAmount || 25} />
            ))}
          </div>
        </div>
      )}

      {/* Модалки */}
      {skillModal && (
        <SkillModal skill={skillModal.skill} onSave={saveSkill} onDelete={deleteSkill}
          onClose={()=>setSkillModal(null)} />
      )}
      {nodeModal && (
        <NodeModal node={nodeModal.node} parentNode={nodeModal.parent}
          onSave={saveNode} onDelete={deleteNode}
          onClose={()=>setNodeModal(null)} />
      )}
    </div>
  );
};
