// OPT-QC-06 · Upload external QC report
const QcExtReport = ({ t, go }) => {
  const { Btn, Stepper, Banner, PhotoTile } = window.Op;
  const Ic = window.Icons, QD = window.QD;
  const state = t.extReport; // noUpload | uploaded | override | tooOld
  const E = QD.EVENT, m = QD.matrixFor(E.variety, E.stage);
  const uploaded = state !== "noUpload";
  const [useVals, setUseVals] = useState(state === "override");

  const Field = ({ label, value, ph, req, locked, wide }) => (
    <div className="op-field" style={{ margin: 0, gridColumn: wide ? "1 / -1" : "auto" }}>
      <div className="op-label" style={{ fontSize: 12.5 }}>{label} {req && <span className="req">*</span>}</div>
      <input className="op-input" style={{ height: 46, fontSize: 14, opacity: locked ? 0.5 : 1 }} defaultValue={value} placeholder={ph} disabled={locked}/>
    </div>
  );

  return (
    <div className="op-body" style={{ display: "flex", flexDirection: "column" }}>
      <div className="op-pad" style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "2px 0 16px" }}>
          <Stepper steps={["Start", "Sampling", "Parameters", "Decision"]} current={2}/>
          <div className="op-tabs">
            <button onClick={() => go("dmParam")}>DM</button>
            <button onClick={() => go("ffaParam")}>FFA</button>
            <button className="on">External</button>
          </div>
        </div>

        <div style={{ marginBottom: 14 }}><Banner tone="info" icon={Ic.FileText} title="Attach a third-party lab certificate" desc="Use a certified lab report as the parameter source instead of (or in addition to) inspector readings. Useful for premium / certified suppliers. Values are transcribed manually in v1."/></div>
        {state === "tooOld" && <div style={{ marginBottom: 14 }}><Banner tone="warning" icon={Ic.Warning} title="Report date is older than 14 days" desc="A stale certificate may not reflect the current load. You can still use it, but the age is logged."/></div>}
        {useVals && <div style={{ marginBottom: 14 }}><Banner tone="soil" icon={Ic.Info} title="External values override inspector readings" desc="The DM and FFA tabs now show an 'Overridden by external report' badge on affected rows."/></div>}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, alignItems: "start" }}>
          {/* Upload tile */}
          <div>
            {uploaded ? (
              <div className="op-card flush" style={{ overflow: "hidden" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 13, padding: 16 }}>
                  <span className="op-row-thumb" style={{ width: 48, height: 48, background: "var(--soil-soft)", color: "var(--soil-fg)" }}><Ic.FileText size={22}/></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 600 }}>AgriCert-Lab-Report-8841.pdf</div>
                    <div className="op-muted" style={{ fontSize: 12 }}>1.8 MB · PDF · uploaded just now</div>
                  </div>
                  <button className="op-iconbtn ghost" aria-label="Remove"><Ic.Trash size={18}/></button>
                </div>
                <div style={{ height: 200, background: "repeating-linear-gradient(135deg, var(--surface) 0 16px, var(--muted) 16px 32px)", display: "flex", alignItems: "center", justifyContent: "center", borderTop: "1px solid var(--border)" }}>
                  <span className="op-muted" style={{ fontSize: 12.5, fontFamily: "var(--font-mono)" }}>certificate preview</span>
                </div>
              </div>
            ) : (
              <PhotoTile label="Upload lab report" hint="PDF, JPG or PNG · max 10 MB" aspect="4 / 3" onTap={() => {}}/>
            )}
            <div className="op-muted" style={{ fontSize: 12, marginTop: 10, lineHeight: 1.5, display: "flex", gap: 7 }}><Ic.Info size={14} style={{ flexShrink: 0, marginTop: 1 }}/> OCR auto-extraction is out of scope for v1 — transcribe values manually from the certificate.</div>
          </div>

          {/* Manual entry */}
          <div className="op-card op-card-pad">
            <div style={{ fontSize: 14.5, fontWeight: 600, marginBottom: 14 }}>Report details</div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Lab name" value={uploaded ? "AgriCert Laboratories" : ""} ph="e.g. AgriCert" req locked={!uploaded}/>
              <Field label="Lab certification ID" value={uploaded ? "KEBS-LAB-2291" : ""} ph="optional" locked={!uploaded}/>
              <Field label="Report number" value={uploaded ? "RPT-8841" : ""} ph="e.g. RPT-0001" req locked={!uploaded}/>
              <Field label="Report date" value={uploaded ? (state === "tooOld" ? "28 Apr 2026" : "15 May 2026") : ""} ph="dd mmm yyyy" req locked={!uploaded}/>
            </div>
            <div className="op-divider"/>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Values from report</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {[["DM (Dry Matter)", uploaded ? "23.40" : "", "%"], ["FFA (Free Fatty Acid)", uploaded ? "0.510" : "", "%"]].map(([k, v, u]) => (
                <div key={k} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <div style={{ flex: 1 }}>
                    <div className="op-label" style={{ fontSize: 12.5, marginBottom: 5 }}>{k}</div>
                    <div style={{ display: "flex", alignItems: "center", height: 46, border: "1px solid var(--input)", borderRadius: "var(--radius-lg)", overflow: "hidden", background: "var(--card)", opacity: uploaded ? 1 : 0.5 }}>
                      <input className="op-num-input" style={{ fontSize: 18, height: "100%" }} defaultValue={v} placeholder="—" disabled={!uploaded}/>
                      <span style={{ fontSize: 12, color: "var(--muted-foreground)", padding: "0 12px", fontWeight: 600 }}>{u}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <button className={`op-toggle-row ${useVals ? "on" : ""}`} onClick={() => uploaded && setUseVals(v => !v)} style={{ marginTop: 14, width: "100%", textAlign: "left", opacity: uploaded ? 1 : 0.5 }} disabled={!uploaded}>
              <div className="op-tr-body">
                <div className="op-tr-title">Use these values for the decision</div>
                <div className="op-tr-sub">Overrides inspector readings on the DM / FFA tabs</div>
              </div>
              <span className={`op-switch ${useVals ? "on" : ""}`}/>
            </button>
          </div>
        </div>
      </div>

      <div className="op-actionbar">
        <Btn variant="ghost" onClick={() => go("dmParam")}>Back to parameters</Btn>
        <div className="op-ab-grow"/>
        <Btn variant="primary" icon={Ic.Check} disabled={!uploaded} onClick={() => go("dmParam")}>Save report</Btn>
      </div>
    </div>
  );
};

window.OptPages = Object.assign(window.OptPages || {}, {
  extReport: { chrome: "flow", title: "External report — GPN-…0041", sub: "Step 3 of 4 · External lab", back: "dmParam", render: (ctx) => <QcExtReport {...ctx}/> },
});
