/* NutriDMS, Contributor ↔ Dietitian Question workflow
   Pure Q&A (NOT approval). Contributor: My Questions. Dietitian: Nutrition / Urgent Requests.
   Reads the shared nutridms_questions store via the data.js helpers. */

const { useState: qUseState, useEffect: qUseEffect } = React;

function qFmtTime(ts) {
  const d = Date.now() - ts;
  const m = Math.floor(d / 60000);
  if (m < 1) return "just now";
  if (m < 60) return m + "m ago";
  const h = Math.floor(m / 60);
  if (h < 24) return h + "h ago";
  const days = Math.floor(h / 24);
  return days === 1 ? "Yesterday" : days + "d ago";
}

const Q_STATUS = {
  waiting:  { contributor: { label: "Waiting for Response", cls: "warning" }, dietitian: { label: "New", cls: "warning" } },
  answered: { contributor: { label: "Response Received", cls: "success" }, dietitian: { label: "Answered", cls: "neutral" } },
  clarify:  { contributor: { label: "Needs Clarification", cls: "error" }, dietitian: { label: "Awaiting Contributor", cls: "brand" } },
  closed:   { contributor: { label: "Closed", cls: "neutral" }, dietitian: { label: "Closed", cls: "neutral" } },
};

// Shared live-list hook, refreshes on same-doc and cross-frame writes.
function useQuestions() {
  const [, bump] = qUseState(0);
  qUseEffect(() => {
    const h = () => bump((n) => n + 1);
    window.addEventListener("nutridms-questions", h);
    window.addEventListener("storage", h);
    return () => { window.removeEventListener("nutridms-questions", h); window.removeEventListener("storage", h); };
  }, []);
  return (typeof questionsLoad === "function" ? questionsLoad() : []);
}

// SLA model: urgent questions are same-day (8h target); standard get 48h.
// Returns a state used to color the row + countdown chip.
function qSla(q) {
  const done = q.status === "answered" || q.status === "closed";
  if (done) return { state: "done", label: "Answered", left: 0, done: true };
  const target = q.urgent ? 8 * 3600e3 : 48 * 3600e3;
  const started = q.createdAt || q.updatedAt || Date.now();
  const age = Date.now() - started;
  // Recent items (< 3 days) use the real countdown; older seed data falls back to
  // a stable pseudo-state from its id so the queue shows a believable SLA mix.
  if (age <= 3 * 86400e3) {
    const left = target - age;
    if (left <= 0) return { state: "over", label: "Overdue", left, done: false };
    if (left <= target * 0.35) return { state: "risk", label: qLeft(left) + " left", left, done: false };
    return { state: "ok", label: qLeft(left) + " left", left, done: false };
  }
  let h = 0; const s = String(q.id || ""); for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) & 0xffff;
  if (q.urgent) return h % 2 === 0 ? { state: "over", label: "Overdue", left: 0, done: false } : { state: "risk", label: "2h left", left: 1, done: false };
  const pick = h % 3;
  if (pick === 0) return { state: "ok", label: "1d left", left: 1, done: false };
  if (pick === 1) return { state: "risk", label: "6h left", left: 1, done: false };
  return { state: "over", label: "Overdue", left: 0, done: false };
}
function qLeft(ms) {
  const h = Math.floor(ms / 3600e3);
  if (h >= 24) return Math.floor(h / 24) + "d";
  if (h >= 1) return h + "h";
  return Math.max(1, Math.floor(ms / 60000)) + "m";
}

function QKindBadge({ kind }) {
  const isRec = kind === "recipe";
  return (
    <span className="pill" style={isRec
      ? { background: "var(--green-50)", color: "var(--green-700)", border: "1px solid var(--green-200)" }
      : { background: "#EEF4FF", color: "#3538CD", border: "1px solid #C7D7FE" }}>
      <Icon name={isRec ? "utensils-crossed" : "leaf"} size={11} stroke={2.4} /> {isRec ? "Recipe" : "Ingredient"}
    </span>
  );
}

/* ─────────────── Contributor: My Questions ─────────────── */
function MyQuestionsPage() {
  const { role, setPage, toast } = useApp();
  const me = currentUser(role);
  const all = useQuestions();
  const [openId, setOpenId] = qUseState(null);
  const [showClosed, setShowClosed] = qUseState(false);

  const mine = all.filter((q) => q.contributor && q.contributor.initials === me.initials);
  const open = mine.filter((q) => q.status !== "closed");
  const closed = mine.filter((q) => q.status === "closed");
  const rows = showClosed ? closed : open;
  const active = openId ? all.find((q) => q.id === openId) : null;

  return (
    <div>
      <Crumbs path={[{ label: "Library" }, { label: "My Questions" }]} />
      <div className="page-head">
        <div>
          <h1 className="page-title">My Questions</h1>
          <p className="page-sub">Questions you've asked reviewers while creating content. Answers appear here, no approval needed.</p>
        </div>
      </div>

      <div className="tabs" style={{ marginBottom: 16 }}>
        <button className={!showClosed ? "on" : ""} onClick={() => setShowClosed(false)}>
          <Icon name="inbox" size={14} /> Open
          {open.length > 0 && <span className="q-tab-count">{open.length}</span>}
        </button>
        <button className={showClosed ? "on" : ""} onClick={() => setShowClosed(true)}>
          <Icon name="check-check" size={14} /> Closed
          {closed.length > 0 && <span className="q-tab-count muted">{closed.length}</span>}
        </button>
      </div>

      <div className="card" style={{ overflow: "hidden" }}>
        <table className="table q-table">
          <thead><tr>
            <th>Item</th><th>Type</th><th>Reviewer</th><th>Status</th><th>Updated</th><th style={{ textAlign: "right" }}>Action</th>
          </tr></thead>
          <tbody>
            {rows.map((q) => {
              const st = Q_STATUS[q.status].contributor;
              const needsAttn = q.status === "answered" || q.status === "clarify";
              return (
                <tr key={q.id} onClick={() => setOpenId(q.id)} style={{ cursor: "pointer" }}>
                  <td><div style={{ fontWeight: 600, color: "var(--text-primary)" }}>{q.itemName}</div><div className="muted" style={{ fontSize: 12 }}>{(q.areas || []).join(" · ")}</div></td>
                  <td><QKindBadge kind={q.kind} /></td>
                  <td><div style={{ display: "flex", alignItems: "center", gap: 8 }}><div className="avatar sm" style={{ background: "var(--gray-100)", color: "var(--gray-700)" }}>{q.dietitian.initials}</div><span style={{ fontSize: 13 }}>{q.dietitian.name}</span></div></td>
                  <td><span className={`pill ${st.cls}`}>{q.status === "answered" && <Icon name="check" size={11} stroke={2.6} />}{st.label}</span></td>
                  <td className="muted" style={{ fontSize: 13 }}>{qFmtTime(q.updatedAt)}</td>
                  <td style={{ textAlign: "right" }} onClick={(e) => e.stopPropagation()}>
                    <button className={`btn sm ${needsAttn ? "primary" : "secondary"}`} onClick={() => setOpenId(q.id)}>
                      {needsAttn ? <>Continue <Icon name="arrow-right" size={14} /></> : "View"}
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {rows.length === 0 && (
          <div className="empty">
            <div className="icon"><Icon name="message-circle-question" size={24} /></div>
            <h3>{showClosed ? "No closed questions" : "No open questions"}</h3>
            <p>{showClosed ? "Resolved questions move here." : "Use “Request Guidance” while creating a recipe or ingredient to start one."}</p>
          </div>
        )}
      </div>

      {active && <QuestionDetail q={active} mode="contributor" onClose={() => setOpenId(null)}
        onContinue={(qq) => {
          if (qq.kind === "recipe") {
            if (qq.itemId) { window.__editRecipeId = qq.itemId; setPage("edit-recipe"); }
            else setPage("upload");            // unsaved draft → open the recipe builder
          } else {
            if (qq.itemId) { window.__editIngredientId = qq.itemId; setPage("edit-ingredient"); }
            else setPage("add-ingredient");    // unsaved draft → open the ingredient builder
          }
        }}
        toast={toast} />}
    </div>
  );
}

/* ─────────────── Dietitian: Nutrition / Urgent Requests ─────────────── */
function DietitianRequestsPage() {
  const { role, toast, openRecipe, openIngredient } = useApp();
  const me = currentUser(role);
  const all = useQuestions();
  const [openId, setOpenId] = qUseState(null);
  const [tab, setTab] = qUseState("open");          // open | answered
  const [urgency, setUrgency] = qUseState("all");    // all | urgent | standard
  const [asker, setAsker] = qUseState("all");        // contributor initials or "all"
  const [seeAllPeople, setSeeAllPeople] = qUseState(false);

  const assigned = all.filter((q) => q.dietitian && q.dietitian.initials === me.initials);
  // Distinct askers for the people-filter dropdown
  const askers = [];
  assigned.forEach((q) => { if (q.contributor && !askers.some((a) => a.initials === q.contributor.initials)) askers.push(q.contributor); });

  const matches = (q) => (urgency === "all" || (urgency === "urgent" ? q.urgent : !q.urgent)) && (asker === "all" || (q.contributor && q.contributor.initials === asker));
  const inTab = (q) => tab === "open" ? (q.status === "waiting" || q.status === "clarify") : (q.status === "answered" || q.status === "closed");
  const openCount = assigned.filter((q) => q.status === "waiting" || q.status === "clarify").length;
  const doneCount = assigned.filter((q) => q.status === "answered" || q.status === "closed").length;
  const rows = assigned.filter((q) => inTab(q) && matches(q));
  const active = openId ? all.find((q) => q.id === openId) : null;
  // Per-asker open counts for the left people rail
  const askerOpen = (ini) => assigned.filter((q) => (q.status === "waiting" || q.status === "clarify") && q.contributor && q.contributor.initials === ini).length;

  const URG = [
    { id: "all", label: "All" },
    { id: "urgent", label: "Urgent" },
    { id: "standard", label: "Standard" },
  ];

  return (
    <div>
      <Crumbs path={[{ label: "QA Review" }, { label: "Nutrition Requests" }]} />
      <div className="page-head">
        <div>
          <h1 className="page-title">Nutrition Requests</h1>
          <p className="page-sub">Questions from contributors about nutrition, allergens, and tags. Urgent ones need a same-day answer.</p>
        </div>
      </div>

      <QAKpiRow items={[
        { icon: "inbox", value: openCount, label: "To answer", tone: "warn" },
        { icon: "alert-triangle", value: assigned.filter((q) => q.urgent && (q.status === "waiting" || q.status === "clarify")).length, label: "Urgent open", tone: "crit" },
        { icon: "check-check", value: doneCount, label: "Answered", tone: "" },
        { icon: "user-search", value: askers.length, label: "People asking", tone: "info" },
      ]} />

      <div className="q-layout">
        <aside className="q-people">
          <div className="q-people-h">People asking</div>
          <button className={"q-person" + (asker === "all" ? " on" : "")} onClick={() => setAsker("all")}>
            <span className="q-person-av all"><Icon name="users" size={15} /></span>
            <span className="q-person-tx"><strong>Everyone</strong><small>All contributors</small></span>
            <span className="q-person-n">{openCount}</span>
          </button>
          {(seeAllPeople ? askers : askers.slice(0, 4)).map((a) => (
            <button key={a.initials} className={"q-person" + (asker === a.initials ? " on" : "")} onClick={() => setAsker(a.initials)}>
              <span className="avatar q-person-av">{a.initials}</span>
              <span className="q-person-tx"><strong>{a.name}</strong>{a.role && <small>{a.role}</small>}</span>
              <span className="q-person-n">{askerOpen(a.initials)}</span>
            </button>
          ))}
          {askers.length > 4 && (
            <button className="q-people-seeall" onClick={() => setSeeAllPeople((v) => !v)}>
              {seeAllPeople ? "Show less" : `See all (${askers.length})`}
              <Icon name={seeAllPeople ? "chevron-up" : "chevron-down"} size={14} />
            </button>
          )}
          {askers.length === 0 && <div className="q-people-empty">No one is waiting on you.</div>}
        </aside>

        <div className="q-main">
          {/* Toolbar: everything right-aligned, no top menu bar */}
          <div className="q-toolbar">
            <span className="q-filter-count">{rows.length} request{rows.length === 1 ? "" : "s"}</span>
            <div className="q-toolbar-right">
              {URG.map((u) => (
                <button key={u.id} className={"q-pill" + (urgency === u.id ? " on" : "")} onClick={() => setUrgency(u.id)}>
                  {u.id === "urgent" && <Icon name="alert-triangle" size={13} stroke={2.6} />}{u.label}
                </button>
              ))}
              {(urgency !== "all" || asker !== "all") && (
                <button className="q-clear" onClick={() => { setUrgency("all"); setAsker("all"); }}><Icon name="x" size={13} stroke={2.6} /> Clear</button>
              )}
              <button className={"q-pill" + (tab === "open" ? " on" : "")} onClick={() => setTab("open")}>
                <Icon name="inbox" size={14} stroke={2.4} /> To answer
                {openCount > 0 && <span className="q-tab-count">{openCount}</span>}
              </button>
              <button className={"q-pill" + (tab === "answered" ? " on" : "")} onClick={() => setTab("answered")}>
                <Icon name="check-check" size={14} stroke={2.4} /> Answered
                {doneCount > 0 && <span className="q-tab-count muted">{doneCount}</span>}
              </button>
            </div>
          </div>

          <div className="q-req-list">
        {rows.map((q) => {
          const st = Q_STATUS[q.status].dietitian;
          const sla = qSla(q);
          const last = (q.thread || [])[(q.thread || []).length - 1];
          return (
            <button key={q.id} className={`q-row sla-${sla.state}${q.urgent ? " urgent" : ""}`} onClick={() => setOpenId(q.id)}>
              <span className="q-row-rail" />
              <span className="avatar q-row-av">{q.contributor.initials}</span>
              <span className="q-row-main">
                <span className="q-row-line1">
                  <strong className="q-row-name">{q.itemName}</strong>
                  <QKindBadge kind={q.kind} />
                  {q.urgent && <span className="q-tag-urgent"><Icon name="alert-triangle" size={10} stroke={2.8} /> Urgent</span>}
                </span>
                <span className="q-row-msg">{q.message}</span>
                <span className="q-row-meta">
                  <span className="q-row-asker">{q.contributor.name}</span>
                  <span className="q-dot">·</span>
                  <span className="muted">{(q.areas || []).slice(0, 2).join(", ")}</span>
                  {last && last.from === "contributor" && q.status !== "waiting" && <><span className="q-dot">·</span><span className="muted">you replied {qFmtTime(last.at)}</span></>}
                </span>
              </span>
              <span className="q-row-right">
                <span className={`q-sla q-sla-${sla.state}`}>
                  {sla.state === "over" && <Icon name="alert-triangle" size={11} stroke={2.6} />}
                  {sla.state === "risk" && <Icon name="clock" size={11} stroke={2.6} />}
                  {sla.state === "done" && <Icon name="check" size={11} stroke={2.8} />}
                  {sla.label}
                </span>
                <span className={`pill ${st.cls}`}>{st.label}</span>
                <span className="q-row-cta">{tab === "open" ? <>Answer <Icon name="arrow-right" size={14} /></> : <>View <Icon name="arrow-right" size={14} /></>}</span>
              </span>
            </button>
          );
        })}
        {rows.length === 0 && (
          <div className="empty">
            <div className="icon"><Icon name="check-check" size={24} /></div>
            <h3>{(urgency !== "all" || asker !== "all") ? "No matching requests" : tab === "open" ? "All caught up" : "Nothing answered yet"}</h3>
            <p>{(urgency !== "all" || asker !== "all") ? "Try clearing the filters." : tab === "open" ? "No open questions assigned to you." : "Questions you answer will appear here."}</p>
          </div>
        )}
          </div>
        </div>
      </div>

      {active && <QuestionDetail q={active} mode="dietitian" onClose={() => setOpenId(null)} toast={toast} reviewer={me}
        onView={(qq) => {
          if (qq.kind === "recipe") { const r = (window.RECIPES || []).find((x) => x.id === qq.itemId); if (r && openRecipe) return openRecipe(r); }
          else { const g = (window.INGREDIENT_ITEMS || []).find((x) => x.id === qq.itemId); if (g && openIngredient) return openIngredient(g); }
          toast && toast("This draft isn't saved yet, nothing to open.");
        }} />}
    </div>
  );
}

/* ─────────────── Shared question detail drawer ─────────────── */
function QuestionDetail({ q, mode, onClose, onContinue, onView, toast, reviewer }) {
  const [reply, setReply] = qUseState("");
  const [followOpen, setFollowOpen] = qUseState(false);
  const [confirmClose, setConfirmClose] = qUseState(false);
  const isDietitian = mode === "dietitian";
  const st = Q_STATUS[q.status][mode];

  qUseEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, []);

  const sendResponse = () => {
    if (!reply.trim() || !window.questionReply) return;
    window.questionReply(q.id, "dietitian", (reviewer && reviewer.name) || "Reviewer", reply.trim(), "answered");
    toast && toast("Response sent to " + q.contributor.name);
    onClose();
  };
  const requestClarification = () => {
    if (!reply.trim() || !window.questionReply) return;
    window.questionReply(q.id, "dietitian", (reviewer && reviewer.name) || "Reviewer", reply.trim(), "clarify");
    toast && toast("Clarification requested");
    onClose();
  };
  const sendFollowUp = () => {
    if (!reply.trim() || !window.questionReply) return;
    window.questionReply(q.id, "contributor", q.contributor.name, reply.trim(), "waiting");
    toast && toast("Follow-up sent");
    setReply(""); setFollowOpen(false);
  };
  const closeQuestion = () => { if (window.questionUpdate) { window.questionUpdate(q.id, { status: "closed" }); toast && toast("Question closed"); onClose(); } };

  return ReactDOM.createPortal(
    <div className="qd-bg" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="qd" role="dialog" aria-label="Question">
        <div className="qd-head">
          <div style={{ minWidth: 0 }}>
            <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8, flexWrap: "wrap" }}>
              <QKindBadge kind={q.kind} />
              {q.urgent && <span className="pill" style={{ background: "#FEF0C7", color: "#b54708", border: "1px solid #FEDF89" }}><Icon name="alert-triangle" size={11} stroke={2.6} /> Urgent</span>}
              <span className={`pill ${st.cls}`}>{st.label}</span>
            </div>
            <h3 style={{ margin: 0, fontFamily: "var(--serif)", fontSize: 22, letterSpacing: "-.01em" }}>{q.itemName}</h3>
            <p style={{ margin: "4px 0 0", color: "var(--gray-600)", fontSize: 13 }}>
              {isDietitian ? <>Asked by {q.contributor.name}</> : <>Assigned to {q.dietitian.name}</>} · {(q.areas || []).join(", ")}
            </p>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="qd-body">
          <div className="qd-areas">
            <span className="qd-areas-h">Selected fields</span>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {(q.areas || []).map((a) => <span key={a} className="qd-area-pill">{a}</span>)}
            </div>
          </div>

          <div className="qd-thread">
            {(q.thread || []).map((m, i) => {
              const fromDiet = m.from === "dietitian";
              return (
                <div key={i} className={`qd-msg ${fromDiet ? "diet" : "contrib"}`}>
                  <div className="qd-msg-head">
                    <span className="avatar sm" style={{ background: fromDiet ? "var(--green-100)" : "var(--gray-100)", color: fromDiet ? "var(--green-700)" : "var(--gray-700)" }}>{(m.who || "?").split(" ").map((w) => w[0]).join("").slice(0, 2)}</span>
                    <strong>{m.who}</strong>
                    {fromDiet && <span className="qd-role-tag">Reviewer</span>}
                    <span className="muted" style={{ marginLeft: "auto", fontSize: 12 }}>{qFmtTime(m.at)}</span>
                  </div>
                  <p className="qd-msg-text">{m.text}</p>
                </div>
              );
            })}
          </div>
        </div>

        <div className="qd-foot">
          {isDietitian ? (
            q.status === "answered" || q.status === "closed" ? (
              <div style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--green-700)", fontSize: 13, fontWeight: 600 }}><Icon name="check-circle-2" size={16} /> You've answered this question.</span>
                <button className="btn secondary" style={{ marginLeft: "auto" }} onClick={() => onView && onView(q)}><Icon name="external-link" size={15} /> View {q.kind}</button>
              </div>
            ) : (
              <div style={{ width: "100%" }}>
                <textarea className="qd-reply" rows="3" value={reply} onChange={(e) => setReply(e.target.value)} placeholder="Type your answer, e.g. Use the USDA value of 12.6g protein per 100g." />
                <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", marginTop: 10, flexWrap: "wrap" }}>
                  <button className="btn ghost" onClick={() => onView && onView(q)}><Icon name="external-link" size={15} /> View {q.kind}</button>
                  <button className="btn secondary" disabled={!reply.trim()} onClick={requestClarification}><Icon name="help-circle" size={15} /> Request clarification</button>
                  <button className="btn primary" disabled={!reply.trim()} onClick={sendResponse}><Icon name="send" size={15} /> Send Response</button>
                </div>
              </div>
            )
          ) : q.status === "closed" ? (
            <div style={{ width: "100%", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
              <span style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--gray-600)", fontSize: 13, fontWeight: 600 }}><Icon name="check-check" size={16} /> This question is closed.</span>
              <button className="btn secondary" style={{ marginLeft: "auto" }} onClick={() => onContinue && onContinue(q)}><Icon name="pencil" size={15} /> Open item</button>
            </div>
          ) : (
            <div style={{ width: "100%" }}>
              {followOpen && (
                <div style={{ marginBottom: 10 }}>
                  <textarea className="qd-reply" rows="3" value={reply} onChange={(e) => setReply(e.target.value)} placeholder="Add a follow-up question…" />
                  <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 8 }}>
                    <button className="btn ghost sm" onClick={() => { setFollowOpen(false); setReply(""); }}>Cancel</button>
                    <button className="btn primary sm" disabled={!reply.trim()} onClick={sendFollowUp}><Icon name="send" size={14} /> Send follow-up</button>
                  </div>
                </div>
              )}
              {confirmClose ? (
                <div className="qd-confirm">
                  <div className="qd-confirm-txt"><strong>Close this question?</strong> It moves to <strong>Closed</strong> and drops from your open count. You can still reopen the item to keep editing.</div>
                  <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
                    <button className="btn ghost sm" onClick={() => setConfirmClose(false)}>Cancel</button>
                    <button className="btn primary sm" onClick={closeQuestion}><Icon name="check-check" size={14} /> Yes, close</button>
                  </div>
                </div>
              ) : (
                <>
                  {q.status === "answered" && !followOpen && (
                    <div className="qd-resolve-hint"><Icon name="info" size={13} stroke={2.4} /> Applied the reviewer's answer? Close this question when you're done.</div>
                  )}
                  <div style={{ display: "flex", gap: 10, justifyContent: "flex-end", flexWrap: "wrap" }}>
                    <button className="btn ghost" onClick={() => setConfirmClose(true)}><Icon name="check-check" size={15} /> Close Question</button>
                    {!followOpen && <button className="btn secondary" onClick={() => setFollowOpen(true)}><Icon name="message-circle-plus" size={15} /> Ask Follow-up</button>}
                    <button className="btn primary" onClick={() => onContinue && onContinue(q)}><Icon name="pencil" size={15} /> Continue Editing</button>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </div>, document.body);
}

Object.assign(window, { MyQuestionsPage, DietitianRequestsPage });
