/* ========================================================================
   estate-requests.jsx — the request pattern (Story 2)
   Management actions on international SIMs are fulfilled by the Meaningful
   Planet team, so every action is a request: it raises a support ticket,
   shows its progress on the SIM, and resolves to completed or declined.
   Reusable kit: store, banner, row chip, drawer, confirm modal, notice.
   ======================================================================== */
const { useState: uR, useEffect: eR } = React;
const RD = window.MILO_DATA;
const RE = window.MP_ESTATE;

/* ---------- Store ---------- */
const REQ_KEY = "mp_estate_requests_v3";
const REQ_TYPES = {
  suspend: { label: "Request Suspension", icon: "circle-pause", verb: "Suspension", title: "Suspension", becomes: "Suspended" },
  reactivate: { label: "Request Reactivation", icon: "circle-play", verb: "Reactivation", title: "Reactivation", becomes: "Active" },
  terminate: { label: "Request Termination", icon: "power-off", verb: "Termination", title: "Termination", becomes: "Terminated" },
  contact: { label: "Contact Us About This SIM", icon: "message-square", verb: "Enquiry", title: "Enquiry", becomes: null },
  new_sims: { label: "Request International SIMs", icon: "globe", verb: "New SIMs", title: "New SIMs", becomes: null },
  altnet_sims: { label: "Request Alternative Network SIMs", icon: "card-sim", verb: "New SIMs", title: "New SIMs", becomes: null },
  travel_plan: { label: "Request a Travel eSIM Plan", icon: "plane", verb: "Travel plan", title: "Travel plan", becomes: null },
  move_device: { label: "Move to Another Device", icon: "smartphone", verb: "Device move", title: "Device move", becomes: null },
  pool_change: { label: "Add SIMs or Modify Data Pool", icon: "layers", verb: "Pool change", title: "Pool change", becomes: null }
};
const DECLINE_REASON = "This SIM is in a contract term until March 2027";

/* A realistic estate carries one open request, not a queue of them. */
function seededRequest() {
  const sim = RD.SIMS.find((x) => x.group === "international" && x.status === "Active");
  if (!sim) return [];
  return [{ id: "r4821", simId: sim.id, type: "suspend", ticket: "4821",
    created: new Date(Date.now() - 2 * 86400000).toISOString(), status: "open" }];
}
let REQ = { seq: 4821, list: seededRequest(), overrides: {} };
try { const raw = localStorage.getItem(REQ_KEY); if (raw) REQ = { ...REQ, ...JSON.parse(raw) }; } catch (e) {}
const reqSubs = new Set();
function reqPersist() { try { localStorage.setItem(REQ_KEY, JSON.stringify(REQ)); } catch (e) {} }
function reqNotify() { reqPersist(); reqSubs.forEach((cb) => cb()); }
function useRequests() {
  const [, force] = uR(0);
  eR(() => { const cb = () => force((n) => n + 1); reqSubs.add(cb); return () => reqSubs.delete(cb); }, []);
  return REQ;
}

const openRequestFor = (simId) => REQ.list.find((r) => r.simId === simId && r.status === "open") || null;
const noticeFor = (simId) => REQ.list.find((r) => r.simId === simId && r.status === "declined" && !r.dismissed) || null;
/* A completed request is the only thing that changes a SIM's status. */
const estStatus = (sim) => REQ.overrides[sim.id] || sim.status;

function raiseAlert(kind, title, description) {
  RD.ALERTS.unshift({ id: Date.now(), kind, title, description, time_ago: "Just now" });
}

function createRequest(simId, type, extra) {
  REQ.seq += 1;
  const r = {
    id: "r" + REQ.seq, simId: simId || null, type,
    ticket: String(REQ.seq),
    created: new Date().toISOString(),
    status: "open", ...(extra || {})
  };
  REQ.list.unshift(r);
  const sim = simId ? RD.SIMS.find((s) => s.id === simId) : null;
  raiseAlert("sim_request_open", (REQ_TYPES[type].title || REQ_TYPES[type].verb) + " requested",
    sim ? REQ_TYPES[type].verb + " requested for " + sim.msisdn + ". Ticket #" + r.ticket + ". The team is working on it." :
      "Your request has been sent to the team. Ticket #" + r.ticket + " is open.");
  reqNotify();
  return r;
}
/* A batch request: one ticket, one record per SIM, resolved together. */
function createBatchRequest(simIds, type) {
  REQ.seq += 1;
  const ticket = String(REQ.seq);
  const batch = "b" + REQ.seq;
  const created = new Date().toISOString();
  simIds.forEach((simId, i) => {
    REQ.list.unshift({ id: "r" + REQ.seq + "-" + i, simId, type, ticket, batch, created, status: "open" });
  });
  raiseAlert("sim_request_open", (REQ_TYPES[type].title || REQ_TYPES[type].verb) + " requested",
    REQ_TYPES[type].verb + " requested for " + simIds.length + " SIMs. Ticket #" + ticket + ". The team is working on it.");
  reqNotify();
  return ticket;
}
function resolveRequest(id, status, reason) {
  const first = REQ.list.find((x) => x.id === id);
  if (!first || first.status !== "open") return;
  const group = first.batch ? REQ.list.filter((x) => x.batch === first.batch && x.status === "open") : [first];
  group.forEach((r, i) => resolveOne(r, status, reason, i === 0, group.length));
  reqNotify();
}
function resolveOne(r, status, reason, announce, batchSize) {
  r.status = status;
  r.resolved = new Date().toISOString();
  if (status === "declined") r.reason = reason || DECLINE_REASON;
  const sim = r.simId ? RD.SIMS.find((s) => s.id === r.simId) : null;
  const t = REQ_TYPES[r.type];
  if (status === "completed" && sim && t.becomes) REQ.overrides[sim.id] = t.becomes;
  /* A completed device move consumes the old QR and starts the install again. */
  if (status === "completed" && sim && r.type === "move_device" && window.MP_ESIM) window.MP_ESIM.moveCompleted(sim.id);
  if (!announce) return;
  const many = batchSize > 1 ? batchSize + " SIMs" : null;
  if (status === "completed") {
    raiseAlert("sim_request_done", (t.title || t.verb) + " completed",
      many ? t.verb + " completed for " + many + "." :
      sim ? (r.type === "move_device" ?
        "The eSIM for " + sim.msisdn + " is ready to install on the new device, and a new activation email has been sent." :
        t.verb + " completed for " + sim.msisdn + ".") : "Your request has been completed.");
  } else {
    raiseAlert("sim_request_declined", (t.title || t.verb) + " declined",
      (many ? "The request for " + many + " was declined. " :
       sim ? "The request for " + sim.msisdn + " was declined. " : "Your request was declined. ") + r.reason);
  }
}
function dismissNotice(id) {
  const r = REQ.list.find((x) => x.id === id);
  if (r) { r.dismissed = true; reqNotify(); }
}
/* Tweaks: resolve the newest open request, and roll the usage month. */
function resolveNewestOpen(status) {
  const r = REQ.list.find((x) => x.status === "open");
  if (r) resolveRequest(r.id, status);
  return !!r;
}
function rollUsageMonth() {
  RE.rollUsageMonth(1);
  raiseAlert("usage_available", "Monthly usage available",
    RE.monthLabel + " usage is now available for your International SIMs.");
  reqNotify();
}

/* ---------- Ticket reference ----------
   Every ticket is listed in Support Tickets, so the reference goes there. */
function TicketLink({ ticket }) {
  return <a className="mp-ticket-ref" href="#/support/tickets">#{ticket}</a>;
}
/* What a request asked for, in the ticket list's Description column. */
function requestDetail(r, count, sim) {
  if (r.type === "new_sims") return [r.qty + " SIMs", r.market, r.plan].filter(Boolean).join(", ");
  if (r.type === "altnet_sims") return [r.qty + " SIMs", r.network, r.plan].filter(Boolean).join(", ");
  if (r.type === "pool_change") return r.change === "Add SIMs" ? "Add " + r.qty + " SIMs" : "Change to " + r.size;
  if (r.type === "travel_plan") return [r.market, r.person].filter(Boolean).join(", ");
  if (count > 1) return count + " SIMs";
  return sim ? sim.msisdn : "";
}

/* What a request is called in a ticket list. */
function requestSubject(r) {
  const t = REQ_TYPES[r.type];
  if (r.type === "new_sims") return "New international SIMs requested";
  if (r.type === "altnet_sims") return "New alternative network SIMs requested";
  if (r.type === "travel_plan") return "Travel eSIM plan requested";
  if (r.type === "pool_change") return "Data pool change requested";
  return (t.verb || t.label) + " requested";
}

/* ---------- Banner: open request, or a declined notice ---------- */
function RequestBanner({ sim }) {
  useRequests();
  const open = openRequestFor(sim.id);
  const notice = noticeFor(sim.id);
  if (open) {
    const t = REQ_TYPES[open.type];
    return (
      <div className="mp-req-banner mp-req-banner--open">
        <Icon name="loader" size={18} />
        <span className="mp-req-banner-text">
          <strong>{t.verb} requested</strong>, {RE.fmtDate(new Date(open.created))}, ticket <TicketLink ticket={open.ticket} />: in progress.
        </span>
      </div>);
  }
  if (notice) {
    return (
      <div className="mp-req-banner mp-req-banner--declined">
        <Icon name="triangle-alert" size={18} />
        <span className="mp-req-banner-text">
          <strong>Request declined:</strong> {notice.reason}. Ticket <TicketLink ticket={notice.ticket} />.
        </span>
        <button type="button" className="mp-req-banner-x" onClick={() => dismissNotice(notice.id)} aria-label="Dismiss this notice">
          <Icon name="x" size={16} />
        </button>
      </div>);
  }
  return null;
}

/* ---------- Row chip for tables ---------- */
function RequestRowChip({ sim }) {
  useRequests();
  const open = openRequestFor(sim.id);
  if (!open) return null;
  return (
    <span className="mp-req-chip" title={"Ticket #" + open.ticket}>
      <Icon name="loader" size={11} />{REQ_TYPES[open.type].verb + " requested"}
    </span>);
}

/* ---------- Confirm modal ---------- */
function RequestConfirmModal({ sim, type, onCancel, onConfirm }) {
  const t = REQ_TYPES[type];
  const body = type === "contact" ?
    <>Start an enquiry about <strong>{sim.msisdn}</strong>? A support ticket will be created and we will keep you updated.</> :
    type === "move_device" ?
    <>The current eSIM stops working as soon as the move is completed. The Meaningful Planet team will action this request, and a support ticket will be created and we will keep you updated.</> :
    <>Request {t.verb.toLowerCase()} of <strong>{sim.msisdn}</strong>? The Meaningful Planet team will action this request. A support ticket will be created and we will keep you updated.</>;
  const title = type === "contact" ? "Contact us about this SIM?" :
    type === "move_device" ? "Move this eSIM to another device?" :
    "Request " + t.verb.toLowerCase() + "?";
  return (
    <div className="mp-modal-overlay" onClick={onCancel}>
      <div className="mp-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 460 }}>
        <div className="mp-modal-ic mp-modal-ic--neutral"><Icon name={t.icon} size={20} /></div>
        <h3 className="mp-modal-title">{title}</h3>
        <p className="mp-modal-text">{body}</p>
        {type === "terminate" ?
        <div className="mp-modal-note mp-modal-note--warn">
          <Icon name="triangle-alert" size={16} />
          <span>Termination is permanent. The number cannot be recovered later.</span>
        </div> : null}
        {type === "move_device" ?
        <div className="mp-modal-note mp-modal-note--warn">
          <Icon name="triangle-alert" size={16} />
          <span>The user will lose connectivity on the old device when the move completes.</span>
        </div> : null}
        <div className="mp-modal-actions">
          <Button variant="secondary" onClick={onCancel}>Cancel</Button>
          <Button variant="primary" icon="send" onClick={onConfirm}>Send Request</Button>
        </div>
      </div>
    </div>);
}

/* ---------- Request a Change drawer ---------- */
function RequestChangeDrawer({ sim, onClose }) {
  useRequests();
  const [confirm, setConfirm] = uR(null);
  const open = openRequestFor(sim.id);
  const status = estStatus(sim);
  eR(() => {
    const onKey = (e) => { if (e.key === "Escape") { if (confirm) setConfirm(null); else onClose(); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [confirm]);

  const actions = [];
  if (!open) {
    if (status === "Active") actions.push("suspend");
    if (status === "Suspended") actions.push("reactivate");
    if (status === "Active" || status === "Suspended") actions.push("terminate");
    if (window.MP_ESIM && window.MP_ESIM.isInstalled(sim)) actions.push("move_device");
  }

  return (
    <>
      <div className="mp-drawer-scrim" onClick={onClose} />
      <aside className="mp-drawer" role="dialog" aria-label="Make a request">
        <header className="mp-drawer-head">
          <div style={{ minWidth: 0 }}>
            <div className="mp-drawer-headline"><h3>Make a Request</h3></div>
            <div className="mp-drawer-sub">{sim.msisdn}{sim.country && RE.COUNTRIES[sim.country] ? " · " + RE.COUNTRIES[sim.country].name : sim.group === "altnet" && sim.network ? " · " + sim.network : ""}</div>
          </div>
          <button type="button" className="mp-drawer-x" onClick={onClose} aria-label="Close"><Icon name="x" size={18} /></button>
        </header>

        <div className="mp-drawer-body">
          {open ?
          <>
            <div className="mp-req-open-card">
              <div className="mp-req-open-head">
                <Icon name="loader" size={16} />
                <span>{REQ_TYPES[open.type].verb} requested</span>
              </div>
              <div className="mp-req-open-body">
                Sent {RE.fmtDate(new Date(open.created))}. The team is working on it. Your reference is ticket <TicketLink ticket={open.ticket} />.
              </div>
            </div>
          </> : null}

          <div className="mp-action-group">
            <div className="mp-action-group-title">Requests</div>
            <div className="mp-action-list">
              {actions.map((k) =>
                <ActionRow key={k} icon={REQ_TYPES[k].icon} label={REQ_TYPES[k].label}
                  tone={k === "terminate" ? "danger" : undefined} onClick={() => setConfirm(k)} />)}
              <ActionRow icon={REQ_TYPES.contact.icon} label={REQ_TYPES.contact.label} onClick={() => setConfirm("contact")} />
            </div>
          </div>
        </div>
      </aside>

      {confirm ?
      <RequestConfirmModal sim={sim} type={confirm}
        onCancel={() => setConfirm(null)}
        onConfirm={() => { createRequest(sim.id, confirm); setConfirm(null); onClose(); }} /> : null}
    </>);
}

/* ---------- Request new international SIMs ---------- */
function RequestNewSimsModal({ onClose, onSent }) {
  const [country, setCountry] = uR("");
  const [qty, setQty] = uR("5");
  const [plan, setPlan] = uR("");
  const [note, setNote] = uR("");
  const PLANS = [
    { value: "5 GB", label: "5 GB" }, { value: "10 GB", label: "10 GB" },
    { value: "20 GB", label: "20 GB" }, { value: "Unlimited", label: "Unlimited" }];
  const MARKETS = [
    { value: "DE", label: "Germany" }, { value: "IE", label: "Ireland" }, { value: "FR", label: "France" },
    { value: "ES", label: "Spain" }, { value: "NL", label: "Netherlands" }, { value: "IT", label: "Italy" },
    { value: "PL", label: "Poland" }, { value: "SG", label: "Singapore" }, { value: "US", label: "United States" }];
  const ready = country && Number(qty) > 0 && plan;
  return (
    <div className="mp-modal-overlay" onClick={onClose}>
      <div className="mp-modal mp-modal--form" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 480 }}>
        <div className="mp-modal-ic mp-modal-ic--neutral"><Icon name="globe" size={20} /></div>
        <h3 className="mp-modal-title">Request international SIMs</h3>
        <p className="mp-modal-sub">Tell us the country and how many you need. The team will come back to you with options and pricing.</p>
        <div className="mp-field">
          <label className="mp-field-label">Country</label>
          <Select value={country} onChange={setCountry} placeholder="Choose a country" options={MARKETS} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Quantity</label>
          <input className="mp-field-input" type="number" min="1" value={qty} onChange={(e) => setQty(e.target.value)} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Data plan per SIM</label>
          <Select value={plan} onChange={setPlan} placeholder="Choose a plan" options={PLANS} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Note (optional)</label>
          <textarea className="mp-field-input" rows={6} value={note} onChange={(e) => setNote(e.target.value)}
            placeholder="Anything that would help us, like a start date or who they are for, or tell us if you need a mix of plans." />
        </div>
        <div className="mp-modal-actions">
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="send" className={ready ? "" : "is-disabled"}
            onClick={ready ? () => {
              const label = (MARKETS.find((m) => m.value === country) || {}).label;
              createRequest(null, "new_sims", { market: label, qty: Number(qty), plan, note: note.trim() });
              onSent();
            } : undefined}>Send Request</Button>
        </div>
      </div>
    </div>);
}

/* ---------- Request alternative network SIMs ----------
   Mirrors the international request: network, quantity, plan, note. */
function RequestAltNetSimsModal({ onClose, onSent }) {
  const [network, setNetwork] = uR("");
  const [qty, setQty] = uR("5");
  const [plan, setPlan] = uR("");
  const [note, setNote] = uR("");
  const NETWORKS = [{ value: "O2", label: "O2" }, { value: "Vodafone", label: "Vodafone" }];
  const PLANS = Object.values(RD.PLANS).map((p) => ({ value: p.data, label: p.data }));
  const ready = network && Number(qty) > 0 && plan;
  return (
    <div className="mp-modal-overlay" onClick={onClose}>
      <div className="mp-modal mp-modal--form" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 480 }}>
        <div className="mp-modal-ic mp-modal-ic--neutral"><Icon name="card-sim" size={20} /></div>
        <h3 className="mp-modal-title">Request alternative network SIMs</h3>
        <p className="mp-modal-sub">Tell us the network and how many you need. The team will come back to you with options and pricing.</p>
        <div className="mp-field">
          <label className="mp-field-label">Network</label>
          <Select value={network} onChange={setNetwork} placeholder="Choose a network" options={NETWORKS} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Quantity</label>
          <input className="mp-field-input" type="number" min="1" value={qty} onChange={(e) => setQty(e.target.value)} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Data plan per SIM</label>
          <Select value={plan} onChange={setPlan} placeholder="Choose a plan" options={PLANS} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Note (optional)</label>
          <textarea className="mp-field-input" rows={6} value={note} onChange={(e) => setNote(e.target.value)}
            placeholder="Anything that would help us, like a start date or who they are for, or tell us if you need a mix of plans." />
        </div>
        <div className="mp-modal-actions">
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="send" className={ready ? "" : "is-disabled"}
            onClick={ready ? () => {
              createRequest(null, "altnet_sims", { network, qty: Number(qty), plan, note: note.trim() });
              onSent();
            } : undefined}>Send Request</Button>
        </div>
      </div>
    </div>);
}

/* ---------- Add SIMs and modify the data pool ----------
   Two things the team arranges, asked for in one place, because a customer
   adding SIMs usually needs more allowance with them. */
function RequestPoolChangeModal({ currentGb, onClose, onSent }) {
  const [kind, setKind] = uR("");
  const [qty, setQty] = uR("5");
  const [size, setSize] = uR("");
  const [note, setNote] = uR("");
  const TIERS = [200, 400, 600, 1000];
  const label = (gb) => (gb === 1000 ? "1 TB" : gb + " GB") + (gb === currentGb ? " (Current)" : "");
  const ready = kind === "add" ? Number(qty) > 0 : kind === "resize" ? !!size : false;
  return (
    <div className="mp-modal-overlay" onClick={onClose}>
      <div className="mp-modal mp-modal--form" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 480 }}>
        <div className="mp-modal-ic mp-modal-ic--neutral"><Icon name="layers" size={20} /></div>
        <h3 className="mp-modal-title">Add SIMs and modify data pool</h3>
        <p className="mp-modal-sub">Tell us what you need and the team will come back to you with options and pricing.</p>

        <div className="mp-sso-paths mp-sso-paths--stack" style={{ marginTop: 18 }}>
          <button type="button" className={"mp-sso-path" + (kind === "add" ? " is-selected" : "")} onClick={() => setKind("add")}>
            <span className="mp-sso-path-ic"><Icon name="card-sim" size={18} /></span>
            <span className="mp-sso-path-body">
              <span className="mp-sso-path-name">Add SIMs to the data pool</span>
              <span className="mp-sso-path-msg">More SIMs sharing the allowance you already have.</span>
            </span>
          </button>
          <button type="button" className={"mp-sso-path" + (kind === "resize" ? " is-selected" : "")} onClick={() => setKind("resize")}>
            <span className="mp-sso-path-ic"><Icon name="layers" size={18} /></span>
            <span className="mp-sso-path-body">
              <span className="mp-sso-path-name">Change the pool allowance</span>
              <span className="mp-sso-path-msg">More or less data for everyone sharing the pool.</span>
            </span>
          </button>
        </div>

        {kind === "add" ?
        <div className="mp-field">
          <label className="mp-field-label">How many SIMs</label>
          <input className="mp-field-input" type="number" min="1" value={qty} onChange={(e) => setQty(e.target.value)} />
        </div> : null}

        {kind === "resize" ?
        <div className="mp-field">
          <label className="mp-field-label">New pool size</label>
          <Select value={size} onChange={setSize} placeholder="Choose a size"
            options={TIERS.map((gb) => ({ value: String(gb), label: label(gb) }))} />
        </div> : null}

        {kind ?
        <div className="mp-field">
          <label className="mp-field-label">Note (optional)</label>
          <textarea className="mp-field-input" rows={6} value={note} onChange={(e) => setNote(e.target.value)}
            placeholder="Anything that would help us, like when you need this by." />
        </div> : null}

        <div className="mp-modal-actions">
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="send" className={ready ? "" : "is-disabled"}
            onClick={ready ? () => {
              createRequest(null, "pool_change", kind === "add" ?
                { change: "Add SIMs", qty: Number(qty), note: note.trim() } :
                { change: "Change allowance", size: label(Number(size)).replace(" (Current)", ""), note: note.trim() });
              onSent();
            } : undefined}>Send Request</Button>
        </div>
      </div>
    </div>);
}

/* ---------- Request a travel eSIM plan ---------- */
function RequestTravelPlanModal({ onClose, onSent }) {
  const [user, setUser] = uR("");
  const [dest, setDest] = uR("");
  const [kind, setKind] = uR("trip");
  const [note, setNote] = uR("");
  const ready = user && dest.trim();
  return (
    <div className="mp-modal-overlay" onClick={onClose}>
      <div className="mp-modal mp-modal--form" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 480 }}>
        <div className="mp-modal-ic mp-modal-ic--neutral"><Icon name="plane" size={20} /></div>
        <h3 className="mp-modal-title">Request a travel eSIM plan</h3>
        <p className="mp-modal-sub">Tell us who is travelling and where. The team will set the plan up and confirm the options with you.</p>
        <div className="mp-field">
          <label className="mp-field-label">Who is travelling</label>
          {window.UserSearchPicker ?
            <window.UserSearchPicker candidates={RD.USERS} value={user} onChange={setUser} /> :
            <Select value={user} onChange={setUser} placeholder="Choose a person"
              options={RD.USERS.map((u) => ({ value: String(u.id), label: u.full_name }))} />}
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Destination</label>
          <input className="mp-field-input" value={dest} onChange={(e) => setDest(e.target.value)}
            placeholder="A country or a region, like Japan or Europe" />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">How long for</label>
          <div className="mp-scope" role="group" aria-label="How long for">
            <button type="button" className={"mp-scope-btn" + (kind === "trip" ? " is-active" : "")} aria-pressed={kind === "trip"} onClick={() => setKind("trip")}>Single Trip</button>
            <button type="button" className={"mp-scope-btn" + (kind === "ongoing" ? " is-active" : "")} aria-pressed={kind === "ongoing"} onClick={() => setKind("ongoing")}>Travels Regularly</button>
          </div>
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Note (optional)</label>
          <textarea className="mp-field-input" rows={6} value={note} onChange={(e) => setNote(e.target.value)}
            placeholder="Travel dates, or how much data they are likely to need." />
        </div>
        <div className="mp-modal-actions">
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="primary" icon="send" className={ready ? "" : "is-disabled"}
            onClick={ready ? () => {
              const person = RD.USERS.find((u) => String(u.id) === String(user));
              createRequest(null, "travel_plan", {
                market: dest.trim(), person: person ? person.full_name : null,
                duration: kind === "trip" ? "Single Trip" : "Travels Regularly", note: note.trim()
              });
              onSent();
            } : undefined}>Send Request</Button>
        </div>
      </div>
    </div>);
}

window.MP_REQ = {
  useRequests, openRequestFor, noticeFor, estStatus, createRequest, createBatchRequest, resolveRequest,
  allRequests: () => REQ.list.slice(), requestSubject, requestDetail,
  dismissNotice, resolveNewestOpen, rollUsageMonth
};

Object.assign(window, {
  RequestBanner, RequestRowChip, RequestChangeDrawer, RequestNewSimsModal, RequestAltNetSimsModal,
  RequestTravelPlanModal, RequestPoolChangeModal, RequestConfirmModal, TicketLink
});
