// FRM-PROC-08 · Gate-in — confirm & gate pass
// The buyer accepted the offer → the farmer confirms the gate-in (date/time they
// proposed). Only after confirming does the QR gate pass go live (shown to both).
const ResponseAcceptedScreen = ({ nav, t, params, setTweak }) => {
  const { AppBar, Btn, QR, Banner, Sheet } = window.Fm;
  const Ic = window.Icons, FD = window.FD;
  const resp = FD.RESP_BY_ID[params.id] || FD.RESPONSES.find(r => r.status === "accepted");
  const state = t.acceptedState; // pendingAccept | accepted | reschedule | completed
  const confirmed = state === "accepted" || state === "reschedule" || state === "completed";
  const completed = state === "completed";
  const [qrSheet, setQrSheet] = useState(false);
  const [toast, setToast] = useState(false);
  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(false), 2200); };

  // ── Trucks on this gate pass ──────────────────────────────────────────────
  // One GNP for the slot; each truck is a line under it. Auto-seeded with the
  // farmer's own vehicle; they add more if they're splitting the load.
  const [trucks, setTrucks] = useState(() => [
    { id: "t1", plate: "KCB 412G", driver: "Samuel Otieno", phone: "0726 145 880", trailer: "", qty: resp.allocatedQty },
  ]);
  const [truckSheet, setTruckSheet] = useState(false);
  const [editId, setEditId] = useState(null);
  const blankTruck = { plate: "", driver: "", phone: "", trailer: "", qty: 0 };
  const [form, setForm] = useState(blankTruck);
  const fset = (patch) => setForm(f => ({ ...f, ...patch }));
  const formValid = form.plate.trim().length >= 4 && form.driver.trim().length >= 2 && form.phone.trim().length >= 7;
  const openAddTruck = () => { setEditId(null); setForm(blankTruck); setTruckSheet(true); };
  const openEditTruck = (tr) => { setEditId(tr.id); setForm({ plate: tr.plate, driver: tr.driver, phone: tr.phone, trailer: tr.trailer, qty: tr.qty }); setTruckSheet(true); };
  const removeTruck = (id) => setTrucks(list => list.filter(x => x.id !== id));
  const saveTruck = () => {
    if (!formValid) return;
    if (editId) setTrucks(list => list.map(x => x.id === editId ? { ...x, ...form } : x));
    else setTrucks(list => [...list, { ...form, id: "t" + Date.now() }]);
    setTruckSheet(false);
    showToast(editId ? "Truck updated" : "Truck added");
  };
  const truckTotal = trucks.reduce((s, x) => s + (Number(x.qty) || 0), 0);

  const acceptGateIn = () => { setTweak && setTweak("acceptedState", "accepted"); showToast("Gate-in confirmed — gate pass ready"); };

  return (
    <>
      <AppBar onBack={() => nav.back()} title={confirmed ? "Gate-in" : "Confirm gate-in"} align="left"
        right={<button className="fm-iconbtn" aria-label="Share" onClick={() => showToast("Shared via WhatsApp")}><Ic.Share size={20}/></button>}/>
      <div className="fm-body">
        <div className="fm-scroll" style={{ paddingTop: 4 }}>
          {/* Status banner */}
          {completed ? (
            <div className="fm-card fm-card-pad" style={{ textAlign: "center", marginBottom: 16, background: "var(--success-soft)", borderColor: "transparent" }}>
              <div className="fm-splash-ring" style={{ width: 64, height: 64, marginBottom: 10 }}><Ic.CheckCircle size={34}/></div>
              <div style={{ fontSize: 18, fontWeight: 600 }}>Delivery completed</div>
              <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>Payment is being processed. You'll be notified when it's sent.</div>
            </div>
          ) : confirmed ? (
            <div style={{ marginBottom: 16 }}>
              <Banner tone="success" icon={Ic.CheckCircle} title="Gate-in confirmed"
                      desc="Your gate pass was generated automatically. Add the trucks you'll send below."/>
            </div>
          ) : (
            <div style={{ marginBottom: 16 }}>
              <Banner tone="success" icon={Ic.Handshake} title="Your offer was accepted!"
                      desc={`The buyer accepted your offer for ${resp.title}. Confirm the gate-in to lock your slot.`}/>
            </div>
          )}

          {/* Allocation note */}
          {resp.allocatedQty < resp.offeredQty && (
            <div style={{ marginBottom: 16 }}>
              <Banner tone="info" icon={Ic.Info} title="Partial allocation"
                      desc={`You offered ${FD.KG(resp.offeredQty)}, the buyer accepted ${FD.KG(resp.allocatedQty)}.`}/>
            </div>
          )}

          {/* Gate-in summary */}
          <div className="fm-ds-label" style={{ margin: "0 2px 8px" }}>Gate-in summary</div>
          <div className="fm-card flush" style={{ marginBottom: 16 }}>
            <div className="fm-srow"><span className="k">Reference</span><span className="v fm-mono">{resp.po}</span></div>
            <div className="fm-srow"><span className="k">Accepted quantity</span><span className="v">{FD.KG(resp.allocatedQty)}</span></div>
            <div className="fm-srow"><span className="k">Agreed rate</span><span className="v">{FD.KES(resp.rate)}<small> /kg</small></span></div>
            <div className="fm-srow"><span className="k">Order value</span><span className="v">KSh {(resp.allocatedQty * resp.rate).toLocaleString("en-US")}</span></div>
          </div>

          {/* Gate-in slot — the date/time the farmer proposed */}
          <div className="fm-ds-label" style={{ margin: "0 2px 8px" }}>Your delivery slot</div>
          <div className="fm-card flush" style={{ marginBottom: 16 }}>
            <div className="fm-srow"><span className="k">Date</span><span className="v">{resp.slotDate}</span></div>
            <div className="fm-srow"><span className="k">Time window</span><span className="v">{resp.slotWindow}</span></div>
            <div className="fm-srow"><span className="k" style={{ flex: 1 }}>Gate</span><span className="v" style={{ fontWeight: 500, maxWidth: 200 }}>{resp.gate}</span></div>
          </div>

          {/* Reschedule pending */}
          {state === "reschedule" && <div style={{ marginBottom: 16 }}><Banner tone="warning" icon={Ic.Clock} title="Reschedule pending review" desc="You asked to move to 15 May. The buyer will respond within 24 hours."/></div>}

          {/* Gate pass — gated behind confirmation */}
          <div className="fm-ds-label" style={{ margin: "0 2px 8px" }}>Gate pass</div>
          {confirmed ? (
            <div className="fm-card" style={{ marginBottom: 16 }}>
              <div className="fm-qr-wrap" onClick={() => setQrSheet(true)} style={{ cursor: "pointer" }}>
                <QR value={resp.gpn} size={184}/>
                <div className="fm-qr-caption">{resp.gpn}</div>
                <div className="muted" style={{ fontSize: 12, marginTop: -6 }}>One pass for every truck on this slot · tap to enlarge.</div>
              </div>
              <div style={{ display: "flex", gap: 10, padding: "0 16px 16px" }}>
                <button className="fm-btn fm-btn-outline fm-btn-sm" style={{ flex: 1 }} onClick={() => showToast("Saved to phone")}><Ic.Download size={16}/> Save</button>
                <button className="fm-btn fm-btn-outline fm-btn-sm" style={{ flex: 1 }} onClick={() => showToast("Shared via WhatsApp")}><Ic.Share size={16}/> Share</button>
              </div>
            </div>
          ) : (
            <div className="fm-card fm-card-pad" style={{ marginBottom: 16, textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
              <span className="fm-req-thumb" style={{ width: 52, height: 52, background: "var(--muted)", color: "var(--muted-foreground)" }}><Ic.Clock size={24}/></span>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Gate pass appears after you confirm</div>
              <div className="muted" style={{ fontSize: 12.5, lineHeight: 1.5, maxWidth: 260 }}>Confirming the gate-in generates your QR pass. The gate keeper scans it to let your truck in.</div>
            </div>
          )}

          {/* Trucks on this gate pass — multi-truck against one GNP */}
          {confirmed && !completed && (
            <>
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", margin: "0 2px 8px" }}>
                <div className="fm-ds-label" style={{ margin: 0 }}>Trucks on this gate pass</div>
                <span className="muted" style={{ fontSize: 12 }}>{trucks.length} {trucks.length === 1 ? "truck" : "trucks"} · 1 GNP</span>
              </div>

              {trucks.map((tr, i) => (
                <div className="fm-card flush" key={tr.id} style={{ marginBottom: 10 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderBottom: "1px solid var(--border)" }}>
                    <span className="fm-req-thumb" style={{ width: 40, height: 40, background: "var(--soil-soft)", color: "var(--soil-fg)" }}><Ic.Truck size={19}/></span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14.5, fontWeight: 600, letterSpacing: "-0.01em" }}>Truck {i + 1} <span className="fm-mono" style={{ fontWeight: 500, color: "var(--muted-foreground)" }}>· {tr.plate}</span></div>
                      <div className="muted" style={{ fontSize: 12.5 }}>{tr.driver}</div>
                    </div>
                    <button className="fm-iconbtn" style={{ border: "1px solid var(--border)" }} aria-label="Edit truck" onClick={() => openEditTruck(tr)}><Ic.Edit size={16}/></button>
                    {trucks.length > 1 && <button className="fm-iconbtn" style={{ border: "1px solid var(--border)" }} aria-label="Remove truck" onClick={() => removeTruck(tr.id)}><Ic.Trash size={16}/></button>}
                  </div>
                  <div className="fm-srow"><span className="k">Driver phone</span><span className="v">{tr.phone}</span></div>
                  {tr.trailer && <div className="fm-srow"><span className="k">Trailer plate</span><span className="v fm-mono">{tr.trailer}</span></div>}
                  {tr.qty > 0 && <div className="fm-srow"><span className="k">Estimated load</span><span className="v">{FD.KG(tr.qty)}</span></div>}
                </div>
              ))}

              <button className="fm-btn fm-btn-outline" style={{ width: "100%", marginBottom: 8 }} onClick={openAddTruck}><Ic.Plus size={18}/> Add another truck</button>
              <div className="muted" style={{ fontSize: 12, lineHeight: 1.5, margin: "0 2px 16px" }}>
                One gate pass covers every truck for this slot. {truckTotal > 0 && <>Trucks cover <b style={{ color: "var(--foreground)" }}>{FD.KG(truckTotal)}</b> of {FD.KG(resp.allocatedQty)} allocated.</>}
              </div>
            </>
          )}

          {/* Buyer contact */}
          <div className="fm-ds-label" style={{ margin: "0 2px 8px" }}>Buyer contact</div>
          <div className="fm-card fm-card-pad" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span className="fm-req-thumb" style={{ width: 40, height: 40 }}><Ic.Leaf size={18}/></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{FD.BUYER.org}</div>
              <div className="muted" style={{ fontSize: 12 }}>{FD.BUYER.plant}</div>
            </div>
            <button className="fm-iconbtn" style={{ border: "1px solid var(--border)" }} aria-label="Call" onClick={() => showToast("Calling buyer…")}><Ic.Phone size={18}/></button>
            <button className="fm-iconbtn" style={{ border: "1px solid var(--border)" }} aria-label="Message" onClick={() => showToast("Opening chat…")}><Ic.Message size={18}/></button>
          </div>
        </div>
      </div>

      {!completed && (
        <div className="fm-actionbar">
          {!confirmed
            ? <>
                <Btn variant="primary" icon={Ic.CheckCircle} onClick={acceptGateIn}>Accept gate-in</Btn>
                <button className="fm-btn fm-btn-outline" style={{ flexShrink: 0, whiteSpace: "nowrap" }} onClick={() => nav.go("reschedule", { id: resp.id })}><Ic.Calendar size={16}/> Another time</button>
              </>
            : <button className="fm-btn fm-btn-outline" onClick={() => nav.go("reschedule", { id: resp.id })}><Ic.Calendar size={18}/> Request reschedule</button>}
        </div>
      )}

      <Sheet open={truckSheet} onClose={() => setTruckSheet(false)} title={editId ? "Edit truck" : "Add truck"}>
        <div className="muted" style={{ fontSize: 12.5, lineHeight: 1.5, marginBottom: 14 }}>These details are checked against the truck at the gate before it's let in.</div>
        <div className="fm-field">
          <label className="fm-label">Truck plate number <span className="req">*</span></label>
          <input className="fm-input" placeholder="e.g. KCB 412G" value={form.plate} onChange={(e) => fset({ plate: e.target.value.toUpperCase() })}/>
        </div>
        <div className="fm-field">
          <label className="fm-label">Driver name <span className="req">*</span></label>
          <input className="fm-input" placeholder="Full name" value={form.driver} onChange={(e) => fset({ driver: e.target.value })}/>
        </div>
        <div className="fm-field">
          <label className="fm-label">Driver phone <span className="req">*</span></label>
          <input className="fm-input" inputMode="tel" placeholder="0722 000 000" value={form.phone} onChange={(e) => fset({ phone: e.target.value })}/>
        </div>
        <div className="fm-field">
          <label className="fm-label">Trailer / second plate <span className="muted" style={{ fontWeight: 400 }}>(optional)</span></label>
          <input className="fm-input" placeholder="For articulated trucks" value={form.trailer} onChange={(e) => fset({ trailer: e.target.value.toUpperCase() })}/>
        </div>
        <div className="fm-field">
          <label className="fm-label">Estimated load on this truck <span className="muted" style={{ fontWeight: 400 }}>(optional)</span></label>
          <div className="fm-stepper">
            <button className="fm-step-btn" onClick={() => fset({ qty: Math.max(0, (form.qty || 0) - 100) })}>−</button>
            <input className="fm-step-input" inputMode="numeric" placeholder="0" value={form.qty ? form.qty.toLocaleString("en-US") : ""} onChange={(e) => fset({ qty: Math.max(0, Number(e.target.value.replace(/\D/g, "")) || 0) })}/>
            <span className="fm-step-suffix">kg</span>
            <button className="fm-step-btn" onClick={() => fset({ qty: (form.qty || 0) + 100 })}>+</button>
          </div>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 8 }}>
          {editId && <Btn variant="ghost" onClick={() => { removeTruck(editId); setTruckSheet(false); }}><Ic.Trash size={16}/> Remove</Btn>}
          <Btn variant="primary" disabled={!formValid} className="fm-btn" style={{ flex: 1 }} onClick={saveTruck}><Ic.Check size={18}/> {editId ? "Save truck" : "Add truck"}</Btn>
        </div>
      </Sheet>

      <Sheet open={qrSheet} onClose={() => setQrSheet(false)} title="Gate pass">
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12, padding: "8px 0 4px" }}>
          <QR value={resp.gpn} size={240}/>
          <div className="fm-qr-caption" style={{ fontSize: 15 }}>{resp.gpn}</div>
          <div className="muted" style={{ fontSize: 12.5, textAlign: "center" }}>Valid ±2 hours around your slot. The gate keeper scans this to verify your truck.</div>
        </div>
        <div style={{ marginTop: 14 }}><Btn variant="outline" onClick={() => setQrSheet(false)}>Close</Btn></div>
      </Sheet>

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

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