/* NutriDMS, Use Template
   End-to-end template flow for BOTH recipes and ingredients:
   browse starter templates, create/manage your own, preview, then
   "Use template" prefills the Recipe / Ingredient builder. */

const { useState: useTplState, useEffect: useTplEffect, useMemo: useTplMemo } = React;

/* ── Curated starter templates ── */
const STARTER_TEMPLATES = {
  recipe: [
    { id: "rt-med", name: "Mediterranean Main", desc: "Olive-oil base, fresh vegetables, lean protein. Heart-friendly dinner scaffold.",
      icon: "salad", color: "#3b7c0f", category: "Dinner", uses: 248, official: true,
      data: { recipeType: "food", category: "Dinner", cuisine: "Mediterranean", servings: 4, prepTime: 15, cookTime: 25,
        tags: ["heart", "fiber"],
        ingredients: [
          { id: 1, name: "Extra-virgin olive oil", qty: "2", unit: "tbsp" },
          { id: 2, name: "Garlic, minced", qty: "3", unit: "cloves" },
          { id: 3, name: "Cherry tomatoes", qty: "300", unit: "g" },
        ],
        cookingSteps: [
          { id: 1, t: "Heat the olive oil in a large skillet over medium heat until shimmering." },
          { id: 2, t: "Add garlic and cook until fragrant, about 30 seconds." },
          { id: 3, t: "" },
        ] } },
    { id: "rt-breakfast", name: "Breakfast Bowl", desc: "Single-serve, high-protein morning bowl with grains, fruit, and yogurt.",
      icon: "egg-fried", color: "#dc6803", category: "Breakfast", uses: 176, official: true,
      data: { recipeType: "food", category: "Breakfast", cuisine: "American", servings: 1, prepTime: 10, cookTime: 5,
        tags: ["protein"],
        ingredients: [
          { id: 1, name: "Greek yogurt, plain", qty: "150", unit: "g" },
          { id: 2, name: "Rolled oats", qty: "40", unit: "g" },
          { id: 3, name: "Mixed berries", qty: "80", unit: "g" },
        ],
        cookingSteps: [{ id: 1, t: "Layer yogurt, oats, and berries in a bowl." }, { id: 2, t: "" }] } },
    { id: "rt-plant", name: "Plant-Based Entrée", desc: "Vegan main with legumes and whole grains. Allergen-light, fiber-rich.",
      icon: "sprout", color: "#0E9384", category: "Dinner", uses: 142, official: true,
      data: { recipeType: "food", category: "Dinner", cuisine: "Mediterranean", servings: 4, prepTime: 20, cookTime: 30,
        tags: ["vegan", "fiber"],
        ingredients: [
          { id: 1, name: "Chickpeas, cooked", qty: "400", unit: "g" },
          { id: 2, name: "Brown rice, cooked", qty: "300", unit: "g" },
          { id: 3, name: "Spinach", qty: "100", unit: "g" },
        ],
        cookingSteps: [{ id: 1, t: "" }, { id: 2, t: "" }] } },
    { id: "rt-beverage", name: "Smoothie / Beverage", desc: "Blended beverage scaffold, single serve, fruit & dairy base.",
      icon: "glass-water", color: "#2A54E5", category: "Beverage", uses: 98, official: true,
      data: { recipeType: "beverage", category: "Beverage", servings: 1, prepTime: 5, cookTime: 0,
        tags: ["protein"],
        ingredients: [
          { id: 1, name: "Banana", qty: "1", unit: "ea" },
          { id: 2, name: "Greek yogurt", qty: "100", unit: "g" },
          { id: 3, name: "Almond milk", qty: "200", unit: "ml" },
        ],
        cookingSteps: [{ id: 1, t: "Add all ingredients to a blender and blend until smooth." }] } },
    { id: "rt-soup", name: "Comfort Soup", desc: "Large-batch soup base, 6 servings, slow-simmered, freezer-friendly.",
      icon: "soup", color: "#b54708", category: "Lunch", uses: 121, official: true,
      data: { recipeType: "food", category: "Lunch", cuisine: "American", servings: 6, prepTime: 20, cookTime: 40,
        tags: ["fiber"],
        ingredients: [
          { id: 1, name: "Vegetable stock", qty: "1.5", unit: "L" },
          { id: 2, name: "Carrots, diced", qty: "200", unit: "g" },
        ],
        cookingSteps: [{ id: 1, t: "" }, { id: 2, t: "" }, { id: 3, t: "" }] } },
    { id: "rt-kids", name: "Kids Meal", desc: "Allergen-aware, smaller portions, balanced macros for ages 4-12.",
      icon: "baby", color: "#6938EF", category: "Lunch", uses: 64, official: true,
      data: { recipeType: "food", category: "Lunch", cuisine: "American", servings: 2, prepTime: 10, cookTime: 15,
        tags: [], allergens: ["peanut", "tree-nut"],
        ingredients: [{ id: 1, name: "Whole-wheat pasta", qty: "120", unit: "g" }],
        cookingSteps: [{ id: 1, t: "" }] } },
  ],
  ingredient: [
    { id: "it-protein", name: "Lean Protein", desc: "Animal protein scaffold, per-100g basis, USDA-sourced, macro fields ready.",
      icon: "drumstick", color: "#b42318", category: "Protein", uses: 312, official: true,
      data: { category: "Protein", baseUnit: "g", refServing: 100, sourceType: "USDA FoodData Central",
        regions: ["USA", "Canada"], storage: "refrigerated", shelfLife: 3,
        nutr: { calories: 165, protein: 31, carbs: 0, fat: 3.6, fiber: 0, sodium: 74 }, allergens: [] } },
    { id: "it-green", name: "Leafy Green Vegetable", desc: "Low-calorie vegetable scaffold with fiber and micronutrient fields.",
      icon: "leaf", color: "#3b7c0f", category: "Vegetable", uses: 204, official: true,
      data: { category: "Vegetable", baseUnit: "g", refServing: 100, sourceType: "USDA FoodData Central",
        regions: ["USA", "Europe"], storage: "refrigerated", shelfLife: 7,
        nutr: { calories: 23, protein: 2.9, carbs: 3.6, fat: 0.4, fiber: 2.2, sodium: 79 }, allergens: [] } },
    { id: "it-grain", name: "Whole Grain", desc: "Complex-carb staple, cooked basis, fiber & B-vitamin scaffold.",
      icon: "wheat", color: "#dc6803", category: "Grain", uses: 168, official: true,
      data: { category: "Grain", baseUnit: "g", refServing: 100, sourceType: "USDA FoodData Central",
        regions: ["USA"], storage: "ambient", shelfLife: 365,
        nutr: { calories: 123, protein: 2.7, carbs: 26, fat: 1, fiber: 1.6, sodium: 4 }, allergens: [] } },
    { id: "it-dairy", name: "Dairy Product", desc: "Dairy scaffold with allergen pre-flagged and refrigeration defaults.",
      icon: "milk", color: "#2A54E5", category: "Dairy", uses: 134, official: true,
      data: { category: "Dairy", baseUnit: "g", refServing: 100, sourceType: "USDA FoodData Central",
        regions: ["USA", "Europe"], storage: "refrigerated", shelfLife: 14,
        nutr: { calories: 59, protein: 10, carbs: 3.6, fat: 0.4, fiber: 0, sodium: 36 }, allergens: ["dairy"] } },
    { id: "it-oil", name: "Cooking Oil / Fat", desc: "High-fat ingredient scaffold, per-100g, fatty-acid breakdown fields.",
      icon: "droplet", color: "#ca8a04", category: "Fat & Oil", uses: 92, official: true,
      data: { category: "Fat & Oil", baseUnit: "ml", refServing: 100, sourceType: "USDA FoodData Central",
        regions: ["USA"], storage: "ambient", shelfLife: 540,
        nutr: { calories: 884, protein: 0, carbs: 0, fat: 100, fiber: 0, sodium: 2 }, allergens: [] } },
    { id: "it-bevbase", name: "Beverage Base", desc: "Liquid base, per-100ml basis for drink and smoothie ingredients.",
      icon: "glass-water", color: "#0E9384", category: "Beverage Base", uses: 58, official: true,
      data: { category: "Beverage Base", baseUnit: "ml", refServing: 100, sourceType: "USDA FoodData Central",
        regions: ["USA"], storage: "refrigerated", shelfLife: 10,
        nutr: { calories: 42, protein: 1, carbs: 9, fat: 0.5, fiber: 0, sodium: 5 }, allergens: [] } },
  ],
};

const TPL_ICONS = ["salad", "egg-fried", "sprout", "glass-water", "soup", "baby", "drumstick", "leaf", "wheat", "milk", "droplet", "utensils-crossed", "flame", "fish", "carrot", "cake"];
const TPL_COLORS = ["#3b7c0f", "#dc6803", "#0E9384", "#2A54E5", "#b54708", "#6938EF", "#b42318", "#ca8a04"];

function useMyTemplates() {
  const [my, setMy] = useTplState(() => {
    try { return JSON.parse(localStorage.getItem("nutridms_my_templates") || "[]"); } catch (e) { return []; }
  });
  useTplEffect(() => { try { localStorage.setItem("nutridms_my_templates", JSON.stringify(my)); } catch (e) {} }, [my]);
  return [my, setMy];
}

function TemplatesPage() {
  const { setPage, toast } = useApp();
  const [kind, setKind] = useTplState("recipe");
  const [q, setQ] = useTplState("");
  const [cat, setCat] = useTplState("All");
  const [preview, setPreview] = useTplState(null);
  const [createOpen, setCreateOpen] = useTplState(false);
  const [my, setMy] = useMyTemplates();

  const starters = STARTER_TEMPLATES[kind];
  const mine = my.filter(t => t.type === kind);
  const cats = ["All", ...Array.from(new Set(starters.map(t => t.category)))];
  const match = (t) => (cat === "All" || t.category === cat) && (!q || t.name.toLowerCase().includes(q.toLowerCase()) || (t.desc || "").toLowerCase().includes(q.toLowerCase()));
  const shownStarters = starters.filter(match);
  const shownMine = mine.filter(match);

  const useTemplate = (t) => {
    const payload = { name: t.name, data: t.data || t.fields || {} };
    try {
      localStorage.setItem(kind === "recipe" ? "nutridms_recipe_template" : "nutridms_ingredient_template", JSON.stringify(payload));
    } catch (e) {}
    toast(`Template applied, "${t.name}"`);
    setPreview(null);
    setPage(kind === "recipe" ? "upload" : "add-ingredient");
  };
  const duplicateTpl = (t) => {
    const copy = { ...t, id: "my-" + Date.now(), name: t.name + " (copy)", type: kind, official: false, uses: 0, createdAt: Date.now() };
    delete copy.official;
    setMy(m => [{ ...copy, official: false }, ...m]);
    toast("Template duplicated to My Templates");
    setPreview(null);
  };
  const deleteTpl = (id) => { setMy(m => m.filter(t => t.id !== id)); setPreview(null); toast("Template deleted"); };
  const saveNew = (tpl) => { setMy(m => [{ ...tpl, type: kind, createdAt: Date.now() }, ...m]); setCreateOpen(false); toast("Template created"); };

  return (
    <div className="tpl">
      <Crumbs path={[{ label: "Dashboard", onClick: () => setPage("dashboard") }, { label: "Templates" }]} />

      <div className="page-head">
        <div>
          <h1 className="page-title">Templates</h1>
          <p className="page-sub">Start faster with a reusable scaffold. Pick a starter template or one your team created, it pre-fills the {kind === "recipe" ? "recipe" : "ingredient"} builder, ready to customize.</p>
        </div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          <button className="btn secondary" onClick={() => setPage(kind === "recipe" ? "upload" : "add-ingredient")}><Icon name="file-plus" size={16} /> Start blank</button>
          <button className="btn primary" onClick={() => setCreateOpen(true)}><Icon name="plus" size={16} /> Create Template</button>
        </div>
      </div>

      {/* Recipe / Ingredient switch */}
      <div className="tpl-switch">
        <button className={kind === "recipe" ? "on" : ""} onClick={() => { setKind("recipe"); setCat("All"); }}><Icon name="utensils-crossed" size={16} /> Recipe Templates <span className="tpl-switch-c">{STARTER_TEMPLATES.recipe.length + my.filter(t => t.type === "recipe").length}</span></button>
        <button className={kind === "ingredient" ? "on" : ""} onClick={() => { setKind("ingredient"); setCat("All"); }}><Icon name="leaf" size={16} /> Ingredient Templates <span className="tpl-switch-c">{STARTER_TEMPLATES.ingredient.length + my.filter(t => t.type === "ingredient").length}</span></button>
      </div>

      {/* Toolbar */}
      <div className="tpl-toolbar">
        <div className="tpl-search">
          <Icon name="search" size={16} />
          <input placeholder={`Search ${kind} templates…`} value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <div className="tpl-cats">
          {cats.map(c => <button key={c} className={`tpl-cat ${cat === c ? "on" : ""}`} onClick={() => setCat(c)}>{c}</button>)}
        </div>
      </div>

      {/* Starter templates */}
      <div className="tpl-section-head">
        <h3><Icon name="lightbulb" size={15} /> Starter templates</h3>
        <span className="muted">Maintained by NutriDMS · validated structure</span>
      </div>
      <div className="tpl-grid">
        {shownStarters.map(t => <TemplateCard key={t.id} t={t} onPreview={() => setPreview(t)} onUse={() => useTemplate(t)} />)}
        {shownStarters.length === 0 && <div className="tpl-empty">No starter templates match your search.</div>}
      </div>

      {/* My templates */}
      <div className="tpl-section-head" style={{ marginTop: 28 }}>
        <h3><Icon name="bookmark" size={15} /> My templates</h3>
        <span className="muted">{mine.length} saved · created by you & your team</span>
      </div>
      {shownMine.length > 0 ? (
        <div className="tpl-grid">
          {shownMine.map(t => <TemplateCard key={t.id} t={t} mine onPreview={() => setPreview(t)} onUse={() => useTemplate(t)} onDelete={() => deleteTpl(t.id)} />)}
        </div>
      ) : (
        <div className="tpl-empty-card">
          <div className="tpl-empty-ic"><Icon name="bookmark-plus" size={22} /></div>
          <div style={{ flex: 1 }}>
            <strong>No templates yet</strong>
            <p>Create a reusable {kind} template so your team can start from a consistent structure every time.</p>
          </div>
          <button className="btn primary" onClick={() => setCreateOpen(true)}><Icon name="plus" size={15} /> Create Template</button>
        </div>
      )}

      {preview && <TemplatePreview t={preview} kind={kind} onClose={() => setPreview(null)} onUse={() => useTemplate(preview)} onDuplicate={() => duplicateTpl(preview)} onDelete={preview.official ? null : () => deleteTpl(preview.id)} />}
      {createOpen && <CreateTemplateModal kind={kind} onClose={() => setCreateOpen(false)} onSave={saveNew} />}
    </div>
  );
}

function TemplateCard({ t, mine, onPreview, onUse, onDelete }) {
  const fieldCount = t.type === "ingredient" || t.data?.nutr
    ? Object.keys(t.data?.nutr || {}).length + (t.data?.category ? 1 : 0)
    : (t.data?.ingredients?.length || 0) + (t.data?.cookingSteps?.filter(s => s.t)?.length || 0);
  return (
    <div className="tpl-card" onClick={onPreview}>
      <div className="tpl-card-top">
        <div className="tpl-card-ic" style={{ background: (t.color || "#3b7c0f") + "1a", color: t.color || "#3b7c0f" }}><Icon name={t.icon || "file-text"} size={20} /></div>
        {t.official ? <span className="tpl-badge official"><Icon name="badge-check" size={11} /> Official</span> : <span className="tpl-badge mine">Custom</span>}
      </div>
      <div className="tpl-card-name">{t.name}</div>
      <div className="tpl-card-desc">{t.desc}</div>
      <div className="tpl-card-meta">
        <span className="tpl-chip">{t.category}</span>
        {!!fieldCount && <span className="tpl-chip ghost"><Icon name="list" size={11} /> {fieldCount} prefilled</span>}
        {t.official && <span className="tpl-chip ghost"><Icon name="users" size={11} /> {t.uses} uses</span>}
      </div>
      <div className="tpl-card-actions" onClick={e => e.stopPropagation()}>
        <button className="btn secondary sm" onClick={onPreview}><Icon name="eye" size={14} /> Preview</button>
        <button className="btn primary sm" onClick={onUse}>Use template <Icon name="arrow-right" size={13} /></button>
        {mine && onDelete && <button className="tpl-del" title="Delete" onClick={onDelete}><Icon name="trash-2" size={15} /></button>}
      </div>
    </div>
  );
}

function TemplatePreview({ t, kind, onClose, onUse, onDuplicate, onDelete }) {
  const d = t.data || t.fields || {};
  return (
    <Modal open onClose={onClose} width={620} title={t.name} subtitle={t.desc} footer={
      <>
        {onDelete && <button className="btn danger" onClick={onDelete} style={{ marginRight: "auto" }}><Icon name="trash-2" size={14} /> Delete</button>}
        <button className="btn ghost" onClick={onDuplicate}><Icon name="copy" size={14} /> Duplicate</button>
        <button className="btn primary" onClick={onUse}><Icon name="arrow-right" size={14} /> Use this template</button>
      </>
    }>
      <div className="tpl-prev-head">
        <div className="tpl-card-ic" style={{ background: (t.color || "#3b7c0f") + "1a", color: t.color || "#3b7c0f", width: 44, height: 44 }}><Icon name={t.icon || "file-text"} size={22} /></div>
        <div className="tpl-prev-tags">
          <span className="tpl-chip">{kind === "recipe" ? "Recipe" : "Ingredient"}</span>
          <span className="tpl-chip">{t.category}</span>
          {t.official ? <span className="tpl-badge official"><Icon name="badge-check" size={11} /> Official</span> : <span className="tpl-badge mine">Custom</span>}
        </div>
      </div>
      <div className="tpl-prev-note"><Icon name="info" size={14} /> Using this template pre-fills the builder with the values below. Everything stays editable.</div>

      {kind === "recipe" ? (
        <div className="tpl-prev-grid">
          <PrevField label="Type" value={d.recipeType === "beverage" ? "Beverage" : "Food"} />
          <PrevField label="Category" value={d.category} />
          <PrevField label="Cuisine" value={d.cuisine} />
          <PrevField label="Servings" value={d.servings} />
          <PrevField label="Prep time" value={d.prepTime ? d.prepTime + " min" : null} />
          <PrevField label="Cook time" value={d.cookTime != null ? d.cookTime + " min" : null} />
          {!!(d.ingredients || []).length && (
            <div className="tpl-prev-full">
              <div className="tpl-prev-label">Ingredients ({d.ingredients.length})</div>
              <div className="tpl-prev-list">{d.ingredients.map((i, k) => <span key={k} className="tpl-chip ghost">{i.qty} {i.unit} {i.name}</span>)}</div>
            </div>
          )}
          {!!(d.cookingSteps || []).filter(s => s.t).length && (
            <div className="tpl-prev-full">
              <div className="tpl-prev-label">Cooking steps ({d.cookingSteps.filter(s => s.t).length} prefilled · {d.cookingSteps.length} slots)</div>
              <ol className="tpl-prev-steps">{d.cookingSteps.filter(s => s.t).map((s, k) => <li key={k}>{s.t}</li>)}</ol>
            </div>
          )}
          {!!(d.tags || []).length && (
            <div className="tpl-prev-full"><div className="tpl-prev-label">Health tags</div><div className="tpl-prev-list">{d.tags.map((tg, k) => <span key={k} className="tpl-chip">{tg}</span>)}</div></div>
          )}
        </div>
      ) : (
        <div className="tpl-prev-grid">
          <PrevField label="Category" value={d.category} />
          <PrevField label="Base unit" value={d.baseUnit} />
          <PrevField label="Reference serving" value={d.refServing ? d.refServing + " " + (d.baseUnit || "g") : null} />
          <PrevField label="Source" value={d.sourceType} />
          <PrevField label="Storage" value={d.storage} />
          <PrevField label="Shelf life" value={d.shelfLife ? d.shelfLife + " days" : null} />
          {!!Object.keys(d.nutr || {}).length && (
            <div className="tpl-prev-full">
              <div className="tpl-prev-label">Nutrition (per {d.refServing || 100}{d.baseUnit || "g"})</div>
              <div className="tpl-prev-list">{Object.entries(d.nutr).map(([k, v]) => <span key={k} className="tpl-chip ghost">{k}: {v}</span>)}</div>
            </div>
          )}
          {!!(d.allergens || []).length && (
            <div className="tpl-prev-full"><div className="tpl-prev-label">Allergens pre-flagged</div><div className="tpl-prev-list">{d.allergens.map((a, k) => <span key={k} className="tpl-chip danger">{a}</span>)}</div></div>
          )}
          {!!(d.regions || []).length && (
            <div className="tpl-prev-full"><div className="tpl-prev-label">Compliance regions</div><div className="tpl-prev-list">{d.regions.map((r, k) => <span key={k} className="tpl-chip">{r}</span>)}</div></div>
          )}
        </div>
      )}
    </Modal>
  );
}

function PrevField({ label, value }) {
  return (
    <div className="tpl-prev-field">
      <div className="tpl-prev-label">{label}</div>
      <div className="tpl-prev-value">{value != null && value !== "" ? value : <span className="muted">—</span>}</div>
    </div>
  );
}

/* ── Create template builder ── */
function CreateTemplateModal({ kind, onClose, onSave }) {
  const [name, setName] = useTplState("");
  const [desc, setDesc] = useTplState("");
  const [category, setCategory] = useTplState(kind === "recipe" ? "Dinner" : "Protein");
  const [icon, setIcon] = useTplState(kind === "recipe" ? "utensils-crossed" : "leaf");
  const [color, setColor] = useTplState("#3b7c0f");
  // recipe fields
  const [cuisine, setCuisine] = useTplState("Mediterranean");
  const [servings, setServings] = useTplState(4);
  const [prep, setPrep] = useTplState(15);
  const [cook, setCook] = useTplState(20);
  const [stepSlots, setStepSlots] = useTplState(3);
  // ingredient fields
  const [baseUnit, setBaseUnit] = useTplState("g");
  const [refServing, setRefServing] = useTplState(100);
  const [sourceType, setSourceType] = useTplState("USDA FoodData Central");

  const recipeCats = ["Breakfast", "Lunch", "Dinner", "Snack", "Dessert", "Beverage"];
  const ingCats = ["Protein", "Grain", "Dairy", "Vegetable", "Fruit", "Fat & Oil", "Legume", "Beverage Base", "Seasoning"];

  const build = () => {
    const base = { id: "my-" + Date.now(), name: name.trim() || "Untitled template", desc: desc.trim() || "Custom template", category, icon, color, official: false, uses: 0 };
    if (kind === "recipe") {
      base.data = { recipeType: category === "Beverage" ? "beverage" : "food", category, cuisine, servings: Number(servings) || 4, prepTime: Number(prep) || 0, cookTime: Number(cook) || 0,
        tags: [], ingredients: [], cookingSteps: Array.from({ length: Math.max(1, Number(stepSlots) || 1) }, (_, i) => ({ id: i + 1, t: "" })) };
    } else {
      base.data = { category, baseUnit, refServing: Number(refServing) || 100, sourceType, nutr: {}, allergens: [], regions: [], storage: "ambient", shelfLife: 30 };
    }
    onSave(base);
  };

  return (
    <Modal open onClose={onClose} width={600} title={`Create ${kind === "recipe" ? "Recipe" : "Ingredient"} Template`} subtitle="Define defaults your team will start from. You can refine each value when you use it." footer={
      <>
        <button className="btn ghost" onClick={onClose}>Cancel</button>
        <button className="btn primary" disabled={!name.trim()} onClick={build}><Icon name="check" size={14} /> Save Template</button>
      </>
    }>
      <div className="field"><label>Template name <span className="req">*</span></label>
        <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder={kind === "recipe" ? "e.g. Weeknight Sheet-Pan Dinner" : "e.g. Frozen Seafood"} /></div>
      <div className="field"><label>Description</label>
        <input className="input" value={desc} onChange={e => setDesc(e.target.value)} placeholder="What is this template for?" /></div>

      <div className="tpl-form-row">
        <div className="field" style={{ flex: 1 }}><label>Category</label>
          <select className="input" value={category} onChange={e => setCategory(e.target.value)}>{(kind === "recipe" ? recipeCats : ingCats).map(c => <option key={c}>{c}</option>)}</select></div>
      </div>

      {kind === "recipe" ? (
        <div className="tpl-form-grid">
          <div className="field"><label>Cuisine</label><select className="input" value={cuisine} onChange={e => setCuisine(e.target.value)}>{["American", "Mediterranean", "Asian", "Mexican", "Italian", "Indian", "Middle Eastern"].map(c => <option key={c}>{c}</option>)}</select></div>
          <div className="field"><label>Servings</label><input type="number" className="input" min="1" value={servings} onChange={e => setServings(e.target.value)} /></div>
          <div className="field"><label>Prep (min)</label><input type="number" className="input" min="0" value={prep} onChange={e => setPrep(e.target.value)} /></div>
          <div className="field"><label>Cook (min)</label><input type="number" className="input" min="0" value={cook} onChange={e => setCook(e.target.value)} /></div>
          <div className="field"><label>Step slots</label><input type="number" className="input" min="1" max="20" value={stepSlots} onChange={e => setStepSlots(e.target.value)} /></div>
        </div>
      ) : (
        <div className="tpl-form-grid">
          <div className="field"><label>Base unit</label><select className="input" value={baseUnit} onChange={e => setBaseUnit(e.target.value)}>{["g", "ml", "oz", "ea"].map(c => <option key={c}>{c}</option>)}</select></div>
          <div className="field"><label>Reference serving</label><input type="number" className="input" min="1" value={refServing} onChange={e => setRefServing(e.target.value)} /></div>
          <div className="field" style={{ gridColumn: "1 / -1" }}><label>Default source</label><select className="input" value={sourceType} onChange={e => setSourceType(e.target.value)}>{["USDA FoodData Central", "FDA", "EFSA (Europe)", "Health Canada", "Manufacturer", "Internal lab"].map(c => <option key={c}>{c}</option>)}</select></div>
        </div>
      )}

      <div className="field"><label>Icon &amp; color</label>
        <div className="tpl-icon-pick">
          {TPL_ICONS.map(ic => <button key={ic} type="button" className={`tpl-icon-opt ${icon === ic ? "on" : ""}`} onClick={() => setIcon(ic)} style={icon === ic ? { borderColor: color, color } : {}}><Icon name={ic} size={16} /></button>)}
        </div>
        <div className="tpl-color-pick">
          {TPL_COLORS.map(c => <button key={c} type="button" className={`tpl-color-opt ${color === c ? "on" : ""}`} onClick={() => setColor(c)} style={{ background: c }} />)}
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { TemplatesPage });
