// Screen 2: Shipment Execution
function Screen_Shipment({ sho, onOpenGuard }) {
  const data = window.GoldaData;
  const e = data.engagements.find(x => x.sho === sho) || data.engagements[0];
  // Live data-binding: use the per-shipment fields/steps the adapter attached to the engagement,
  // falling back to the design mock when the page is loaded without live data.
  const fields = (e && e.fields) || data.sho_fields;

  // Email timeline: fetch THIS shipment's own emails (was a single global list shown on every
  // shipment). In live mode use the fetched per-shipment emails; in mock mode use the design data.
  const isLive = !!(data && data.__live);
  const [liveEmails, setLiveEmails] = React.useState(null);
  const [acted, setActed] = React.useState(null);
  const [instruction, setInstruction] = React.useState("");
  const [status, setStatus] = React.useState(null); // 'saving' | 'saved' | 'error:<msg>'
  React.useEffect(() => { setActed(null); setInstruction(""); setStatus(null); }, [sho]); // reset when switching shipments
  React.useEffect(() => {
    if (!isLive || !e) return;
    let alive = true;
    const ref = e.fileRef || e.sho || sho;
    fetch(`/api/emails/by-shipment?ref=${encodeURIComponent(ref)}`, { cache: "no-store" })
      .then(r => r.ok ? r.json() : { items: [] })
      .then(d => {
        if (!alive) return;
        setLiveEmails((d.items || []).map((it, i) => ({
          id: it.id || `se-${i}`,
          dir: it.fromAddress && String(it.fromAddress).toLowerCase().includes("totalcargo") ? "internal" : "vendor",
          from: it.fromAddress || "Inbound email",
          time: String(it.sentAt || it.receivedAt || "").slice(0, 10),
          subject: it.subject || "(no subject)",
          operatorDecision: Boolean(it.operatorDecision),
          decisionText: it.actionRequiredNow || it.essenceSummary || "",
          extract: [["classification", it.classification || "—"], ["action", it.actionRequiredNow || it.essenceSummary || "Review"]],
          action: it.nextActionAfterThat || "Continue monitoring"
        })));
      })
      .catch(() => { if (alive) setLiveEmails([]); });
    return () => { alive = false; };
  }, [sho, isLive]);
  const emails = isLive ? (liveEmails || []) : data.sho_emails;

  const okCount = fields.filter(f => f.state === "ok").length;
  const pct = fields.length ? Math.round((okCount / fields.length) * 100) : 0;

  const steps = (e && e.steps) || [
    { name: "REO", date: "06-May", state: "done" },
    { name: "Supply Date", date: "07-May", state: "done" },
    { name: "PICKUP", date: "—", state: "done" },
    { name: "BOOKED", date: "09-May", state: "blocked" },
    { name: "ON BOARD", date: "—", state: "" },
    { name: "ATD", date: "—", state: "" }
  ];
  const stepStates = steps.map(s => s.state || "");
  const currentStep = steps.find(s => s.state === "blocked" || s.state === "current") || steps[steps.length - 1];

  // Build the "next action" for THIS shipment from its own live data. Previously every shipment
  // used data.decisions[0] (the global first decision) — so the card and "Open source email"
  // were identical on every shipment. In live mode, derive from the current engagement `e` and
  // hide the mock draft/evidence/guards (they are fictional placeholders, not real per-shipment).
  const raw = (e && (e.liveCase || e.liveShipment)) || {};
  const dec = isLive ? {
    kind: e.automation || "Status update",
    // Real extraction confidence from the matched shipment; null hides the chip (no fake 0.85).
    confidence: (e.liveShipment && typeof e.liveShipment.confidence === "number") ? e.liveShipment.confidence
      : (typeof raw.confidence === "number" ? raw.confidence : null),
    sho: e.sho,
    customer: e.customer,
    risk: e.risk,
    summary: raw.essenceSummary || raw.summary || raw.subject || e.note,
    recommendation: e.note || raw.actionRequiredNow,
    sourceUrl: raw.caseId && !e.fileRef ? `/api/emails/view?caseId=${encodeURIComponent(raw.caseId)}` : `/api/emails/view?ref=${encodeURIComponent(e.fileRef || e.sho || sho)}`,
    evidence: [],
    guards: [],
    caseId: raw.caseId || (e && e.caseId) || null,
    emailId: raw.id || raw.emailId || (e && e.emailId) || null
  } : data.decisions[0];
  const decisionCopy = window.GoldaDecisionCopy(dec);

  // Persist the operator's decision to Golda (records it, re-evaluates the case). In mock/preview
  // (no real case id) it just acknowledges locally so the design preview still behaves.
  async function postFeedback(comment) {
    if (!isLive || !(dec.caseId || dec.emailId)) { setActed("Confirmed"); return; }
    setStatus("saving");
    try {
      const res = await fetch("/api/public/operator-feedback", {
        method: "POST", headers: { "content-type": "application/json" }, cache: "no-store",
        body: JSON.stringify({ comment, caseId: dec.caseId, emailId: dec.emailId })
      });
      const out = await res.json().catch(() => ({}));
      if (res.ok && out.ok !== false) { setStatus("saved"); setActed("Confirmed"); }
      else setStatus("error:" + (out.error || ("Request failed (" + res.status + ")")));
    } catch (err) { setStatus("error:Network error — not saved."); }
  }
  function saveInstruction() {
    const c = instruction.trim();
    if (isLive && (dec.caseId || dec.emailId) && !c) { setStatus("error:Type an instruction first."); return; }
    postFeedback(c || ("Operator confirmed: " + decisionCopy.confirmLabel));
  }
  function confirmDecision() {
    postFeedback("Operator confirmed Golda's recommendation: " + String(dec.recommendation || decisionCopy.confirmLabel || "the recommended next action").slice(0, 300));
  }

  return (
    <div>
      <div className="sho-head">
        <div className="row1">
          <h2 className="mono">{e.sho}</h2>
          <span className="badge b-soft">{e.customer}</span>
          <StageBadge stage={e.stage}/>
          <RiskBadge risk={e.risk}/>
          <AutomationBadge level={e.automation}/>
          <div className="spacer"/>
          <button className="btn btn-sm" onClick={() => window.GoldaOpenSource(dec)}>View source emails</button>
          <button className="btn btn-sm" title="Pausing Golda is not enabled in this preview" disabled>Pause Golda</button>
          <button className="btn btn-sm btn-ghost" title="More actions — not enabled in this preview" disabled>⋯</button>
        </div>
        <div className="row2">
          <div className="sho-meta"><span className="k">Supplier</span><span className="v">{e.supplier}</span></div>
          <div className="sho-meta"><span className="k">Origin</span><span className="v">{e.origin}</span></div>
          <div className="sho-meta"><span className="k">Destination</span><span className="v">{e.destination}</span></div>
          <div className="sho-meta"><span className="k">Incoterms</span><span className="v">{e.incoterms}</span></div>
          <div className="sho-meta"><span className="k">Vessel</span><span className="v mono" title={e.vessel}>{e.vessel}</span></div>
          <div className="sho-meta"><span className="k">ETD / ETA</span><span className="v">{e.etd} / {e.eta}</span></div>
          <div className="sho-meta"><span className="k">Account manager</span><span className="v">{e.manager}</span></div>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-header">
          <h3 className="card-title">Execution progress</h3>
          <span className="card-sub">REO → ATD</span>
          <div className="spacer"/>
          {currentStep && (currentStep.state === "blocked"
            ? <span className="badge b-blocked"><span className="dot"/>Needs attention at {currentStep.name}</span>
            : <span className="badge b-soft"><span className="dot"/>In progress — {currentStep.name}</span>)}
        </div>
        <div style={{ padding: "20px 24px 14px" }}>
          <div className="progress-bar">
            {steps.map((s, i) => (
              <div key={s.name} className={`step ${stepStates[i]}`}>
                <div className="step-name">{s.name}</div>
                <div className="step-date">{s.date}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="split">
        <div>
          <div className="card" style={{ marginBottom: 16 }}>
            <div className="card-header">
              <div className="golda-avatar">G</div>
              <h3 className="card-title">Next action — proposed by Golda</h3>
              <span className="card-sub">{dec.kind}</span>
              <div className="spacer"/>
              <ConfidenceMeter value={dec.confidence}/>
            </div>
            <div className="decision-copy-grid" style={{ padding: "0 16px 14px" }}>
              <div><span className="copy-k">What is this email about?</span><p>{decisionCopy.summary}</p></div>
              <div><span className="copy-k">Recommended next action</span><p>{decisionCopy.recommended}</p></div>
              <div><span className="copy-k">What happens if you confirm?</span><p>{decisionCopy.willHappen}</p></div>
            </div>
            {!isLive && (
              <div className="draft">
                <div className="draft-head">
                  <div className="row"><span className="k">To</span><span>{dec.to}</span></div>
                  {dec.cc && <div className="row"><span className="k">CC</span><span>{dec.cc}</span></div>}
                  <div className="row"><span className="k">Subject</span><span style={{ fontWeight: 600 }}>{dec.subject}</span></div>
                </div>
                <div className="draft-body">{dec.body}</div>
              </div>
            )}
            <label className="next-action-label" style={{ padding: "0 16px 12px" }}>
              <span>Tell Golda a different next action</span>
              <textarea className="next-action-input" rows="2" placeholder={decisionCopy.guidancePrompt}
                value={instruction} onChange={ev => setInstruction(ev.target.value)}></textarea>
              {status && (
                <span style={{ fontSize: 12, marginTop: 6, color: status === "saved" ? "var(--accent)" : status === "saving" ? "var(--text-secondary)" : "var(--danger)" }}>
                  {status === "saving" ? "Saving instruction to Golda…" : status === "saved" ? "Saved ✓ — Golda recorded your instruction." : status.slice(6)}
                </span>
              )}
            </label>
            {!isLive && (
              <div className="evidence">
                <div className="evidence-head">Evidence</div>
                <ul>{(dec.evidence || []).map((x,i)=><li key={i}>{x}</li>)}</ul>
              </div>
            )}
            {!isLive && <GuardStrip guards={dec.guards}/>}
            <div className="action-footer">
              {!isLive && <button className="btn btn-sm" title="Not enabled in this preview" disabled>Edit draft</button>}
              <button className="btn btn-sm" onClick={() => window.GoldaOpenSource(dec)}>{decisionCopy.openLabel}</button>
              {!isLive && <button className="btn btn-sm btn-ghost" onClick={onOpenGuard}>Why? See guard panel</button>}
              <button className="btn btn-sm" disabled={status === "saving"} onClick={saveInstruction}>{status === "saving" ? "Saving…" : status === "saved" ? "Saved ✓" : "Save my instruction"}</button>
              <div className="spacer"/>
              {acted ? (
                <span className="badge b-soft"><span className="dot"/>{acted} — Golda will keep monitoring this shipment</span>
              ) : (
                <React.Fragment>
                  <button className="btn btn-sm btn-danger" onClick={() => setActed("Marked not correct")}>Dismiss / not correct</button>
                  <button className="btn btn-sm" onClick={() => setActed("Reminder set")}>Remind me later</button>
                  <button className="btn btn-sm btn-primary" disabled={status === "saving"} onClick={confirmDecision}>{decisionCopy.confirmLabel}</button>
                </React.Fragment>
              )}
            </div>
          </div>

          <div className="card">
            <div className="card-header">
              <h3 className="card-title">Email timeline</h3>
              <span className="card-sub">{emails.length} messages</span>
              <div className="spacer"/>
              <span className="tag">Newest first</span>
            </div>
            <div className="thread">
              {emails.map(em => (
                <div key={em.id} className="email">
                  <div className="em-rail">
                    <span className={`em-dot ${em.dir}`}>{em.dir === "golda" ? "G" : em.dir[0].toUpperCase()}</span>
                  </div>
                  <div>
                    <div className="em-head">
                      <span className="em-from">{em.from}</span>
                      <span className="tag">{em.dir}</span>
                      <span className="em-time" style={{ marginLeft: "auto" }}>{em.time}</span>
                    </div>
                    <div className="em-subject">{em.subject}</div>
                    {em.operatorDecision && (
                      <div className="em-extract" style={{ borderLeft: "3px solid var(--accent)", background: "var(--bg-app)" }}>
                        <div className="em-extract-head" style={{ color: "var(--accent)" }}>✓ Operator decision recorded</div>
                        {em.decisionText && <div style={{ fontSize: 13, marginTop: 2 }}>{em.decisionText}</div>}
                      </div>
                    )}
                    {em.extract && (
                      <div className="em-extract">
                        <div className="em-extract-head">Golda extracted</div>
                        <div className="kv">
                          {em.extract.map(([k,v],i)=>(
                            <React.Fragment key={i}><span className="k">{k}</span><span className="mono">{v}</span></React.Fragment>
                          ))}
                        </div>
                      </div>
                    )}
                    {em.action && (
                      <div className="em-action">
                        <span className="golda-avatar" style={{ width: 16, height: 16, fontSize: 9 }}>G</span>
                        <span>{em.action}</span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div>
          <div className="card">
            <div className="card-header">
              <h3 className="card-title">Field completeness</h3>
              <div className="spacer"/>
              <span style={{ fontWeight: 600, fontSize: 13 }}>{pct}%</span>
            </div>
            <div style={{ padding: "12px 18px 0" }}>
              <div className="completeness-bar"><div className="fill" style={{ width: `${pct}%` }}/></div>
            </div>
            <div style={{ padding: "0 18px 14px" }} className="fields-list">
              {fields.map(f => (
                <div key={f.name} className="field-row">
                  <span className="f-icon"><FieldIcon state={f.state}/></span>
                  <div>
                    <div className="f-name">{f.name}</div>
                    <div className="f-meta">{f.source}</div>
                  </div>
                  <div className="f-meta mono">{f.at}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.Screen_Shipment = Screen_Shipment;
