/* NutriDMS, Upload wizard
   Embeds the full Add Recipe form (with live preview rail) inside the
   platform shell so contributors never leave the app. */

function UploadWizard() {
  const [loraaOpen, setLoraaOpen] = React.useState(false);
  React.useEffect(() => {
    const onMsg = (e) => { if (e.data && e.data.type === "nutridms-loraa") setLoraaOpen(!!e.data.open); };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, []);
  const closeLoraa = () => {
    const f = document.querySelector('iframe[title="Upload Recipe"]');
    try { f && f.contentWindow.postMessage({ type: "nutridms-loraa-close" }, "*"); } catch (e) {}
  };
  return (
    <div style={{ margin: "-32px -32px -32px", height: "calc(100vh - 64px)", display: "flex", flexDirection: "column", position: "relative", zIndex: loraaOpen ? 160 : "auto" }}>
      {loraaOpen && <div onMouseDown={closeLoraa} style={{ position: "fixed", inset: 0, background: "rgba(12,18,14,.5)", zIndex: 150, animation: "fade .16s ease" }} />}
      <iframe
        src="screens/add-recipe.html?v=20260828-public-catalog-media-1"
        title="Upload Recipe"
        style={{ flex: 1, border: 0, width: "100%", height: "100%", background: "#FBFCF9", position: "relative", zIndex: loraaOpen ? 151 : "auto" }}
      />
    </div>
  );
}

/* ─── Legacy upload wizard (kept for reference, no longer wired into the router) ─── */
function UploadWizardLegacy() {
  const { setPage, toast } = useApp();
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    title: "",
    cuisine: "Mediterranean",
    category: "Lunch",
    region: "Europe",
    description: "",
    servings: 4,
    duration: 25,
    diet: ["Vegetarian"],
    allergens: [],
    coverFile: null,
    gallery: [],
    altText: "",
    ingredients: ["", "", ""],
    steps: ["", ""],
    calories: "", protein: "", carbs: "", fat: "", fiber: "",
    locales: ["en"]
  });
  const STEPS = ["Main Media", "Recipe Details", "Nutrition", "Review & Submit"];

  // Quick validation per step
  const stepValid = (i) => {
    if (i === 0) return form.title.trim().length > 2 && (form.coverFile || form.gallery.length > 0);
    if (i === 1) return form.ingredients.filter((x) => x.trim()).length >= 3 && form.steps.filter((x) => x.trim()).length >= 1;
    if (i === 2) return Number(form.calories) > 0;
    return true;
  };
  const next = () => setStep((s) => Math.min(STEPS.length - 1, s + 1));
  const back = () => setStep((s) => Math.max(0, s - 1));
  const submit = () => {toast("Recipe submitted for review");setPage("dashboard");};

  return (
    <div>
      <Crumbs path={[
      { label: "My Recipes", onClick: () => setPage("recipes") },
      { label: "Upload Recipe" }]
      } />

      <div className="page-head">
        <div>
          <h1 className="page-title">{form.title || "New recipe"}</h1>
          <p className="page-sub">Submit a recipe for nutritional + editorial review. Drafts save automatically every 30 s.</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn ghost" onClick={() => {setForm({ ...form, title: "", description: "", ingredients: ["", "", ""], steps: ["", ""] });toast("Form cleared");}}><Icon name="x" size={16} /> Clear</button>
          <button className="btn secondary"><Icon name="save" size={16} /> Save as Draft</button>
        </div>
      </div>

      {/* Stepper */}
      <div className="card pad" style={{ marginBottom: 18 }}>
        <div className="stepper">
          {STEPS.map((label, i) =>
          <React.Fragment key={label}>
              <div className={`step ${i < step ? "done" : i === step ? "current" : ""}`} onClick={() => i <= step && setStep(i)} style={{ cursor: i <= step ? "pointer" : "default" }}>
                <div className="step-num">{i < step ? <Icon name="check" size={14} stroke={2.6} /> : i + 1}</div>
                <div className="step-name">{label}</div>
              </div>
              {i < STEPS.length - 1 && <div className={`step-line ${i < step ? "done" : ""}`} />}
            </React.Fragment>
          )}
        </div>
      </div>

      {/* Content */}
      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 22 }}>
        <div className="card pad">
          {step === 0 && <StepMedia form={form} set={(p) => setForm({ ...form, ...p })} />}
          {step === 1 && <StepDetails form={form} set={(p) => setForm({ ...form, ...p })} />}
          {step === 2 && <StepNutrition form={form} set={(p) => setForm({ ...form, ...p })} />}
          {step === 3 && <StepReview form={form} />}

          <hr className="divider" />
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <button className="btn secondary" disabled={step === 0} onClick={back}><Icon name="chevron-left" size={16} /> Back</button>
            {step < STEPS.length - 1 ?
            <button className="btn primary" disabled={!stepValid(step)} onClick={next}>Continue <Icon name="chevron-right" size={16} /></button> :

            <button className="btn primary" onClick={submit}><Icon name="send" size={16} /> Submit for Review</button>
            }
          </div>
        </div>

        {/* Preview */}
        <div className="card pad" style={{ position: "sticky", top: 84, alignSelf: "flex-start", maxHeight: "calc(100vh - 100px)", overflow: "auto" }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
            <h3 style={{ fontFamily: "var(--serif)", fontSize: 18, margin: 0 }}>Live preview</h3>
            <span className="pill neutral">draft</span>
          </div>
          <div className="recipe-card" style={{ cursor: "default" }}>
            <div className="recipe-cover" style={{ backgroundImage: form.gallery[0] ? `url("${form.gallery[0]}")` : "linear-gradient(135deg, #E3FBCC, #ABEFC6)" }}>
              {!form.gallery[0] && <div style={{ display: "grid", placeItems: "center", height: "100%", color: "var(--green-700)" }}><Icon name="image" size={36} /></div>}
            </div>
            <div className="recipe-body">
              <h4 className="recipe-title">{form.title || "Recipe title"}</h4>
              <div className="recipe-meta">
                <span><Icon name="clock" size={14} /> {form.duration} min</span>
                <span><Icon name="users" size={14} /> {form.servings}</span>
                <span><Icon name="flame" size={14} /> {form.calories || "—"} kcal</span>
              </div>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                <span className="tag">{form.cuisine}</span>
                <span className="tag" style={{ background: "var(--green-50)", color: "var(--green-700)" }}>{form.category}</span>
              </div>
              <p className="muted" style={{ fontSize: 13, margin: 0, lineHeight: 1.5 }}>{form.description || "Add a description in step 2…"}</p>
            </div>
          </div>

          <div className="alert info" style={{ marginTop: 14 }}>
            <Icon name="lightbulb" size={18} />
            <div style={{ fontSize: 13 }}>
              <strong>Tip</strong>
              <div style={{ marginTop: 2 }}>The cover image should show the finished plated dish, not raw ingredients.</div>
            </div>
          </div>
        </div>
      </div>
    </div>);

}

function StepMedia({ form, set }) {
  const onPick = (file) => {
    // Simulated, turn file into object URL OR keep a placeholder
    if (file && file.type && file.type.startsWith("image/")) {
      const url = URL.createObjectURL(file);
      set({ coverFile: file, gallery: [url, ...form.gallery] });
    }
  };
  return (
    <div className="col" style={{ gap: 18 }}>
      <div className="field">
        <label>Recipe title <span style={{ color: "var(--error-600)" }}>*</span></label>
        <input className="input" value={form.title} onChange={(e) => set({ title: e.target.value })} placeholder="e.g. Mediterranean Quinoa Bowl" />
        <span className="hint">A clear, descriptive name, start with the dish, not the cuisine.</span>
      </div>

      <div className="field">
        <label>Cover image <span style={{ color: "var(--error-600)" }}>*</span></label>
        <Dropzone onPick={onPick} />
        <span className="hint">.jpg, .png, .webp, max 10 MB. Use the final plated result.</span>
      </div>

      {form.gallery.length > 0 &&
      <div className="field">
          <label>Gallery ({form.gallery.length})</label>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
            {form.gallery.map((src, i) =>
          <div key={i} style={{ position: "relative", aspectRatio: "1/1", borderRadius: 10, backgroundImage: `url("${src}")`, backgroundSize: "cover", backgroundPosition: "center", border: "1px solid var(--gray-200)" }}>
                <button onClick={() => set({ gallery: form.gallery.filter((_, j) => j !== i) })} className="icon-btn" style={{ position: "absolute", top: 4, right: 4, width: 24, height: 24, background: "rgba(0,0,0,.55)", color: "#fff" }}><Icon name="x" size={12} /></button>
              </div>
          )}
            <button onClick={() => document.getElementById("more-files")?.click()} style={{ aspectRatio: "1/1", borderRadius: 10, border: "1.5px dashed var(--gray-300)", display: "grid", placeItems: "center", color: "var(--gray-500)" }}>
              <Icon name="plus" size={20} />
            </button>
            <input id="more-files" type="file" accept="image/*" multiple style={{ display: "none" }} onChange={(e) => Array.from(e.target.files).forEach(onPick)} />
          </div>
        </div>
      }

      <div className="field">
        <label>Alt text <span className="muted">(accessibility)</span></label>
        <input className="input" value={form.altText} onChange={(e) => set({ altText: e.target.value })} placeholder="A close-up of a colorful grain bowl with feta and olives" />
      </div>
    </div>);

}

function Dropzone({ onPick }) {
  const [over, setOver] = React.useState(false);
  return (
    <label
      className={`dropzone ${over ? "over" : ""}`}
      onDragOver={(e) => {e.preventDefault();setOver(true);}}
      onDragLeave={() => setOver(false)}
      onDrop={(e) => {e.preventDefault();setOver(false);const f = e.dataTransfer.files?.[0];f && onPick(f);}}
      style={{ display: "block", cursor: "pointer" }}>
      
      <div className="icon"><Icon name="upload-cloud" size={22} /></div>
      <div style={{ fontWeight: 700, color: "var(--text-primary)" }}>Drag your file(s) or <span style={{ color: "var(--brand-700)" }}>browse</span></div>
      <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>Max 10 MB · jpg, png, webp</div>
      <input type="file" accept="image/*" style={{ display: "none" }} onChange={(e) => onPick(e.target.files?.[0])} />
    </label>);

}

function StepDetails({ form, set }) {
  const updateAt = (key, idx, val) => {
    const arr = [...form[key]];arr[idx] = val;set({ [key]: arr });
  };
  const addRow = (key) => set({ [key]: [...form[key], ""] });
  const remove = (key, idx) => set({ [key]: form[key].filter((_, i) => i !== idx) });

  return (
    <div className="col" style={{ gap: 18 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="field"><label>Cuisine</label>
          <select className="select" value={form.cuisine} onChange={(e) => set({ cuisine: e.target.value })}>
            {["Mediterranean", "Italian", "Japanese", "Indian", "French", "American", "Korean", "Middle Eastern", "Modern"].map((c) => <option key={c}>{c}</option>)}
          </select>
        </div>
        <div className="field"><label>Category</label>
          <select className="select" value={form.category} onChange={(e) => set({ category: e.target.value })}>
            {["Breakfast", "Lunch", "Dinner", "Starter", "Side", "Snack", "Dessert", "Beverage"].map((c) => <option key={c}>{c}</option>)}
          </select>
        </div>
        <div className="field"><label>Cooking time (min)</label>
          <input className="input" type="number" value={form.duration} onChange={(e) => set({ duration: +e.target.value })} />
        </div>
        <div className="field"><label>Servings</label>
          <input className="input" type="number" value={form.servings} onChange={(e) => set({ servings: +e.target.value })} />
        </div>
      </div>

      <div className="field"><label>Description</label>
        <textarea className="textarea" rows="3" value={form.description} onChange={(e) => set({ description: e.target.value })} placeholder="A short, mouth-watering description for the recipe page." />
      </div>

      <div className="field">
        <label>Ingredients <span style={{ color: "var(--error-600)" }}>*</span></label>
        <div className="col" style={{ gap: 6 }}>
          {form.ingredients.map((ing, i) =>
          <div key={i} style={{ display: "flex", gap: 8 }}>
              <input className="input" value={ing} onChange={(e) => updateAt("ingredients", i, e.target.value)} placeholder={`Ingredient ${i + 1} (e.g. 1 cup tri-color quinoa)`} />
              <button className="icon-btn" onClick={() => remove("ingredients", i)} disabled={form.ingredients.length <= 1}><Icon name="trash-2" size={14} /></button>
            </div>
          )}
          <button className="btn ghost sm" style={{ alignSelf: "flex-start" }} onClick={() => addRow("ingredients")}><Icon name="plus" size={14} /> Add ingredient</button>
        </div>
      </div>

      <div className="field">
        <label>Method <span style={{ color: "var(--error-600)" }}>*</span></label>
        <div className="col" style={{ gap: 6 }}>
          {form.steps.map((s, i) =>
          <div key={i} style={{ display: "flex", gap: 8, alignItems: "flex-start" }}>
              <div className="step-num" style={{ marginTop: 6 }}>{i + 1}</div>
              <textarea className="textarea" rows="2" value={s} onChange={(e) => updateAt("steps", i, e.target.value)} placeholder="Describe this step…" />
              <button className="icon-btn" onClick={() => remove("steps", i)} disabled={form.steps.length <= 1}><Icon name="trash-2" size={14} /></button>
            </div>
          )}
          <button className="btn ghost sm" style={{ alignSelf: "flex-start" }} onClick={() => addRow("steps")}><Icon name="plus" size={14} /> Add step</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="field">
          <label>Diet tags</label>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["Vegetarian", "Vegan", "Pescatarian", "Gluten-free", "Dairy-free", "Keto", "Low-carb"].map((t) =>
            <button key={t} className={`chip ${form.diet.includes(t) ? "on" : ""}`} onClick={() => set({ diet: form.diet.includes(t) ? form.diet.filter((x) => x !== t) : [...form.diet, t] })}>{t}</button>
            )}
          </div>
        </div>
        <div className="field">
          <label>Allergens</label>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["Gluten", "Dairy", "Egg", "Soy", "Nut", "Sesame", "Fish", "Shellfish"].map((t) =>
            <button key={t} className={`chip ${form.allergens.includes(t) ? "on" : ""}`} onClick={() => set({ allergens: form.allergens.includes(t) ? form.allergens.filter((x) => x !== t) : [...form.allergens, t] })}>{t}</button>
            )}
          </div>
        </div>
      </div>
    </div>);

}

function StepNutrition({ form, set }) {
  const macros = [
  { key: "calories", label: "Calories (kcal)", unit: "kcal" },
  { key: "protein", label: "Protein", unit: "g" },
  { key: "carbs", label: "Carbs", unit: "g" },
  { key: "fat", label: "Fat", unit: "g" },
  { key: "fiber", label: "Fiber", unit: "g" }];

  return (
    <div className="col" style={{ gap: 18 }}>
      <div className="alert info">
        <Icon name="lightbulb" size={18} />
        <div style={{ fontSize: 14 }}>
          <strong>Laura.al assisted estimate</strong>
          <div style={{ marginTop: 2 }}>Laura can pre fill these from your ingredients list. A dietitian will verify before publish.</div>
        </div>
        <button className="btn sm primary" style={{ marginLeft: "auto" }} onClick={() => {
          const r = RECIPES[0];
          set({ calories: r.calories, protein: r.protein, carbs: r.carbs, fat: r.fat, fiber: r.fiber });
        }}><Icon name="wand-2" size={14} /> Auto fill</button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
        {macros.map((m) =>
        <div key={m.key} className="field">
            <label>{m.label}</label>
            <div style={{ position: "relative" }}>
              <input className="input" type="number" value={form[m.key]} onChange={(e) => set({ [m.key]: e.target.value })} style={{ paddingRight: 36 }} />
              <span style={{ position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)", color: "var(--gray-500)", fontSize: 12, fontWeight: 600 }}>{m.unit}</span>
            </div>
          </div>
        )}
      </div>

      <div className="field">
        <label>Source</label>
        <select className="select" defaultValue="usda">
          <option value="usda">USDA FoodData Central</option>
          <option value="self">Self-calculated</option>
          <option value="lab">Lab analysis</option>
        </select>
        <span className="hint">A dietitian will verify your source before approval.</span>
      </div>
    </div>);

}

function StepReview({ form }) {
  const completion = [
  { key: "Cover image", ok: !!form.coverFile || form.gallery.length > 0 },
  { key: "Title", ok: form.title.trim().length > 2 },
  { key: "Description", ok: form.description.trim().length > 10 },
  { key: "Ingredients", ok: form.ingredients.filter((x) => x.trim()).length >= 3 },
  { key: "Method", ok: form.steps.filter((x) => x.trim()).length >= 1 },
  { key: "Calorie data", ok: Number(form.calories) > 0 },
  { key: "Allergens", ok: form.allergens.length > 0, warn: form.allergens.length === 0 },
  { key: "Alt text", ok: form.altText.length > 0, warn: form.altText.length === 0 }];

  const blocking = completion.filter((c) => !c.ok && !c.warn).length;

  return (
    <div className="col" style={{ gap: 18 }}>
      {blocking > 0 ?
      <div className="alert warning">
          <Icon name="alert-triangle" size={18} />
          <div><strong>{blocking} required fields missing.</strong><div style={{ marginTop: 2 }}>Go back and complete them before submitting.</div></div>
        </div> :

      <div className="alert success">
          <Icon name="check-circle-2" size={18} />
          <div><strong>Looking great.</strong><div style={{ marginTop: 2 }}>Submit for review, a dietitian and compliance officer will respond within 48h.</div></div>
        </div>
      }

      <div className="field">
        <label>Submission checklist</label>
        <div className="card" style={{ padding: 12 }}>
          {completion.map((c) =>
          <div key={c.key} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 4px", borderBottom: "1px solid var(--gray-100)" }}>
              <div className={`stat-icon ${c.ok ? "success" : c.warn ? "warn" : "error"}`} style={{ width: 28, height: 28, borderRadius: 8 }}>
                <Icon name={c.ok ? "check" : c.warn ? "alert-triangle" : "x"} size={14} stroke={2.4} />
              </div>
              <div style={{ flex: 1, fontWeight: 500 }}>{c.key}</div>
              <span className={`pill ${c.ok ? "success" : c.warn ? "warning" : "error"}`}>{c.ok ? "Ready" : c.warn ? "Recommended" : "Required"}</span>
            </div>
          )}
        </div>
      </div>

      <div className="field">
        <label>Publish to locales</label>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {LANGUAGES.map((l) =>
          <button key={l.code} className={`chip ${form.locales.includes(l.code) ? "on" : ""}`}>{l.flag} {l.label}</button>
          )}
        </div>
        <span className="hint">English is auto translated to other selected locales after approval.</span>
      </div>
    </div>);

}

Object.assign(window, { UploadWizard });
