// OPT-GATE-10 · Weighbridge — tare weight
const WeighTareScreen = ({ t, go }) => {
  const { Btn, Banner, NumInput, ToggleRow, PhotoTile } = window.Op;
  const Ic = window.Icons, FD = window.OD;
  const state = t.weighTare; // within | over | under | negative | empty
  const order = FD.ORDER;
  const GROSS = 16420;

  const presets = { within: 12220, over: 11600, under: 12900, negative: 17000, empty: 0 };
  const [tare, setTare] = useState(presets[state]);
  const [photo, setPhoto] = useState(state !== "empty");
  const [onBridge, setOnBridge] = useState(state !== "empty");
  useEffect(() => { setTare(presets[state]); setPhoto(state !== "empty"); setOnBridge(state !== "empty"); }, [state]);

  const net = GROSS - tare;
  const variancePct = net > 0 ? ((net - order.qty) / order.qty) * 100 : 0;
  const negative = tare > 0 && net <= 0;
  const within = !negative && Math.abs(variancePct) <= order.variance;
  const over = !negative && variancePct > order.variance;
  const under = !negative && variancePct < -order.variance;
  const canSave = tare > 0 && photo && onBridge && !negative;

  const netColor = negative ? "var(--destructive)" : within ? "var(--success)" : "var(--warning-fg)";

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, alignItems: "start" }}>
          {/* Tare entry */}
          <div>
            <div className="op-sec"><span className="op-sec-title">Tare weight (empty truck)</span></div>
            <div className="op-field">
              <NumInput value={tare} onChange={setTare} step={10} suffix="kg"/>
              <div className="op-hint">Captured after unloading · min 1 · max 30,000.</div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <ToggleRow on={onBridge} onChange={setOnBridge} icon={Ic.Truck} title="Truck is on the bridge" sub="Same anti-fraud confirmation as gross."/>
            </div>
            <div className="op-sec"><span className="op-sec-title">Tare slip photo <span style={{ color: "var(--soil)" }}>*</span></span></div>
            <PhotoTile filled={photo} label="Photo of post-unload slip" hint="Mandatory" tag="tare-slip.jpg" aspect="16 / 10" onTap={() => setPhoto(p => !p)}/>
          </div>

          {/* Net + variance */}
          <div>
            <div className="op-sec"><span className="op-sec-title">Net weight — official received qty</span></div>
            <div className="op-card op-card-pad" style={{ textAlign: "center", padding: 24, borderColor: negative ? "oklch(from var(--destructive) l c h / 0.5)" : within ? "oklch(from var(--success) l c h / 0.4)" : "var(--border)", background: negative ? "oklch(0.97 0.02 25)" : within ? "var(--success-soft)" : "var(--card)" }}>
              <div className="op-muted" style={{ fontSize: 12.5, fontWeight: 600 }}>GROSS {FD.NUM(GROSS)} − TARE {tare ? FD.NUM(tare) : "—"}</div>
              <div className="op-bignum" style={{ justifyContent: "center", marginTop: 8, color: netColor }}>
                <b>{tare ? FD.NUM(net) : "—"}</b><span style={{ color: netColor, opacity: 0.7 }}>kg</span>
              </div>
              {tare > 0 && !negative && (
                <div style={{ marginTop: 10, fontSize: 13.5, fontWeight: 600, color: netColor }}>
                  {within ? <>Within tolerance · {variancePct >= 0 ? "+" : ""}{variancePct.toFixed(1)}%</>
                    : over ? <>Over-delivery by {FD.NUM(Math.round(net - order.qty))} kg · +{variancePct.toFixed(1)}%</>
                    : <>Under-delivery by {FD.NUM(Math.round(order.qty - net))} kg · {variancePct.toFixed(1)}%</>}
                </div>
              )}
            </div>
            {negative && <div style={{ marginTop: 14 }}><Banner tone="danger" icon={Ic.Warning} title="Tare cannot exceed gross" desc="Net weight would be negative. Re-check the readings — this is hard-blocked."/></div>}
            {(over || under) && <div style={{ marginTop: 14 }}><Banner tone="warning" icon={Ic.Warning} title={`${over ? "Over" : "Under"}-delivery beyond ${order.variance}% tolerance`} desc="Acceptable variance comes from the linked requirement. Excessive deviation may notify procurement."/></div>}
            <div className="op-card flush" style={{ marginTop: 14 }}>
              <window.Op.SRow k="Gross (OPT-09)" v={FD.KG(GROSS)}/>
              <window.Op.SRow k="Expected" v={FD.KG(order.qty)}/>
              <window.Op.SRow k="Tolerance" v={`±${order.variance}%`}/>
            </div>
          </div>
        </div>
      </div>

      <div className="op-actionbar">
        <div className="op-muted" style={{ fontSize: 12.5 }}>{negative ? "Net cannot be negative" : !canSave ? "Enter tare, confirm bridge & photo" : "Net becomes received qty · status → Awaiting QC"}</div>
        <div className="op-ab-grow"/>
        <Btn variant="primary" icon={Ic.Check} disabled={!canSave} onClick={() => go("dashboard")}>Save &amp; complete</Btn>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  weighTare: { chrome: "flow", title: "Weighbridge — tare weight", sub: "GPN-20260516-0042", back: "dashboard", render: (ctx) => <WeighTareScreen {...ctx}/> },
});
