/* recipes.jsx — recipe catalog + recipe card + editor.
   Globals: RecipeCard, RecipesPage, RecipeEditorModal
*/

(function () {
const { useState, useMemo } = React;

// ===========================================================
// RecipeCard — grey by default, purple border for class recipes;
//              craftable state stays purple highlight.
//              `compact` mode strips category tag + explanation for catalog density.
// ===========================================================
function RecipeCard({
  recipe, supply, onCraft,
  craftLabel = 'Maken',
  hideButton = false,
  catalogMode = false,
  compact = false,
}) {
  const craftable = !catalogMode && recipe.cost.every(([k, q]) => (supply?.[k] || 0) >= q);
  const catClass = `cat-${recipe.category}`;
  const iconSize    = compact ? 22 : 28;
  const chipIconSize= compact ? 12 : 14;
  return (
    <div
      className={`recipe-card ${catClass} ${catalogMode ? '' : (craftable ? 'craftable' : '')} ${compact ? 'compact' : ''}`}
      title={compact && recipe.explanation ? recipe.explanation : undefined}
    >
      <div className="recipe-inner">
        <div className="recipe-head">
          <div className="recipe-icon-box"><ItemIcon itemKey={recipe.output} size={iconSize} glow={craftable}/></div>
          <div>
            <p className="recipe-name">{recipe.name}</p>
            {!compact && <span className="recipe-tag">{RECIPE_CATEGORY_LABEL[recipe.category]}</span>}
          </div>
        </div>

        {!compact && recipe.explanation && (
          <p className="recipe-explanation">{recipe.explanation}</p>
        )}

        <div className="recipe-cost">
          {recipe.cost.map(([k, q]) => {
            const have = supply?.[k] || 0;
            const missing = !catalogMode && have < q;
            return (
              <span key={k} className={`cost-chip ${missing ? 'missing' : ''}`} title={ITEMS[k].name}>
                <ItemIcon itemKey={k} size={chipIconSize}/>
                ×{q}
                {!catalogMode && <span className="have">({have})</span>}
              </span>
            );
          })}
        </div>

        {!hideButton && (
          <button
            className={`craft-btn ${craftable ? 'enabled' : ''}`}
            disabled={!craftable}
            onClick={(e) => onCraft?.(recipe, e)}
          >
            {craftable ? craftLabel : 'Te weinig'}
          </button>
        )}
      </div>
    </div>
  );
}

// ===========================================================
// RecipesPage — 2-column catalog: rewards left, materials right
// ===========================================================
function RecipesPage({ recipes, adminMode, onEditRecipes }) {
  const leftGroups = [
    { cat: 'basic',     label: 'Basis beloningen' },
    { cat: 'advanced',  label: 'Gevorderde beloningen' },
    { cat: 'class',     label: 'Klasbeloningen' },
  ];
  const rightGroups = [
    { cat: 'rare',      label: 'Zeldzame materialen' },
    { cat: 'legendary', label: 'Legendarische materialen' },
  ];
  const byCat = useMemo(() => {
    const m = {};
    for (const r of recipes) (m[r.category] ??= []).push(r);
    return m;
  }, [recipes]);

  const renderSection = (g) => (
    <section key={g.cat} className="recipes-section">
      <div className="recipes-section-head">
        <h2>{g.label}</h2>
        <span className="count">{(byCat[g.cat] || []).length} recept{((byCat[g.cat]||[]).length === 1) ? '' : 'en'}</span>
      </div>
      <div className="recipe-grid">
        {(byCat[g.cat] || []).map(r => (
          <RecipeCard
            key={r.key}
            recipe={r}
            catalogMode
            hideButton
          />
        ))}
      </div>
    </section>
  );

  return (
    <>
      <div className="recipes-header">
        <div className="recipes-header-text">
          <p className="page-eyebrow">Receptenboek</p>
          <h1 className="page-title">Alle recepten</h1>
        </div>
        {adminMode && (
          <button
            className="btn-pixel violet"
            style={{ padding: '10px 16px', fontSize: 11, marginLeft: 'auto' }}
            onClick={onEditRecipes}
          >
            ✎ Recepten bewerken
          </button>
        )}
      </div>

      <div className="recipes-2col">
        <div className="recipes-col">
          <h2 className="recipes-col-title">Beloningen</h2>
          {leftGroups.map(renderSection)}
        </div>
        <div className="recipes-col">
          <h2 className="recipes-col-title">Materialen</h2>
          {rightGroups.map(renderSection)}
        </div>
      </div>
    </>
  );
}

// ===========================================================
// RecipeEditorModal — teacher can edit/add/delete recipes
// ===========================================================
function RecipeEditorModal({ recipes, onSave, onReset, onCancel }) {
  const [draft, setDraft] = useState(() => JSON.parse(JSON.stringify(recipes)));
  const [confirmReset, setConfirmReset] = useState(false);

  const categories = [
    { cat: 'basic',     label: 'Basis beloningen' },
    { cat: 'rare',      label: 'Zeldzame materialen' },
    { cat: 'advanced',  label: 'Gevorderde beloningen' },
    { cat: 'legendary', label: 'Legendarische materialen' },
    { cat: 'class',     label: 'Klasbeloningen' },
  ];

  const itemKeys = Object.keys(ITEMS);

  const upd = (key, field, val) =>
    setDraft(d => d.map(r => r.key === key ? { ...r, [field]: val } : r));

  const updCostQty = (key, idx, qty) =>
    setDraft(d => d.map(r => r.key !== key ? r :
      { ...r, cost: r.cost.map((c, i) => i === idx ? [c[0], Math.max(1, qty)] : c) }));

  const updCostItem = (key, idx, ik) =>
    setDraft(d => d.map(r => r.key !== key ? r :
      { ...r, cost: r.cost.map((c, i) => i === idx ? [ik, c[1]] : c) }));

  const addIngredient = (key) =>
    setDraft(d => d.map(r => r.key !== key ? r :
      { ...r, cost: [...r.cost, ['water', 1]] }));

  const removeIngredient = (key, idx) =>
    setDraft(d => d.map(r => r.key !== key ? r :
      { ...r, cost: r.cost.filter((_, i) => i !== idx) }));

  const deleteRecipe = (key) =>
    setDraft(d => d.filter(r => r.key !== key));

  const addRecipe = (cat) => {
    const ts = Date.now();
    setDraft(d => [...d, {
      key: `recipe_${ts}`,
      output: 'water',
      name: 'Nieuw recept',
      category: cat,
      explanation: '',
      cost: [['water', 1]],
    }]);
  };

  const inputStyle = {
    width: '100%', background: 'var(--bg-deep)', border: '2px solid var(--line)',
    padding: '8px 10px', fontFamily: 'var(--font-body)', fontSize: 16,
    color: 'var(--ink)', outline: 'none', marginBottom: 6,
  };
  const labelStyle = { display: 'block', fontSize: 11, color: 'var(--ink-dim)',
    fontFamily: 'var(--font-disp)', letterSpacing: 1, marginBottom: 3, textTransform: 'uppercase' };

  return (
    <div className="modal-overlay" onClick={onCancel}>
      <div className="modal wide" onClick={e => e.stopPropagation()}
           style={{ width: 'min(820px, 98%)', maxHeight: '92vh', display: 'flex', flexDirection: 'column' }}>
        <div className="modal-inner" style={{ overflow: 'auto', flex: 1 }}>
          <h3>Recepten bewerken</h3>
          <p>Bewerk naam, uitleg en kosten. Voeg nieuwe recepten toe of verwijder bestaande.</p>

          {categories.map(({ cat, label }) => {
            const catRecipes = draft.filter(r => r.category === cat);
            return (
              <section key={cat} style={{ marginBottom: 28 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10,
                  borderBottom: '2px solid var(--line)', paddingBottom: 8 }}>
                  <h4 style={{ margin: 0, fontSize: 14, fontFamily: 'var(--font-disp)', letterSpacing: 1 }}>
                    {label}
                  </h4>
                  <button className="btn-pixel ghost"
                    style={{ fontSize: 10, padding: '4px 10px', marginLeft: 'auto' }}
                    onClick={() => addRecipe(cat)}>
                    + Recept
                  </button>
                </div>

                {catRecipes.length === 0 && (
                  <p style={{ color: 'var(--ink-faint)', fontSize: 14, margin: '8px 0' }}>
                    Geen recepten. Klik "+ Recept" om er een toe te voegen.
                  </p>
                )}

                {catRecipes.map(r => (
                  <div key={r.key} style={{
                    background: 'var(--bg-deep)', border: '2px solid var(--line)',
                    padding: 14, marginBottom: 10,
                  }}>
                    <div style={{ display: 'flex', gap: 10, marginBottom: 8 }}>
                      <div style={{ flex: 1 }}>
                        <span style={labelStyle}>Naam</span>
                        <input style={inputStyle} value={r.name}
                          onChange={e => upd(r.key, 'name', e.target.value)} />
                      </div>
                      <div style={{ flex: 1 }}>
                        <span style={labelStyle}>Output item</span>
                        <select style={{ ...inputStyle, marginBottom: 0 }} value={r.output}
                          onChange={e => upd(r.key, 'output', e.target.value)}>
                          {itemKeys.map(k => (
                            <option key={k} value={k}>{ITEMS[k].name}</option>
                          ))}
                        </select>
                      </div>
                    </div>

                    <span style={labelStyle}>Uitleg (optioneel)</span>
                    <textarea style={{ ...inputStyle, resize: 'vertical' }}
                      value={r.explanation || ''} rows={2}
                      onChange={e => upd(r.key, 'explanation', e.target.value)} />

                    <span style={labelStyle}>Ingrediënten</span>
                    {r.cost.map(([ik, qty], idx) => (
                      <div key={idx} style={{ display: 'flex', gap: 6, alignItems: 'center', marginBottom: 4 }}>
                        <select style={{ ...inputStyle, flex: 1, marginBottom: 0 }} value={ik}
                          onChange={e => updCostItem(r.key, idx, e.target.value)}>
                          {itemKeys.map(k => (
                            <option key={k} value={k}>{ITEMS[k].name}</option>
                          ))}
                        </select>
                        <input type="number" min="1" value={qty} style={{ ...inputStyle, width: 70, marginBottom: 0 }}
                          onChange={e => updCostQty(r.key, idx, parseInt(e.target.value) || 1)} />
                        <button onClick={() => removeIngredient(r.key, idx)}
                          disabled={r.cost.length <= 1}
                          style={{ color: 'var(--danger)', fontSize: 16, opacity: r.cost.length <= 1 ? 0.3 : 1 }}>
                          ✕
                        </button>
                      </div>
                    ))}
                    <button className="btn-pixel ghost" style={{ fontSize: 10, padding: '4px 8px', marginTop: 4 }}
                      onClick={() => addIngredient(r.key)}>
                      + Ingredient
                    </button>

                    <div style={{ textAlign: 'right', marginTop: 8 }}>
                      <button onClick={() => deleteRecipe(r.key)}
                        style={{ color: 'var(--danger)', fontSize: 11, fontFamily: 'var(--font-disp)',
                          letterSpacing: 1, textTransform: 'uppercase' }}>
                        Verwijder recept
                      </button>
                    </div>
                  </div>
                ))}
              </section>
            );
          })}

          <div className="modal-actions" style={{ marginTop: 8, flexWrap: 'wrap', gap: 8 }}>
            {confirmReset ? (
              <>
                <span style={{ color: 'var(--danger)', fontSize: 13, alignSelf: 'center' }}>
                  Zeker? Al jouw aanpassingen worden verwijderd.
                </span>
                <button className="btn-pixel ghost" onClick={() => setConfirmReset(false)}>Nee</button>
                <button className="btn-pixel"
                  style={{ background: 'var(--danger)', border: '3px solid var(--danger)' }}
                  onClick={() => { onReset(); }}>
                  Ja, herstel
                </button>
              </>
            ) : (
              <button className="btn-pixel ghost" style={{ fontSize: 10 }}
                onClick={() => setConfirmReset(true)}>
                Herstel standaard
              </button>
            )}
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
              <button className="btn-pixel ghost" onClick={onCancel}>Annuleer</button>
              <button className="btn-pixel violet" onClick={() => onSave(draft)}>Opslaan</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { RecipeCard, RecipesPage, RecipeEditorModal });
})();
