/* ============================================================
   BridgeOS — Skills Tab
   ============================================================ */

const SKILL_DB = [
  { name: "Guitar", icon: "🎸", cat: "Music" },
  { name: "Piano / Keys", icon: "🎹", cat: "Music" },
  { name: "Drums", icon: "🥁", cat: "Music" },
  { name: "Violin", icon: "🎻", cat: "Music" },
  { name: "Singing", icon: "🎤", cat: "Music" },
  { name: "Music Theory", icon: "🎼", cat: "Music" },
  { name: "DJing", icon: "🎧", cat: "Music" },
  { name: "Beat Making / Production", icon: "🎛️", cat: "Music" },
  { name: "Bass Guitar", icon: "🎸", cat: "Music" },
  { name: "Spanish", icon: "🇪🇸", cat: "Languages" },
  { name: "French", icon: "🇫🇷", cat: "Languages" },
  { name: "Portuguese", icon: "🇧🇷", cat: "Languages" },
  { name: "Japanese", icon: "🇯🇵", cat: "Languages" },
  { name: "Chinese (Mandarin)", icon: "🇨🇳", cat: "Languages" },
  { name: "German", icon: "🇩🇪", cat: "Languages" },
  { name: "Arabic", icon: "🇸🇦", cat: "Languages" },
  { name: "Italian", icon: "🇮🇹", cat: "Languages" },
  { name: "Russian", icon: "🇷🇺", cat: "Languages" },
  { name: "Korean", icon: "🇰🇷", cat: "Languages" },
  { name: "Drawing / Sketching", icon: "✏️", cat: "Art & Design" },
  { name: "Digital Art", icon: "🖥️", cat: "Art & Design" },
  { name: "Painting", icon: "🎨", cat: "Art & Design" },
  { name: "Graphic Design", icon: "📐", cat: "Art & Design" },
  { name: "Photography", icon: "📷", cat: "Art & Design" },
  { name: "Videography / Editing", icon: "🎬", cat: "Art & Design" },
  { name: "Animation", icon: "🎥", cat: "Art & Design" },
  { name: "3D Modeling", icon: "🧊", cat: "Art & Design" },
  { name: "Python", icon: "🐍", cat: "Coding" },
  { name: "JavaScript / Web Dev", icon: "💻", cat: "Coding" },
  { name: "React / Frontend", icon: "⚛️", cat: "Coding" },
  { name: "Machine Learning / AI", icon: "🤖", cat: "Coding" },
  { name: "Cybersecurity", icon: "🔐", cat: "Coding" },
  { name: "Game Development", icon: "🎮", cat: "Coding" },
  { name: "Mobile Dev (iOS/Android)", icon: "📱", cat: "Coding" },
  { name: "Backend / APIs", icon: "⚙️", cat: "Coding" },
  { name: "Boxing", icon: "🥊", cat: "Martial Arts" },
  { name: "Muay Thai", icon: "🦵", cat: "Martial Arts" },
  { name: "BJJ / Jiu Jitsu", icon: "🥋", cat: "Martial Arts" },
  { name: "Wrestling / Grappling", icon: "🤼", cat: "Martial Arts" },
  { name: "MMA", icon: "⚡", cat: "Martial Arts" },
  { name: "Karate", icon: "🥋", cat: "Martial Arts" },
  { name: "Judo", icon: "🥋", cat: "Martial Arts" },
  { name: "Taekwondo", icon: "🦵", cat: "Martial Arts" },
  { name: "Gymnastics", icon: "🤸", cat: "Athletics" },
  { name: "Parkour / Freerunning", icon: "🏃", cat: "Athletics" },
  { name: "Yoga", icon: "🧘", cat: "Athletics" },
  { name: "Tennis", icon: "🎾", cat: "Athletics" },
  { name: "Golf", icon: "⛳", cat: "Athletics" },
  { name: "Skateboarding", icon: "🛹", cat: "Athletics" },
  { name: "Rock Climbing", icon: "🧗", cat: "Athletics" },
  { name: "Swimming", icon: "🏊", cat: "Athletics" },
  { name: "Basketball", icon: "🏀", cat: "Athletics" },
  { name: "Soccer / Football", icon: "⚽", cat: "Athletics" },
  { name: "Carpentry / Woodwork", icon: "🪚", cat: "Trades" },
  { name: "Welding", icon: "🔥", cat: "Trades" },
  { name: "Electrical", icon: "⚡", cat: "Trades" },
  { name: "Plumbing", icon: "🔧", cat: "Trades" },
  { name: "Automotive / Mechanics", icon: "🚗", cat: "Trades" },
  { name: "Leatherwork", icon: "🧵", cat: "Trades" },
  { name: "Blacksmithing", icon: "⚒️", cat: "Trades" },
  { name: "Chess", icon: "♟️", cat: "Mind" },
  { name: "Public Speaking", icon: "🎙️", cat: "Mind" },
  { name: "Writing / Storytelling", icon: "📝", cat: "Mind" },
  { name: "Memory Techniques", icon: "🧠", cat: "Mind" },
  { name: "Speed Reading", icon: "📖", cat: "Mind" },
  { name: "Math / Problem Solving", icon: "📊", cat: "Mind" },
  { name: "Philosophy / Logic", icon: "🔭", cat: "Mind" },
  { name: "Cooking", icon: "👨‍🍳", cat: "Life Skills" },
  { name: "Lockpicking", icon: "🔓", cat: "Life Skills" },
  { name: "Knot Tying", icon: "🪢", cat: "Life Skills" },
  { name: "First Aid / Medical", icon: "🩺", cat: "Life Skills" },
  { name: "Magic / Card Tricks", icon: "🃏", cat: "Life Skills" },
  { name: "Origami", icon: "🦢", cat: "Life Skills" },
  { name: "Sales / Persuasion", icon: "💬", cat: "Business" },
  { name: "Copywriting", icon: "✍️", cat: "Business" },
  { name: "Trading / Investing", icon: "📈", cat: "Business" },
  { name: "Video Editing", icon: "🎬", cat: "Business" },
  { name: "SEO / Marketing", icon: "📣", cat: "Business" },
  { name: "Custom", icon: "⭐", cat: "Other" },
];
const SKILL_CATS = ["All", ...Array.from(new Set(SKILL_DB.map((s) => s.cat)))];

function SkillsView({ me, updateMe, today }) {
  const P = window.PP;
  const skills = Object.values(me.skills || {});
  const history = me.skillHistory || [];
  const [view, setView] = useState("list"); // "list" | skill-id
  const [addOpen, setAddOpen] = useState(false);
  const [logOpen, setLogOpen] = useState(null); // skill id or "manual"

  const activeSkill = view !== "list" ? (me.skills || {})[view] : null;
  const goals = me.skillGoals || { weeklyMin: 600, totalMin: 36000 };

  function fmtMin(m) {
    m = Number(m) || 0;
    if (m >= 60) { const h = Math.floor(m / 60), rm = m % 60; return h + "h" + (rm > 0 ? " " + rm + "m" : ""); }
    return m + "m";
  }

  // minutes logged per skill
  function skillMins(skillId) {
    return history.filter((e) => e.skillId === skillId).reduce((s, e) => s + (e.min || 0), 0);
  }
  // minutes this week per skill
  function skillMinsThisWeek(skillId) {
    const ws = P.weekStart(today);
    return history.filter((e) => e.skillId === skillId && e.iso >= ws).reduce((s, e) => s + (e.min || 0), 0);
  }
  // broad totals across ALL skills
  const allTotalMins = history.reduce((s, e) => s + (e.min || 0), 0);
  const allWeekMins = history.filter((e) => e.iso >= P.weekStart(today)).reduce((s, e) => s + (e.min || 0), 0);

  function setGoal(field) {
    const cur = goals[field];
    const label = field === "weeklyMin" ? "Weekly goal — total minutes across all skills (e.g. 600 = 10h):" : "All-time total goal — total minutes (e.g. 36000 = 600h):";
    const v = prompt(label, cur);
    if (v === null) return;
    const n = Number(v);
    if (!n || n < 1) return;
    updateMe((m) => { m.skillGoals = Object.assign({}, m.skillGoals || {}, { [field]: n }); });
  }
  // sessions last 60 days (for mini bar)
  function skillDayBars(skillId, n) {
    const bars = [];
    for (let i = n - 1; i >= 0; i--) {
      const iso = P.addDays(today, -i);
      const mins = history.filter((e) => e.skillId === skillId && e.iso === iso).reduce((s, e) => s + (e.min || 0), 0);
      bars.push({ iso, mins });
    }
    return bars;
  }

  function addSkill(name, icon) {
    const id = "sk_" + Date.now().toString(36);
    updateMe((m) => {
      if (!m.skills) m.skills = {};
      m.skills[id] = { id, name, icon, targetMinWeek: 600, notes: "", media: [] };
    });
    setAddOpen(false);
  }

  function deleteSkill(skillId) {
    if (!confirm("Delete this skill and all its history?")) return;
    updateMe((m) => {
      delete m.skills[skillId];
      m.skillHistory = (m.skillHistory || []).filter((e) => e.skillId !== skillId);
    });
    setView("list");
  }

  function logSession(skillId, iso, min, what, notes) {
    const id = "sh_" + Date.now().toString(36);
    updateMe((m) => {
      if (!m.skillHistory) m.skillHistory = [];
      m.skillHistory.push({ id, skillId, iso, min: Number(min) || 0, what: what || "", notes: notes || "" });
    });
    setLogOpen(null);
  }

  function deleteEntry(entryId) {
    updateMe((m) => { m.skillHistory = (m.skillHistory || []).filter((e) => e.id !== entryId); });
  }

  function addPhoto(skillId, dataUrl) {
    updateMe((m) => {
      const sk = m.skills[skillId];
      if (!sk) return;
      if (!sk.media) sk.media = [];
      sk.media.push({ id: "sm_" + Date.now().toString(36), type: "photo", data: dataUrl, caption: "", iso: today });
    });
  }

  function addVideoLink(skillId, url, title) {
    updateMe((m) => {
      const sk = m.skills[skillId];
      if (!sk) return;
      if (!sk.media) sk.media = [];
      sk.media.push({ id: "sm_" + Date.now().toString(36), type: "link", url: url.trim(), title: title.trim() || url.trim(), iso: today });
    });
  }

  function deletePhoto(skillId, mediaId) {
    updateMe((m) => {
      const sk = m.skills[skillId];
      if (sk && sk.media) sk.media = sk.media.filter((x) => x.id !== mediaId);
    });
  }

  function updateSkillField(skillId, field, value) {
    updateMe((m) => { if (m.skills[skillId]) m.skills[skillId][field] = value; });
  }

  if (activeSkill) {
    return <SkillDetail
      skill={activeSkill}
      onAddVideoLink={(url, title) => addVideoLink(activeSkill.id, url, title)}
      history={history.filter((e) => e.skillId === activeSkill.id)}
      today={today}
      skillMins={skillMins(activeSkill.id)}
      skillMinsThisWeek={skillMinsThisWeek(activeSkill.id)}
      skillDayBars={(n) => skillDayBars(activeSkill.id, n)}
      onBack={() => setView("list")}
      onLogSession={(iso, min, what, notes) => logSession(activeSkill.id, iso, min, what, notes)}
      onDeleteEntry={deleteEntry}
      onDelete={() => deleteSkill(activeSkill.id)}
      onAddPhoto={(url) => addPhoto(activeSkill.id, url)}
      onDeletePhoto={(mid) => deletePhoto(activeSkill.id, mid)}
      onUpdateField={(f, v) => updateSkillField(activeSkill.id, f, v)}
    />;
  }

  return (
    <div className="skills-wrap">
      <div className="skills-header">
        <div>
          <div className="page-title">Skills</div>
          <div className="dim" style={{ fontSize: 13, marginTop: 2 }}>Track your practice, level up your craft.</div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn btn-sm btn-accent" onClick={() => setAddOpen(true)}>+ Add Skill</button>
          {skills.length > 0 && <button className="btn btn-sm" onClick={() => setLogOpen("manual")}>+ Log Session</button>}
        </div>
      </div>

      {(allTotalMins > 0 || skills.length > 0) && (
        <div className="skill-overview">
          <div className="skill-ov-item">
            <div className="skill-ov-top">
              <span className="skill-ov-label mono">THIS WEEK</span>
              <span className="skill-ov-nums"><b className="mono">{fmtMin(allWeekMins)}</b> <span className="dim">/ </span><button className="skill-ov-goal" onClick={() => setGoal("weeklyMin")}>{fmtMin(goals.weeklyMin)} goal ✎</button></span>
            </div>
            <div className="skill-ov-bar"><div className="skill-ov-fill" style={{ width: Math.min(100, goals.weeklyMin > 0 ? (allWeekMins / goals.weeklyMin) * 100 : 0) + "%" }} /></div>
            <div className="skill-ov-pct mono">{goals.weeklyMin > 0 ? Math.round((allWeekMins / goals.weeklyMin) * 100) : 0}%</div>
          </div>
          <div className="skill-ov-item">
            <div className="skill-ov-top">
              <span className="skill-ov-label mono">ALL TIME</span>
              <span className="skill-ov-nums"><b className="mono">{fmtMin(allTotalMins)}</b> <span className="dim">/ </span><button className="skill-ov-goal" onClick={() => setGoal("totalMin")}>{fmtMin(goals.totalMin)} goal ✎</button></span>
            </div>
            <div className="skill-ov-bar"><div className="skill-ov-fill" style={{ width: Math.min(100, goals.totalMin > 0 ? (allTotalMins / goals.totalMin) * 100 : 0) + "%" }} /></div>
            <div className="skill-ov-pct mono">{goals.totalMin > 0 ? Math.round((allTotalMins / goals.totalMin) * 100) : 0}%</div>
          </div>
        </div>
      )}

      {skills.length === 0 ? (
        <div className="skills-empty">
          <div style={{ fontSize: 48, marginBottom: 12 }}>🎯</div>
          <div style={{ fontSize: 18, fontWeight: 700, marginBottom: 6 }}>No skills tracked yet</div>
          <div className="dim" style={{ marginBottom: 18 }}>Add a skill to start tracking your practice time, progress, and journey.</div>
          <button className="btn btn-accent" onClick={() => setAddOpen(true)}>Add your first skill</button>
        </div>
      ) : (
        <div className="skills-grid">
          {skills.map((sk) => {
            const totalMins = skillMins(sk.id);
            const weekMins = skillMinsThisWeek(sk.id);
            const bars = skillDayBars(sk.id, 30);
            const maxBar = Math.max(1, ...bars.map((b) => b.mins));
            const weekPct = sk.targetMinWeek > 0 ? Math.min(1, weekMins / sk.targetMinWeek) : 0;
            return (
              <button key={sk.id} className="skill-card" onClick={() => setView(sk.id)}>
                <div className="skill-card-icon">{sk.icon}</div>
                <div className="skill-card-name">{sk.name}</div>
                <div className="skill-card-stats">
                  <span className="mono">{totalMins >= 60 ? Math.floor(totalMins / 60) + "h " + (totalMins % 60) + "m" : totalMins + "m"} total</span>
                  <span className="dim">·</span>
                  <span className="mono">{weekMins >= 60 ? Math.floor(weekMins / 60) + "h" : weekMins + "m"} this week</span>
                </div>
                {sk.targetMinWeek > 0 && (
                  <div className="skill-week-bar">
                    <div className="skill-week-fill" style={{ width: (weekPct * 100) + "%" }} />
                    <span className="skill-week-label mono">{Math.round(weekPct * 100)}% of {sk.targetMinWeek >= 60 ? Math.floor(sk.targetMinWeek / 60) + "h" : sk.targetMinWeek + "m"}/wk goal</span>
                  </div>
                )}
                <div className="skill-mini-bars">
                  {bars.map((b, i) => (
                    <div key={i} className={"skill-mini-bar" + (b.iso === today ? " today" : "")} style={{ height: Math.max(2, (b.mins / maxBar) * 36) + "px", opacity: b.mins > 0 ? 1 : 0.18 }} title={b.iso + ": " + b.mins + "m"} />
                  ))}
                </div>
              </button>
            );
          })}
        </div>
      )}

      {addOpen && <AddSkillModal onClose={() => setAddOpen(false)} onAdd={addSkill} existingNames={skills.map((s) => s.name)} />}
      {logOpen === "manual" && <LogSessionModal skills={skills} today={today} onClose={() => setLogOpen(null)} onSave={(skillId, iso, min, what, notes) => logSession(skillId, iso, min, what, notes)} />}
    </div>
  );
}

function ytEmbedUrl(url) {
  try {
    const u = new URL(url);
    if (u.hostname.includes("youtube.com")) {
      const id = u.searchParams.get("v") || u.pathname.split("/").pop();
      if (id) return "https://www.youtube.com/embed/" + id;
    }
    if (u.hostname === "youtu.be") {
      return "https://www.youtube.com/embed/" + u.pathname.slice(1);
    }
  } catch (_) {}
  return null;
}

function SkillDetail({ skill, history, today, skillMins, skillMinsThisWeek, skillDayBars, onBack, onLogSession, onDeleteEntry, onDelete, onAddPhoto, onDeletePhoto, onAddVideoLink, onUpdateField }) {
  const P = window.PP;
  const [logOpen, setLogOpen] = useState(false);
  const [editNotes, setEditNotes] = useState(false);
  const [notes, setNotes] = useState(skill.notes || "");
  const [chartView, setChartView] = useState("30d"); // "30d" | "3m" | "all"
  const [linkForm, setLinkForm] = useState(false);
  const [linkUrl, setLinkUrl] = useState("");
  const [linkTitle, setLinkTitle] = useState("");
  const fileRef = useRef(null);

  const n = chartView === "30d" ? 30 : chartView === "3m" ? 90 : Math.max(90, history.length > 0 ? P.daysBetween(history[0].iso, today) + 1 : 90);
  const bars = skillDayBars(n);
  const maxBar = Math.max(1, ...bars.map((b) => b.mins));
  const sortedHistory = [...history].sort((a, b) => (b.iso > a.iso ? 1 : -1));
  const totalMins = skillMins;
  const weekMins = skillMinsThisWeek;
  const sessionCount = history.length;

  function handleFiles(files) {
    Array.from(files).forEach((file) => {
      const reader = new FileReader();
      reader.onload = (ev) => {
        const img = new Image();
        img.onload = () => {
          const max = 1100;
          let { width, height } = img;
          if (width > max || height > max) { const s = max / Math.max(width, height); width *= s; height *= s; }
          const c = document.createElement("canvas");
          c.width = width; c.height = height;
          c.getContext("2d").drawImage(img, 0, 0, width, height);
          onAddPhoto(c.toDataURL("image/jpeg", 0.82));
        };
        img.src = ev.target.result;
      };
      reader.readAsDataURL(file);
    });
  }

  return (
    <div className="skill-detail">
      <div className="skill-detail-head">
        <button className="btn btn-sm" onClick={onBack}>← Back</button>
        <div className="skill-detail-title">
          <span style={{ fontSize: 28 }}>{skill.icon}</span>
          <span>{skill.name}</span>
        </div>
        <button className="btn btn-sm btn-accent" onClick={() => setLogOpen(true)}>+ Log Session</button>
      </div>

      {/* stats row */}
      <div className="skill-stats-row">
        <div className="skill-stat-box">
          <div className="skill-stat-val mono">{totalMins >= 60 ? Math.floor(totalMins / 60) + "h " + (totalMins % 60) + "m" : totalMins + "m"}</div>
          <div className="skill-stat-key">Total</div>
        </div>
        <div className="skill-stat-box">
          <div className="skill-stat-val mono">{weekMins >= 60 ? Math.floor(weekMins / 60) + "h " + (weekMins % 60) + "m" : weekMins + "m"}</div>
          <div className="skill-stat-key">This week</div>
        </div>
        <div className="skill-stat-box">
          <div className="skill-stat-val mono">{sessionCount}</div>
          <div className="skill-stat-key">Sessions</div>
        </div>
        <div className="skill-stat-box">
          <div className="skill-stat-val mono">{totalMins >= 60 ? (totalMins / 60).toFixed(1) + "h" : totalMins + "m"}</div>
          <div className="skill-stat-key">Practice time</div>
        </div>
      </div>

      {/* weekly goal bar */}
      {skill.targetMinWeek > 0 && (
        <div className="skill-goal-row">
          <span className="dim" style={{ fontSize: 12 }}>Weekly goal: {skill.targetMinWeek >= 60 ? Math.floor(skill.targetMinWeek / 60) + "h" : skill.targetMinWeek + "m"}</span>
          <div className="skill-goal-bar">
            <div className="skill-goal-fill" style={{ width: Math.min(100, (weekMins / skill.targetMinWeek) * 100) + "%" }} />
          </div>
          <span className="mono dim" style={{ fontSize: 12 }}>{Math.round((weekMins / skill.targetMinWeek) * 100)}%</span>
          <button className="mini-btn" onClick={() => {
            const v = prompt("Weekly goal (minutes)", skill.targetMinWeek);
            if (v) onUpdateField("targetMinWeek", Number(v));
          }}>Edit</button>
        </div>
      )}

      {/* chart */}
      <div className="skill-chart-wrap">
        <div className="skill-chart-head">
          <span className="dd-section-label">PRACTICE HISTORY</span>
          <div style={{ display: "flex", gap: 6 }}>
            {["30d", "3m", "all"].map((v) => <button key={v} className={"chip" + (chartView === v ? " on" : "")} style={{ fontSize: 11, padding: "3px 9px" }} onClick={() => setChartView(v)}>{v}</button>)}
          </div>
        </div>
        <div className="skill-chart">
          {bars.map((b, i) => (
            <div key={i} className="skill-bar-col" title={b.iso + ": " + b.mins + "m"}>
              <div className={"skill-bar" + (b.iso === today ? " today" : "")} style={{ height: Math.max(2, (b.mins / maxBar) * 80) + "px", opacity: b.mins > 0 ? 1 : 0.13 }} />
            </div>
          ))}
        </div>
      </div>

      {/* session log */}
      <div className="skill-section">
        <div className="dd-section-label" style={{ marginBottom: 8 }}>SESSION LOG ({sortedHistory.length})</div>
        {sortedHistory.length === 0 ? (
          <div className="dim" style={{ fontSize: 13 }}>No sessions logged yet. Hit "+ Log Session" to start.</div>
        ) : (
          <div className="skill-log-list">
            {sortedHistory.map((entry) => (
              <div key={entry.id} className="skill-log-entry">
                <div className="skill-log-left">
                  <div className="skill-log-date mono">{P.prettyDate(entry.iso)}</div>
                  <div className="skill-log-mins mono">{entry.min >= 60 ? Math.floor(entry.min / 60) + "h " + (entry.min % 60) + "m" : entry.min + "m"}</div>
                </div>
                <div className="skill-log-right">
                  {entry.what && <div className="skill-log-what">{entry.what}</div>}
                  {entry.notes && <div className="skill-log-notes dim">{entry.notes}</div>}
                </div>
                <button className="mini-btn" style={{ color: "var(--dim)", marginLeft: "auto" }} onClick={() => { if (confirm("Delete this session?")) onDeleteEntry(entry.id); }}>✕</button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* media: photos + video links */}
      <div className="skill-section">
        <div className="dd-section-label" style={{ marginBottom: 8 }}>
          PROGRESS MEDIA
          <button className="mini-btn" style={{ marginLeft: 10 }} onClick={() => fileRef.current.click()}>+ Photo</button>
          <button className="mini-btn" style={{ marginLeft: 6 }} onClick={() => { setLinkForm(true); setLinkUrl(""); setLinkTitle(""); }}>+ Video / Link</button>
        </div>
        <input ref={fileRef} type="file" accept="image/*" multiple style={{ display: "none" }} onChange={(e) => handleFiles(e.target.files)} />
        {linkForm && (
          <div className="skill-link-form">
            <input className="inp" autoFocus placeholder="Paste YouTube or any URL..." value={linkUrl} onChange={(e) => setLinkUrl(e.target.value)} style={{ marginBottom: 6 }} />
            <input className="inp" placeholder="Title / caption (optional)" value={linkTitle} onChange={(e) => setLinkTitle(e.target.value)} style={{ marginBottom: 8 }} />
            <div style={{ display: "flex", gap: 8 }}>
              <button className="btn btn-accent btn-sm" disabled={!linkUrl.trim()} onClick={() => { onAddVideoLink(linkUrl, linkTitle); setLinkForm(false); }}>Add</button>
              <button className="btn btn-sm" onClick={() => setLinkForm(false)}>Cancel</button>
            </div>
          </div>
        )}
        {(!skill.media || skill.media.length === 0) && !linkForm ? (
          <div className="dd-photo-drop" onClick={() => fileRef.current.click()}>Click to upload photos, or use + Video / Link above</div>
        ) : (
          <div className="dd-photos">
            {(skill.media || []).map((item) => {
              if (item.type === "link") {
                const embed = ytEmbedUrl(item.url);
                return (
                  <div key={item.id} className="dd-photo skill-link-card">
                    {embed ? (
                      <iframe src={embed} frameBorder={0} allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen style={{ width: "100%", height: "100%", borderRadius: 6, display: "block" }} />
                    ) : (
                      <a href={item.url} target="_blank" rel="noopener noreferrer" className="skill-link-preview">
                        <span style={{ fontSize: 28 }}>🔗</span>
                        <span className="skill-link-title">{item.title || item.url}</span>
                      </a>
                    )}
                    <button className="photo-del" onClick={() => onDeletePhoto(item.id)}>✕</button>
                    <div className="photo-cap mono" style={{ fontSize: 10 }}>{item.iso}</div>
                  </div>
                );
              }
              return (
                <div key={item.id} className="dd-photo">
                  <img src={item.data} alt="" />
                  <button className="photo-del" onClick={() => onDeletePhoto(item.id)}>✕</button>
                  <div className="photo-cap mono" style={{ fontSize: 10 }}>{item.iso}</div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* notes */}
      <div className="skill-section">
        <div className="dd-section-label" style={{ marginBottom: 8 }}>NOTES & RESOURCES</div>
        <textarea
          className="ta"
          rows={4}
          value={notes}
          placeholder={"Resources, goals, technique notes, links..."}
          onChange={(e) => setNotes(e.target.value)}
          onBlur={() => onUpdateField("notes", notes)}
        />
      </div>

      {/* danger zone */}
      <div style={{ marginTop: 24, paddingTop: 16, borderTop: "1px solid var(--line)" }}>
        <button className="btn btn-danger" onClick={onDelete}>Delete skill</button>
      </div>

      {logOpen && <LogSessionModal skills={[skill]} defaultSkillId={skill.id} today={today} onClose={() => setLogOpen(false)} onSave={(sid, iso, min, what, notes) => { onLogSession(iso, min, what, notes); setLogOpen(false); }} />}
    </div>
  );
}

function AddSkillModal({ onClose, onAdd, existingNames }) {
  const [cat, setCat] = useState("All");
  const [q, setQ] = useState("");
  const [customName, setCustomName] = useState("");
  const [customIcon, setCustomIcon] = useState("⭐");

  const filtered = SKILL_DB.filter((s) => {
    if (existingNames.includes(s.name)) return false;
    if (cat !== "All" && s.cat !== cat) return false;
    if (q && !s.name.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  return (
    <Modal open wide onClose={onClose} title="Add a skill">
      <div className="stack">
        <input className="inp" placeholder="Search skills..." value={q} autoFocus onChange={(e) => setQ(e.target.value)} />
        <div className="picker-groups">
          {SKILL_CATS.map((c) => <button key={c} className={"chip" + (cat === c ? " on" : "")} onClick={() => setCat(c)}>{c}</button>)}
        </div>
        <div className="picker-list" style={{ maxHeight: 260 }}>
          {filtered.map((s) => (
            <button key={s.name} className="picker-item" onClick={() => onAdd(s.name, s.icon)}>
              <span style={{ fontSize: 20, marginRight: 10 }}>{s.icon}</span>
              <span className="picker-item-name">{s.name}</span>
              <span className="picker-item-meta mono dim">{s.cat}</span>
              <span className="picker-add">+</span>
            </button>
          ))}
          {filtered.length === 0 && <div className="dim" style={{ padding: 16, textAlign: "center" }}>No skills match. Add a custom one below.</div>}
        </div>
        <div style={{ borderTop: "1px solid var(--line)", paddingTop: 12 }}>
          <div className="dd-section-label" style={{ marginBottom: 8 }}>CUSTOM SKILL</div>
          <div className="row2">
            <Field label="Icon (emoji)"><input className="inp" value={customIcon} onChange={(e) => setCustomIcon(e.target.value)} style={{ width: 64 }} /></Field>
            <Field label="Skill name"><input className="inp" value={customName} placeholder="e.g. Lockpicking" onChange={(e) => setCustomName(e.target.value)} /></Field>
          </div>
          <button className="btn btn-accent" style={{ marginTop: 8 }} disabled={!customName.trim()} onClick={() => onAdd(customName.trim(), customIcon || "⭐")}>Add custom skill</button>
        </div>
      </div>
    </Modal>
  );
}

function LogSessionModal({ skills, defaultSkillId, today, onClose, onSave }) {
  const [skillId, setSkillId] = useState(defaultSkillId || (skills[0] && skills[0].id) || "");
  const [iso, setIso] = useState(today);
  const [hrs, setHrs] = useState(0);
  const [mins, setMins] = useState(30);
  const [what, setWhat] = useState("");
  const [notes, setNotes] = useState("");

  const totalMin = Number(hrs) * 60 + Number(mins);

  return (
    <Modal open onClose={onClose} title="Log skill session"
      footer={<button className="btn btn-accent" disabled={!skillId || totalMin < 1} onClick={() => onSave(skillId, iso, totalMin, what, notes)}>Save session</button>}>
      <div className="stack">
        {skills.length > 1 && (
          <Field label="Skill">
            <select className="inp" value={skillId} onChange={(e) => setSkillId(e.target.value)}>
              {skills.map((s) => <option key={s.id} value={s.id}>{s.icon} {s.name}</option>)}
            </select>
          </Field>
        )}
        <Field label="Date"><input className="inp" type="date" value={iso} onChange={(e) => setIso(e.target.value)} /></Field>
        <div className="row2">
          <Field label="Hours"><input className="inp" type="number" min={0} max={12} value={hrs} onChange={(e) => setHrs(e.target.value)} /></Field>
          <Field label="Minutes"><input className="inp" type="number" min={0} max={59} step={5} value={mins} onChange={(e) => setMins(e.target.value)} /></Field>
        </div>
        <Field label="What did you work on?"><input className="inp" value={what} placeholder="e.g. Practiced scales, chord transitions..." onChange={(e) => setWhat(e.target.value)} /></Field>
        <Field label="Notes (optional)"><textarea className="ta" rows={2} value={notes} placeholder="Any observations, breakthroughs, struggles..." onChange={(e) => setNotes(e.target.value)} /></Field>
      </div>
    </Modal>
  );
}

Object.assign(window, { SkillsView, SKILL_DB });
