// FRM-PROC-06 · My responses
const ResponseCard = ({ resp, onOpen }) => {
  const { Pill } = window.Fm;
  const Ic = window.Icons, FD = window.FD;
  const delivering = resp.status === "confirmed";
  const completed = resp.status === "completed";
  return (
    <div className="fm-req" style={{ marginBottom: 12 }} onClick={onOpen}>
      <div className="fm-req-top" style={{ marginBottom: 12 }}>
        <span className={`fm-req-thumb ${resp.variety === "Fuerte" ? "fuerte" : ""}`}><Ic.Leaf size={20}/></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="fm-req-id">{resp.reqId}</div>
          <div className="fm-req-title" style={{ fontSize: 14.5 }}>{resp.title}</div>
        </div>
        <Pill status={resp.status}/>
      </div>

      {completed ? (
        <div className="fm-req-grid" style={{ marginBottom: 10 }}>
          <div className="fm-req-cell"><div className="k">Delivered</div><div className="v">{Number(resp.actualWeight).toLocaleString("en-US")}<small> kg</small></div></div>
          <div className="fm-req-cell"><div className="k">Payment</div><div className="v" style={{ fontSize: 14 }}>{FD.PAY_LABEL[resp.payStatus] || "—"}</div></div>
        </div>
      ) : delivering ? (
        <div className="fm-req-grid" style={{ marginBottom: 10 }}>
          <div className="fm-req-cell"><div className="k">Deliver by</div><div className="v" style={{ fontSize: 14 }}>{resp.slotDate.replace(" 2026", "")}</div></div>
          <div className="fm-req-cell"><div className="k">Allocated</div><div className="v">{Number(resp.allocatedQty).toLocaleString("en-US")}<small> kg</small></div></div>
        </div>
      ) : (
        <div className="fm-req-grid" style={{ marginBottom: 10 }}>
          <div className="fm-req-cell"><div className="k">You offered</div><div className="v">{Number(resp.qty).toLocaleString("en-US")}<small> kg</small></div></div>
          <div className="fm-req-cell"><div className="k">Your rate</div><div className="v">{FD.KES(resp.rate)}<small> /kg</small></div></div>
        </div>
      )}

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 12 }} className="muted">
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          {resp.queued ? <><Ic.WifiOff size={13}/> Will sync when online</>
            : delivering ? <><Ic.Truck size={13}/> Gate pass ready · {resp.gpn}</>
            : completed ? <><Ic.CheckCircle size={13}/> {resp.updated}</>
            : <><Ic.Clock size={13}/> Updated {resp.updated}</>}
        </span>
        <Ic.ChevronRight size={16}/>
      </div>
    </div>
  );
};

const MyResponsesScreen = ({ nav, t, setTweak }) => {
  const { AppBar, Sheet, Btn, Banner } = window.Fm;
  const Ic = window.Icons, FD = window.FD;
  const [filter, setFilter] = useState("All");
  const [reportOpen, setReportOpen] = useState(false);
  const [toast, setToast] = useState(false);
  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(false), 2200); };
  const state = t.responsesState;

  const order = { confirmed: 0, accepted: 1, pending: 2, completed: 3, rejected: 4 };
  const all = useMemo(() => [...FD.RESPONSES].sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9)), []);
  const statusFor = (label) => ({ Delivering: "confirmed", Completed: "completed", Pending: "pending", Accepted: "accepted", Rejected: "rejected" }[label]);
  const list = filter === "All" ? all : all.filter(r => r.status === statusFor(filter));

  const route = (resp) => {
    // Case 2 — farmer has accepted the request to deliver → gate-in / delivering view.
    const stateMap = { pending: "pendingAccept", accepted: "pendingAccept", confirmed: "accepted", completed: "completed" };
    if (resp.status === "rejected") { nav.go("responseRejected", { id: resp.id }); return; }
    if (resp.status === "pending") { nav.go("responsePending", { id: resp.id }); return; }
    if (setTweak && stateMap[resp.status]) setTweak("acceptedState", stateMap[resp.status]);
    if (setTweak && resp.status === "completed") setTweak("payStatus", resp.payStatus || "inprocess");
    nav.go("responseAccepted", { id: resp.id });
  };

  const chips = ["All", "Pending", "Delivering", "Completed", "Rejected"];
  const empty = state === "empty";
  const loading = state === "loading";
  const filteredEmpty = state === "filteredEmpty" || (!empty && !loading && list.length === 0);
  const onCompletedTab = filter === "Completed";

  return (
    <>
      <AppBar title="My responses" align="left"/>
      <div className="fm-chips">
        {chips.map(c => {
          const n = c === "All" ? all.length : all.filter(r => r.status === statusFor(c)).length;
          return (
            <button key={c} className={`fm-chip ${filter === c ? "on" : ""}`} onClick={() => setFilter(c)}>
              {c}<span className="fm-chip-count">{n}</span>
            </button>
          );
        })}
      </div>

      <div className="fm-body">
        {loading ? (
          <div className="fm-scroll" style={{ paddingTop: 12 }}>{[0, 1, 2].map(i => <div key={i} className="fm-sk fm-sk-card"/>)}</div>
        ) : empty ? (
          <div className="fm-empty">
            <div className="fm-empty-art"><Ic.Handshake size={42}/></div>
            <div className="fm-empty-title">No responses yet</div>
            <div className="fm-empty-desc">You haven't responded to any requirements yet. Browse Home to find opportunities.</div>
            <button className="fm-btn fm-btn-outline fm-btn-sm fm-btn-pill" style={{ marginTop: 18 }} onClick={() => nav.tab("home")}>Browse Home</button>
          </div>
        ) : filteredEmpty ? (
          <div className="fm-empty">
            <div className="fm-empty-art"><Ic.Filter size={40}/></div>
            <div className="fm-empty-title">No responses in this status</div>
            <div className="fm-empty-desc">Try another filter to see your other responses.</div>
            <button className="fm-btn fm-btn-outline fm-btn-sm fm-btn-pill" style={{ marginTop: 18 }} onClick={() => setFilter("All")}>Show all</button>
          </div>
        ) : (
          <div className="fm-scroll" style={{ paddingTop: 12 }}>
            {list.map(resp => <ResponseCard key={resp.id} resp={resp} onOpen={() => route(resp)}/>)}

            {/* Case 1 — a completed delivery isn't showing up. Give the farmer a way to flag it. */}
            {onCompletedTab && (
              <div style={{ marginTop: 4 }}>
                <Banner tone="info" icon={Ic.HelpCircle} title="Missing a completed order?"
                        desc="If you delivered but the order isn't listed here, report it and the plant team will trace the gate record."/>
                <button className="fm-btn fm-btn-outline" style={{ width: "100%", marginTop: 10 }} onClick={() => setReportOpen(true)}>
                  <Ic.Flag size={17}/> Report a missing order
                </button>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Report-missing-order workflow */}
      <Sheet open={reportOpen} onClose={() => setReportOpen(false)} title="Report a missing order">
        <div className="fm-sheet-text" style={{ marginBottom: 14 }}>
          Tell us which delivery is missing. The plant team checks the gate log and the payment record, then updates your list — usually within one working day.
        </div>
        <div className="fm-field">
          <label className="fm-label">Gate pass number <span className="muted" style={{ fontWeight: 400 }}>(if you have it)</span></label>
          <input className="fm-input" placeholder="e.g. GPN-26790"/>
        </div>
        <div className="fm-field">
          <label className="fm-label">Delivery date</label>
          <input className="fm-input" type="date"/>
        </div>
        <div className="fm-field">
          <label className="fm-label">What's wrong?</label>
          <textarea className="fm-input" rows={3} placeholder="e.g. I delivered on 28 Apr but this order isn't showing as completed."/>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 4 }}>
          <Btn variant="ghost" onClick={() => setReportOpen(false)}>Cancel</Btn>
          <Btn variant="primary" className="fm-btn" style={{ flex: 1 }} onClick={() => { setReportOpen(false); showToast("Report sent — we'll trace it"); }}><Ic.Send size={17}/> Submit report</Btn>
        </div>
      </Sheet>

      {toast && <div className="fm-toast"><Ic.CheckCircle size={18}/>{toast}</div>}
    </>
  );
};

window.FarmerPages = Object.assign(window.FarmerPages || {}, {
  myResponses: { brandStatus: false, render: (ctx) => <MyResponsesScreen {...ctx}/> },
});
