// Admin dashboard — správa kategorií a úkolů

function AdminDashboardScreen({ palette, metaphor, age, playfulness, onBack }) {
  const [tick, setTick] = useState(0);
  const [selectedCat, setSelectedCat] = useState(CATEGORIES_META[0].id);
  const [editingTask, setEditingTask] = useState(null);
  const [confirmDelete, setConfirmDelete] = useState(null);
  const [confirmReset, setConfirmReset] = useState(false);

  const refresh = () => setTick(t => t + 1);

  const tasksInCat = useMemo(() => getTasksByCategory(selectedCat), [selectedCat, tick]);
  const categoryCounts = useMemo(() => {
    const counts = {};
    CATEGORIES_META.forEach(c => { counts[c.id] = getTasksByCategory(c.id).length; });
    return counts;
  }, [tick]);

  const totalTasks = useMemo(() => getAllTasks().length, [tick]);

  const cat = CATEGORIES_META.find(c => c.id === selectedCat);

  const handleSaveTask = (task) => {
    upsertTask(task);
    setEditingTask(null);
    refresh();
  };

  const handleDeleteTask = (id) => {
    deleteTask(id);
    setConfirmDelete(null);
    refresh();
  };

  const handleAddTask = () => {
    setEditingTask(newTaskTemplate(selectedCat));
  };

  const handleReset = () => {
    resetCatalog();
    setConfirmReset(false);
    refresh();
  };

  return (
    <div style={{ position: 'relative', minHeight: '100%', zIndex: 1, padding: '0 0 60px' }}>
      {/* Top bar */}
      <div style={{
        padding: '22px 20px 16px', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <motion.button whileTap={{ scale: 0.9 }} onClick={onBack} style={{
          width: 44, height: 44, borderRadius: 14, border: 'none',
          background: palette.card, boxShadow: playfulShadow(1), cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24">
            <path d="M15 6l-6 6 6 6" stroke={palette.ink} strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </motion.button>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 600,
            letterSpacing: '0.08em', textTransform: 'uppercase', color: palette.inkSoft,
          }}>Administrace</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 22, color: palette.ink, lineHeight: 1.1,
          }}>Katalog úkolů pro panďátka</div>
        </div>
        <PandickaChip size={36}/>
      </div>

      {/* Summary */}
      <div style={{
        padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginBottom: 16,
      }}>
        <SoftCard palette={palette} playfulness={playfulness} style={{ padding: '12px 14px' }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 10, color: palette.inkSoft,
            letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
          }}>Kategorií</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 24, fontWeight: 700, color: palette.ink, marginTop: 2,
          }}>{CATEGORIES_META.length}</div>
        </SoftCard>
        <SoftCard palette={palette} playfulness={playfulness} style={{ padding: '12px 14px' }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 10, color: palette.inkSoft,
            letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
          }}>Úkolů</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 24, fontWeight: 700, color: palette.ink, marginTop: 2,
          }}>{totalTasks}</div>
        </SoftCard>
        <SoftCard palette={palette} playfulness={playfulness} style={{ padding: '12px 14px' }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 10, color: palette.inkSoft,
            letterSpacing: '0.06em', textTransform: 'uppercase', fontWeight: 600,
          }}>Role</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 14, fontWeight: 700, color: palette.primaryDeep, marginTop: 6,
          }}>🛡️ Admin</div>
        </SoftCard>
      </div>

      {/* Category tabs */}
      <div style={{
        padding: '0 20px 14px',
        display: 'flex', gap: 8, overflowX: 'auto',
      }}>
        {CATEGORIES_META.map(c => (
          <button key={c.id} onClick={() => setSelectedCat(c.id)} style={{
            flexShrink: 0,
            padding: '10px 14px', borderRadius: 16,
            border: `2px solid ${selectedCat === c.id ? c.color : palette.ink + '18'}`,
            background: selectedCat === c.id ? c.color + '30' : palette.card,
            cursor: 'pointer',
            fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 13, color: palette.ink,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ fontSize: 16 }}>{c.icon}</span>
            {c.shortName}
            <span style={{
              padding: '1px 7px', borderRadius: 10,
              background: palette.ink + '15', fontSize: 11, fontWeight: 700,
            }}>{categoryCounts[c.id]}</span>
          </button>
        ))}
      </div>

      {/* Action bar */}
      <div style={{
        padding: '0 20px 14px', display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 18, color: palette.ink,
          }}>{cat.name}</div>
          <div style={{
            fontFamily: '"Baloo 2"', fontSize: 12, color: palette.inkSoft,
          }}>{tasksInCat.length} úkolů</div>
        </div>
        <BigButton palette={palette} variant="primary" size="sm" onClick={handleAddTask}
          icon={<span style={{ fontSize: 18, fontWeight: 800 }}>+</span>}>
          Nový úkol
        </BigButton>
      </div>

      {/* Task list */}
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {tasksInCat.length === 0 && (
          <SoftCard palette={palette} playfulness={playfulness}
            style={{ padding: 24, textAlign: 'center' }}>
            <div style={{ fontSize: 40, marginBottom: 8 }}>🐼</div>
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 14, color: palette.inkSoft,
            }}>Zatím žádné úkoly. Přidej první!</div>
          </SoftCard>
        )}
        {tasksInCat.map(t => (
          <SoftCard key={t.id} palette={palette} playfulness={1}
            style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: cat.color + '40', border: `1.5px solid ${cat.color}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 16, color: palette.ink,
              flexShrink: 0,
            }}>
              {t.boss ? '🎁' : t.level}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 14, color: palette.ink,
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>{t.title}</div>
              <div style={{
                fontFamily: '"Baloo 2"', fontSize: 11, color: palette.inkSoft, marginTop: 2,
                display: 'flex', gap: 6, flexWrap: 'wrap',
              }}>
                <span>⭐ {t.reward?.xp ?? 10} XP</span>
                <span>💰 {t.reward?.coins ?? 5}</span>
                <span>· {t.options?.length || 0} možností</span>
              </div>
            </div>
            <button onClick={() => setEditingTask(t)} style={{
              width: 36, height: 36, borderRadius: 10, border: `1.5px solid ${palette.ink}18`,
              background: palette.card, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }} title="Upravit">
              <span style={{ fontSize: 16 }}>✏️</span>
            </button>
            <button onClick={() => setConfirmDelete(t)} style={{
              width: 36, height: 36, borderRadius: 10, border: `1.5px solid ${palette.danger}40`,
              background: palette.danger + '15', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }} title="Smazat">
              <span style={{ fontSize: 16 }}>🗑️</span>
            </button>
          </SoftCard>
        ))}
      </div>

      {/* Reset section */}
      <div style={{ padding: '24px 20px 0' }}>
        <SoftCard palette={palette} playfulness={1}
          style={{
            padding: 14, display: 'flex', alignItems: 'center', gap: 12,
            background: palette.ink + '06',
          }}>
          <div style={{ fontSize: 28 }}>🌱</div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 14, color: palette.ink,
            }}>Obnovit výchozí katalog</div>
            <div style={{
              fontFamily: '"Baloo 2"', fontSize: 11, color: palette.inkSoft, marginTop: 2,
            }}>Smaže tvé vlastní úkoly a vrátí původní.</div>
          </div>
          <button onClick={() => setConfirmReset(true)} style={{
            padding: '8px 14px', borderRadius: 999, border: `1.5px solid ${palette.ink}20`,
            background: 'transparent', cursor: 'pointer',
            fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 12, color: palette.ink,
          }}>Reset</button>
        </SoftCard>
      </div>

      {/* Edit modal */}
      {editingTask && (
        <TaskEditModal
          palette={palette} playfulness={playfulness}
          task={editingTask}
          onSave={handleSaveTask}
          onCancel={() => setEditingTask(null)}
        />
      )}

      {/* Delete confirmation */}
      {confirmDelete && (
        <ConfirmModal palette={palette}
          title="Smazat úkol?"
          message={`Opravdu chceš smazat úkol „${confirmDelete.title}"?`}
          confirmLabel="Ano, smazat"
          confirmVariant="danger"
          onConfirm={() => handleDeleteTask(confirmDelete.id)}
          onCancel={() => setConfirmDelete(null)}
        />
      )}

      {/* Reset confirmation */}
      {confirmReset && (
        <ConfirmModal palette={palette}
          title="Obnovit katalog?"
          message="Tím se smažou všechny tvé úpravy a vrátí původní úkoly Pandičky."
          confirmLabel="Obnovit"
          confirmVariant="danger"
          onConfirm={handleReset}
          onCancel={() => setConfirmReset(false)}
        />
      )}
    </div>
  );
}

// ─── Edit modal ──────────────────────────────────────────────
function TaskEditModal({ palette, playfulness, task, onSave, onCancel }) {
  const [draft, setDraft] = useState(task);

  const update = (patch) => setDraft(d => ({ ...d, ...patch }));
  const updateReward = (patch) => setDraft(d => ({ ...d, reward: { ...d.reward, ...patch } }));
  const updateOption = (idx, patch) => {
    setDraft(d => {
      const options = d.options.map((o, i) => i === idx ? { ...o, ...patch } : o);
      return { ...d, options };
    });
  };
  const setCorrect = (idx) => {
    setDraft(d => ({
      ...d,
      options: d.options.map((o, i) => ({ ...o, correct: i === idx })),
    }));
  };

  const canSave = draft.title?.trim() && draft.options?.some(o => o.correct);

  return (
    <motion.div
      initial={{ opacity: 0 }} animate={{ opacity: 1 }}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(20,14,20,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 16,
      }}
      onClick={onCancel}
    >
      <motion.div
        initial={{ scale: 0.9, y: 20 }} animate={{ scale: 1, y: 0 }}
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 440, maxHeight: '90vh', overflow: 'auto',
          background: palette.card, borderRadius: 28, padding: 20,
          boxShadow: '0 30px 60px rgba(0,0,0,0.3)',
        }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14,
        }}>
          <div style={{
            fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 20, color: palette.ink,
          }}>{task.id.startsWith('custom-') || !TASK_CATALOG.find(t => t.id === task.id) ? 'Nový úkol' : 'Upravit úkol'}</div>
          <button onClick={onCancel} style={{
            width: 32, height: 32, borderRadius: '50%', border: 'none',
            background: palette.ink + '10', cursor: 'pointer', fontSize: 18,
          }}>×</button>
        </div>

        <Field label="Kategorie">
          <select value={draft.categoryId}
            onChange={e => update({ categoryId: e.target.value })}
            style={inputStyle(palette)}>
            {CATEGORIES_META.map(c => (
              <option key={c.id} value={c.id}>{c.icon} {c.name}</option>
            ))}
          </select>
        </Field>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Field label="Úroveň">
            <input type="number" min="1" value={draft.level || 1}
              onChange={e => update({ level: parseInt(e.target.value) || 1 })}
              style={inputStyle(palette)}/>
          </Field>
          <Field label="Boss úroveň">
            <label style={{
              display: 'flex', alignItems: 'center', gap: 8, padding: '10px 12px',
              borderRadius: 12, border: `1.5px solid ${palette.ink}18`,
              fontFamily: '"Baloo 2"', fontSize: 13, color: palette.ink, cursor: 'pointer',
              background: draft.boss ? palette.sun + '30' : 'transparent',
            }}>
              <input type="checkbox" checked={!!draft.boss}
                onChange={e => update({ boss: e.target.checked })}/>
              🎁 Odměna
            </label>
          </Field>
        </div>

        <Field label="Otázka (dlouhá)">
          <input type="text" value={draft.title || ''}
            onChange={e => update({ title: e.target.value })}
            style={inputStyle(palette)}/>
        </Field>

        <Field label="Otázka (krátká, pro malé)">
          <input type="text" value={draft.titleShort || ''}
            onChange={e => update({ titleShort: e.target.value })}
            style={inputStyle(palette)}/>
        </Field>

        <Field label="Audio instrukce (co řekne Pandička)">
          <textarea value={draft.audio || ''}
            onChange={e => update({ audio: e.target.value })}
            style={{ ...inputStyle(palette), minHeight: 60, resize: 'vertical' }}/>
        </Field>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <Field label="Odměna ⭐ XP">
            <input type="number" min="0" value={draft.reward?.xp ?? 10}
              onChange={e => updateReward({ xp: parseInt(e.target.value) || 0 })}
              style={inputStyle(palette)}/>
          </Field>
          <Field label="Odměna 💰 mince">
            <input type="number" min="0" value={draft.reward?.coins ?? 5}
              onChange={e => updateReward({ coins: parseInt(e.target.value) || 0 })}
              style={inputStyle(palette)}/>
          </Field>
        </div>

        <div style={{
          fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 700, color: palette.inkSoft,
          letterSpacing: '0.08em', textTransform: 'uppercase', marginTop: 14, marginBottom: 6,
        }}>Možnosti</div>

        {draft.options.map((opt, i) => (
          <div key={opt.id} style={{
            display: 'flex', gap: 6, alignItems: 'center', marginBottom: 8,
            padding: 8, borderRadius: 14,
            background: opt.correct ? palette.success + '18' : palette.ink + '06',
            border: `1.5px solid ${opt.correct ? palette.success : palette.ink + '15'}`,
          }}>
            <button onClick={() => setCorrect(i)} title="Označit jako správnou odpověď"
              style={{
                width: 28, height: 28, borderRadius: '50%', border: 'none', cursor: 'pointer',
                background: opt.correct ? palette.success : palette.ink + '15',
                color: '#fff', fontSize: 14, fontWeight: 800, flexShrink: 0,
              }}>{opt.correct ? '✓' : ''}</button>
            <input value={opt.emoji}
              onChange={e => updateOption(i, { emoji: e.target.value })}
              placeholder="🐼"
              style={{
                width: 48, padding: '8px', textAlign: 'center', fontSize: 18,
                borderRadius: 10, border: `1px solid ${palette.ink}18`, outline: 'none',
              }}/>
            <input value={opt.label}
              onChange={e => updateOption(i, { label: e.target.value })}
              placeholder="Popisek"
              style={{
                flex: 1, padding: '8px 10px', fontSize: 13,
                borderRadius: 10, border: `1px solid ${palette.ink}18`, outline: 'none',
                fontFamily: '"Baloo 2"', color: palette.ink,
              }}/>
          </div>
        ))}

        {!draft.options?.some(o => o.correct) && (
          <div style={{
            padding: 8, borderRadius: 10, background: palette.danger + '18',
            fontFamily: '"Baloo 2"', fontSize: 12, color: palette.danger, fontWeight: 600,
            marginBottom: 10,
          }}>⚠️ Označ jednu správnou odpověď ✓</div>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 16 }}>
          <BigButton palette={palette} variant="ghost" size="sm" onClick={onCancel}
            style={{ flex: 1 }}>Zrušit</BigButton>
          <BigButton palette={palette} variant="primary" size="sm"
            disabled={!canSave}
            onClick={() => onSave(draft)}
            style={{ flex: 1 }}>Uložit 🐾</BigButton>
        </div>
      </motion.div>
    </motion.div>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{
        fontFamily: '"Baloo 2"', fontSize: 11, fontWeight: 700,
        letterSpacing: '0.06em', textTransform: 'uppercase', color: '#7A6670', marginBottom: 4,
      }}>{label}</div>
      {children}
    </div>
  );
}

function inputStyle(palette) {
  return {
    width: '100%', padding: '10px 12px',
    borderRadius: 12, border: `1.5px solid ${palette.ink}18`,
    fontFamily: '"Baloo 2", "Baloo 2", system-ui', fontSize: 14, color: palette.ink,
    outline: 'none', background: '#fff',
  };
}

// ─── Confirm modal ───────────────────────────────────────────
function ConfirmModal({ palette, title, message, confirmLabel, confirmVariant = 'primary', onConfirm, onCancel }) {
  return (
    <motion.div
      initial={{ opacity: 0 }} animate={{ opacity: 1 }}
      style={{
        position: 'fixed', inset: 0, zIndex: 250,
        background: 'rgba(20,14,20,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      }}
      onClick={onCancel}
    >
      <motion.div
        initial={{ scale: 0.9 }} animate={{ scale: 1 }}
        onClick={e => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: 340,
          background: palette.card, borderRadius: 24, padding: 22,
          boxShadow: '0 30px 60px rgba(0,0,0,0.3)', textAlign: 'center',
        }}>
        <div style={{ fontSize: 42, marginBottom: 8 }}>🐼</div>
        <div style={{
          fontFamily: '"Baloo 2"', fontWeight: 700, fontSize: 20, color: palette.ink, marginBottom: 6,
        }}>{title}</div>
        <div style={{
          fontFamily: '"Baloo 2"', fontSize: 14, color: palette.inkSoft, marginBottom: 16,
        }}>{message}</div>
        <div style={{ display: 'flex', gap: 10 }}>
          <BigButton palette={palette} variant="ghost" size="sm"
            onClick={onCancel} style={{ flex: 1 }}>Zpět</BigButton>
          <button onClick={onConfirm} style={{
            flex: 1, height: 44, borderRadius: 22, border: 'none', cursor: 'pointer',
            background: confirmVariant === 'danger' ? palette.danger : palette.primary,
            color: '#fff', fontFamily: '"Baloo 2"', fontWeight: 600, fontSize: 14,
            boxShadow: `0 3px 0 ${confirmVariant === 'danger' ? '#B05364' : palette.primaryDeep}`,
          }}>{confirmLabel}</button>
        </div>
      </motion.div>
    </motion.div>
  );
}

Object.assign(window, { AdminDashboardScreen });
