/* NutriDMS, Review Feedback
   Rich reviewer-feedback addressing screen for BOTH recipes and ingredients.
   Reached from the Feedback page. Contributor reviews each reviewer comment,
   replies, marks resolved, then resubmits for review. */

function buildRecipeFeedback(r) {
  const ing = r.ingredients || [];
  return [
    { id: "fb1", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Basic Info", field: "Description", status: "needs-revision",
      submission: r.description, comment: "The description is too brief. Please add more details about the flavor profile, health benefits, and what makes this dish unique. Aim for at least 2-3 sentences." },
    { id: "fb2", who: "Dr. Sarah Chen", initials: "SC", role: "Compliance Feedback", when: "2 hours ago", cat: "Ingredients", field: "Quantities", status: "needs-revision",
      submission: ing.slice(0, 3).join(" · "), comment: "Please specify whether the lentils should be dried or pre-cooked. Also, the garlic quantity seems too low for this serving size." },
    { id: "fb3", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Ingredients", field: "Cook time", status: "needs-revision",
      submission: `Cook: ${r.duration} min`, comment: "The cooking time specified may not be sufficient for the lentils to become tender. Consider updating to 25-30 minutes, or specifying to use red lentils which cook faster." },
    { id: "fb4", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Instructions", field: "Step detail", status: "needs-revision",
      submission: (r.steps && r.steps[0]) || "—", comment: "The first step needs more detail on technique, clarify how long to simmer and at what heat before moving on." },
    { id: "fb5", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Complementary Dish", field: "Pairing", status: "needs-revision",
      submission: "No pairing provided", comment: "Consider adding a complementary side (e.g. steamed basmati or naan) to round out the meal for the menu listing." },
    { id: "fb6", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Reference", field: "Dish name", status: "approved",
      submission: `Dish name: '${r.name}'`, comment: `The dish name '${r.name}' is clear and descriptive. Approved.` },
    { id: "fb7", who: "Dr. Sarah Chen", initials: "SC", role: "Compliance Feedback", when: "2 hours ago", cat: "Reference", field: "Allergens", status: "approved",
      submission: (r.allergens || []).join(", ") || "None declared", comment: "Allergen declarations match the ingredient list. Approved." },
  ];
}

function buildIngredientFeedback(i) {
  return [
    { id: "fb1", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Basic Info", field: "Name", status: "approved",
      submission: `${i.name} (${i.canonical})`, comment: "Scientific name and category are correct and clearly described. Approved." },
    { id: "fb2", who: "Dr. Sarah Chen", initials: "SC", role: "Compliance Feedback", when: "2 hours ago", cat: "Nutrition", field: "Macros", status: "needs-revision",
      submission: `${i.nutr.calories} kcal · P ${i.nutr.p}g · C ${i.nutr.c}g · F ${i.nutr.f}g (per 100g)`, comment: "The fat value per 100g looks off versus USDA FoodData Central. Please re-verify and attach the source row before approval." },
    { id: "fb3", who: "Dr. Sarah Chen", initials: "SC", role: "Compliance Feedback", when: "2 hours ago", cat: "Allergens", field: "Declaration", status: i.allergens && i.allergens.length ? "needs-revision" : "approved",
      submission: (i.allergens || []).join(", ") || "None declared", comment: i.allergens && i.allergens.length ? "Allergen present, confirm cross-contamination handling notes are attached for this ingredient." : "No allergens, declaration looks complete." },
    { id: "fb4", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Sourcing", field: "Source", status: "needs-revision",
      submission: "USDA FoodData Central", comment: "Please attach the FDC ID and the default serving size so downstream recipes map correctly." },
    { id: "fb5", who: "Dr. Sarah Chen", initials: "SC", role: "Reviewer Feedback", when: "2 hours ago", cat: "Reference", field: "Usage", status: "approved",
      submission: "Linked to recipes", comment: "Ingredient is correctly linked to its master record. Approved." },
  ];
}

const RF_CATS_RECIPE = ["Basic Info", "Ingredients", "Instructions", "Nutrition", "Complementary Dish", "Reference"];
const RF_CATS_ING = ["Basic Info", "Nutrition", "Allergens", "Sourcing", "Reference"];

function ReviewFeedback() {
  const { activeRecipe, activeIngredient, reviewKind, setActiveRecipe, setActiveIngredient, setPage, toast } = useApp();
  const kind = reviewKind || (activeIngredient ? "ingredient" : "recipe");
  const item = kind === "ingredient" ? activeIngredient : activeRecipe;
  if (!item) return null;

  const allFeedback = React.useMemo(() => kind === "ingredient" ? buildIngredientFeedback(item) : buildRecipeFeedback(item), [item, kind]);
  const cats = kind === "ingredient" ? RF_CATS_ING : RF_CATS_RECIPE;

  const [activeCat, setActiveCat] = React.useState("all");
  const [addressed, setAddressed] = React.useState(() => new Set());
  const [replyOpen, setReplyOpen] = React.useState(null);
  const [replyText, setReplyText] = React.useState("");
  const [repliesSent, setRepliesSent] = React.useState(() => new Set());
  const [collapsed, setCollapsed] = React.useState(() => new Set());
  const [fixOpen, setFixOpen] = React.useState(null);
  const [fixText, setFixText] = React.useState("");
  const [fixed, setFixed] = React.useState(() => ({}));
  const [resubmitOpen, setResubmitOpen] = React.useState(false);
  const [confirmChecked, setConfirmChecked] = React.useState(false);
  const [notes, setNotes] = React.useState("");
  const [success, setSuccess] = React.useState(false);

  // Items that REQUIRE action (needs-revision); approved ones are informational
  const actionable = allFeedback.filter(f => f.status === "needs-revision");
  const addressedCount = actionable.filter(f => addressed.has(f.id)).length;
  const totalActionable = actionable.length;
  const shown = activeCat === "all" ? allFeedback : allFeedback.filter(f => f.cat === activeCat);

  const markAddressed = (id) => { setAddressed(s => { const n = new Set(s); n.add(id); return n; }); toast("Feedback marked as addressed"); };
  const undoAddressed = (id) => setAddressed(s => { const n = new Set(s); n.delete(id); return n; });
  const sendReply = (id) => { setRepliesSent(s => { const n = new Set(s); n.add(id); return n; }); setReplyOpen(null); setReplyText(""); toast("Reply sent to reviewer"); };
  const toggleCollapse = (id) => setCollapsed(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const openFix = (f) => { setFixOpen(f.id); setFixText(fixed[f.id] != null ? fixed[f.id] : f.submission); setReplyOpen(null); };
  const saveFix = (id) => {
    setFixed(m => ({ ...m, [id]: fixText }));
    setAddressed(s => { const n = new Set(s); n.add(id); return n; });
    setFixOpen(null);
    toast("Issue fixed & marked resolved");
  };

  const catCount = (c) => allFeedback.filter(f => f.cat === c).length;
  const back = () => { setPage("feedback"); setActiveRecipe(null); setActiveIngredient(null); };
  const editTarget = () => { if (kind === "ingredient") { window.__editIngredientId = item.id; setPage("edit-ingredient"); } else { setPage("upload"); } };

  // Gallery sources
  const gallery = kind === "recipe"
    ? [item.cover, item.cover + "&sat=-20", item.cover + "&flip=h", item.cover + "&blur=2"]
    : null;

  const statusPill = (s) => s === "approved"
    ? <span className="rf-status approved"><Icon name="check" size={11} stroke={2.6} /> Approved</span>
    : <span className="rf-status revision">Needs Revision</span>;

  return (
    <div className="rf">
      <Crumbs path={[
        { label: kind === "ingredient" ? "Ingredient Library" : "Browse Recipes", onClick: back },
        { label: "Review Feedback" }
      ]} />

      <div className="rf-head">
        <div style={{ minWidth: 0 }}>
          <div style={{ marginBottom: 8 }}><StatusPill status={item.status} /></div>
          <h1 className="rf-title">Review Feedback</h1>
          <p className="rf-sub">View and address reviewer feedback for your {kind} submission.</p>
        </div>
        <div className="rf-head-actions">
          <button className="btn secondary" onClick={editTarget}><Icon name="pencil" size={16} /> Edit {kind === "ingredient" ? "Ingredient" : "Recipe"}</button>
          <button className="btn primary" onClick={() => { setResubmitOpen(true); setConfirmChecked(false); }}><Icon name="send" size={16} /> Resubmit for Review</button>
        </div>
      </div>

      {/* Media / identity */}
      <h3 className="rf-section-label">{kind === "recipe" ? "Recipe Images" : "Ingredient"}</h3>
      {kind === "recipe" ? (
        <div className="rf-gallery">
          <div className="rf-gallery-main" style={{ backgroundImage: `url("${gallery[0]}")` }} />
          <div className="rf-gallery-grid">
            <div className="rf-gallery-wide" style={{ backgroundImage: `url("${gallery[1]}")` }} />
            <div className="rf-gallery-thumb" style={{ backgroundImage: `url("${gallery[2]}")` }} />
            <div className="rf-gallery-thumb" style={{ backgroundImage: `url("${gallery[3]}")` }} />
          </div>
        </div>
      ) : (
        <div className="rf-ing-hero">
          <div className="rf-ing-banner"><Icon name="leaf" size={64} stroke={1.3} /></div>
          <span className="tag" style={{ position: "absolute", left: 16, bottom: 16, background: "rgba(255,255,255,.92)", color: "var(--green-700)", fontWeight: 700 }}>{item.category}</span>
        </div>
      )}

      <p className="rf-desc">{kind === "recipe" ? item.description : `${item.canonical} · ${item.category}`}</p>
      <div className="rf-meta">
        {kind === "recipe" ? (
          <>
            <span><Icon name="clock" size={14} /> Prep: 15 min</span>
            <span><Icon name="flame" size={14} /> Cook: {item.duration} min</span>
            <span><Icon name="users" size={14} /> Serves: {item.servings}</span>
          </>
        ) : (
          <>
            <span><Icon name="zap" size={14} /> {item.nutr.calories} kcal / 100g</span>
            <span><Icon name="tag" size={14} /> {item.category}</span>
            <span><Icon name="git-commit-horizontal" size={14} /> v{item.ver || 1}</span>
          </>
        )}
      </div>

      {/* Progress summary, what to do, at a glance */}
      <div className="rf-summary">
        <div className="rf-summary-ic" style={addressedCount >= totalActionable ? { background: "var(--green-100)", color: "var(--green-700)" } : {}}>
          <Icon name={addressedCount >= totalActionable ? "check-check" : "list-checks"} size={18} />
        </div>
        <div className="rf-summary-text">
          <strong>{addressedCount >= totalActionable ? "All issues resolved, ready to resubmit" : `${totalActionable - addressedCount} issue${totalActionable - addressedCount === 1 ? "" : "s"} to fix`}</strong>
          <span>Fix each flagged item below, then resubmit for review. Approved items need no action.</span>
        </div>
        <div className="rf-summary-prog">
          <div className="progress" style={{ width: 120, background: "var(--gray-100)" }}><i style={{ width: `${totalActionable ? (addressedCount / totalActionable) * 100 : 100}%`, background: "var(--green-600)" }} /></div>
          <span className="rf-summary-count">{addressedCount}/{totalActionable}</span>
        </div>
      </div>

      {/* Category tabs */}
      <div className="rf-tabs">
        <button className={`rf-tab ${activeCat === "all" ? "on" : ""}`} onClick={() => setActiveCat("all")}>All <span className="rf-tab-c">{allFeedback.length}</span></button>
        {cats.map(c => {
          const n = catCount(c);
          return <button key={c} className={`rf-tab ${activeCat === c ? "on" : ""}`} onClick={() => setActiveCat(c)} disabled={n === 0} style={n === 0 ? { opacity: .45 } : {}}>
            {c}{n > 0 && <span className="rf-tab-c">{n}</span>}
          </button>;
        })}
      </div>

      {/* Feedback cards */}
      <div className="rf-list">
        {shown.map(f => {
          const isAddressed = addressed.has(f.id);
          const isCollapsed = collapsed.has(f.id);
          const replied = repliesSent.has(f.id);
          const needsAction = f.status === "needs-revision";
          return (
            <div key={f.id} className={`rf-card ${isAddressed ? "done" : ""}`}>
              <div className="rf-card-top">
                <div className="rf-card-who">
                  <div className="avatar sm" style={{ background: "var(--gray-100)", color: "var(--gray-700)" }}>{f.initials}</div>
                  <div>
                    <div className="rf-who-line"><strong>{f.who}</strong><span className="rf-role">· {f.role}</span><span className="rf-when">· {f.when}</span></div>
                    <div className="rf-cat-line"><span className="rf-cat-tag">{f.cat}</span><span className="rf-arrow">→ {f.field}</span></div>
                  </div>
                </div>
                <div className="rf-card-meta">
                  {isAddressed ? <span className="rf-status addressed"><Icon name="check" size={11} stroke={2.6} /> Addressed</span> : statusPill(f.status)}
                  <button className="rf-collapse" onClick={() => toggleCollapse(f.id)}><Icon name={isCollapsed ? "chevron-down" : "chevron-up"} size={16} /></button>
                </div>
              </div>

              {!isCollapsed && (
                <div className="rf-card-body">
                  <div className="rf-comment"><Icon name="message-circle" size={14} /> <span>{f.comment}</span></div>

                  <div className={`rf-submission ${fixed[f.id] != null ? "fixed" : ""}`}>
                    <div className="rf-submission-label">{fixed[f.id] != null ? "Updated value" : "Your submission"}</div>
                    <div className="rf-submission-text">{fixed[f.id] != null ? fixed[f.id] : f.submission}</div>
                  </div>

                  {/* Inline fix editor */}
                  {needsAction && fixOpen === f.id && (
                    <div className="rf-fix">
                      <div className="rf-fix-label"><Icon name="wand-2" size={13} /> Fix “{f.field}”, {f.cat}</div>
                      <textarea className="textarea" rows="3" value={fixText} onChange={e => setFixText(e.target.value)} placeholder={`Enter the corrected ${f.field.toLowerCase()}…`} autoFocus />
                      <div className="rf-fix-hint">Tip: address exactly what the reviewer asked, “{f.comment.slice(0, 60)}{f.comment.length > 60 ? "…" : ""}”</div>
                      <div className="rf-reply-actions">
                        <button className="btn ghost sm" onClick={() => setFixOpen(null)}>Cancel</button>
                        <button className="btn success-solid sm" disabled={!fixText.trim()} onClick={() => saveFix(f.id)}><Icon name="check" size={13} /> Save &amp; resolve</button>
                      </div>
                    </div>
                  )}

                  {/* Reply editor */}
                  {needsAction && replyOpen === f.id && (
                    <div className="rf-reply">
                      <textarea className="textarea" rows="3" placeholder="Write your reply to the reviewer…" value={replyText} onChange={e => setReplyText(e.target.value)} />
                      <div className="rf-reply-actions">
                        <button className="btn ghost sm" onClick={() => { setReplyOpen(null); setReplyText(""); }}>Cancel</button>
                        <button className="btn primary sm" disabled={!replyText.trim()} onClick={() => sendReply(f.id)}><Icon name="send" size={13} /> Send Reply</button>
                      </div>
                    </div>
                  )}

                  {/* Action bar */}
                  {needsAction && fixOpen !== f.id && replyOpen !== f.id && (
                    isAddressed ? (
                      <div className="rf-card-actions">
                        <span className="rf-addressed-note"><Icon name="check-circle-2" size={14} /> Resolved</span>
                        <button className="btn ghost sm" onClick={() => openFix(f)}><Icon name="pencil" size={13} /> Edit fix</button>
                        <button className="btn ghost sm" onClick={() => undoAddressed(f.id)}>Reopen</button>
                      </div>
                    ) : (
                      <div className="rf-card-actions">
                        <button className="btn success-solid sm" onClick={() => openFix(f)}><Icon name="wand-2" size={13} /> Fix this issue</button>
                        {replied
                          ? <span className="rf-reply-sent"><Icon name="check-circle-2" size={14} /> Reply sent</span>
                          : <button className="btn secondary sm" onClick={() => setReplyOpen(f.id)}><Icon name="reply" size={13} /> Reply</button>}
                        <button className="btn ghost sm" onClick={() => markAddressed(f.id)}>Mark resolved</button>
                      </div>
                    )
                  )}
                </div>
              )}
            </div>
          );
        })}
        {shown.length === 0 && <div className="muted" style={{ padding: 20, textAlign: "center" }}>No feedback in this category.</div>}
      </div>

      {/* Resubmit modal */}
      <Modal open={resubmitOpen} onClose={() => setResubmitOpen(false)} title="Resubmit for Review" subtitle={`Submit your updated ${kind} for another round of review.`} footer={
        <>
          <button className="btn ghost" onClick={() => setResubmitOpen(false)}>Cancel</button>
          <button className="btn primary" disabled={!confirmChecked} onClick={() => { setResubmitOpen(false); setSuccess(true); }}><Icon name="send" size={14} /> Submit for Review</button>
        </>
      }>
        <div className="rf-modal-item">
          <div className="rf-modal-ic"><Icon name={kind === "ingredient" ? "leaf" : "file-text"} size={18} /></div>
          <div><div style={{ fontWeight: 800 }}>{item.name}</div><div className="muted" style={{ fontSize: 12.5 }}>{kind === "ingredient" ? "Ingredient" : "Recipe"} Submission</div></div>
        </div>
        <div className="rf-progress-head">
          <span style={{ fontWeight: 700, fontSize: 13 }}>Feedback Progress</span>
          <span style={{ fontWeight: 800, fontSize: 13 }}>{addressedCount} of {totalActionable} addressed</span>
        </div>
        <div className="progress" style={{ height: 8, background: "var(--gray-100)" }}><i style={{ width: `${totalActionable ? (addressedCount / totalActionable) * 100 : 100}%`, background: "var(--green-600)" }} /></div>
        {addressedCount < totalActionable && (
          <div className="rf-warn"><Icon name="alert-triangle" size={15} /> You have {totalActionable - addressedCount} unaddressed feedback item{totalActionable - addressedCount === 1 ? "" : "s"}</div>
        )}
        <div className="field" style={{ marginTop: 14 }}>
          <label>Notes for Reviewer (Optional)</label>
          <textarea className="textarea" rows="4" placeholder="Add any notes about the changes you made or questions for the reviewer…" value={notes} onChange={e => setNotes(e.target.value)} />
          <div className="muted" style={{ fontSize: 11, textAlign: "right", marginTop: 4 }}>{notes.length} characters · {notes.trim() ? notes.trim().split(/\s+/).length : 0} words</div>
        </div>
        <label className="rf-confirm">
          <input type="checkbox" checked={confirmChecked} onChange={e => setConfirmChecked(e.target.checked)} />
          <span>I have reviewed all feedback and made the necessary changes to my {kind} submission.</span>
        </label>
      </Modal>

      {/* Success modal */}
      {success && (
        <div className="modal-bg" style={{ display: "grid", placeItems: "center" }} onMouseDown={e => { if (e.target === e.currentTarget) { setSuccess(false); back(); } }}>
          <div className="card" style={{ width: 480, maxWidth: "94vw", padding: "36px 32px", textAlign: "center", position: "relative" }}>
            <button className="icon-btn" style={{ position: "absolute", top: 14, right: 14 }} onClick={() => { setSuccess(false); back(); }}><Icon name="x" size={18} /></button>
            <div className="rf-success-ic"><Icon name="check" size={30} stroke={2.6} /></div>
            <h2 style={{ fontFamily: "var(--serif)", fontSize: 28, margin: "16px 0 8px" }}>{kind === "ingredient" ? "Ingredient" : "Recipe"} Submitted Successfully!</h2>
            <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.5, maxWidth: 380, margin: "0 auto" }}>
              Your {kind} has been sent for review. Our team will review your submission and notify you once it's approved for publishing. You can track the status in "My Contributions."
            </p>
            <div style={{ display: "flex", gap: 10, justifyContent: "center", marginTop: 22 }}>
              <button className="btn primary" onClick={() => { setSuccess(false); back(); }}>Back to Feedback</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ReviewFeedback });
