// Create / Edit shipping method — modal/sheet with template picker step + form step
const { useState: useStateCE, useEffect: useEffectCE } = React;

const blankMethod = () => ({
  name: "", code: "", description: "",
  active: true, isDefault: false,
  type: "", carrier: "", priority: "Standard",
  trackingEnabled: false, trackingUrl: "",
  transit: "", requiresTracking: false, signature: false,
  customCarrierName: "",
  availableInQuoting: true, availableInPurchasing: true, availableForInternalTransfer: false,
  pricing: "Flat Rate", flat: "",
  apiCarrier: "", apiService: "", apiMarkupPercent: "",
  amountEntryPoint: "Shipment", requireAmountBeforeContinuing: false, allowAmountOverride: true,
  ownership: "When Shipped",
  warehouses: [], countries: [],
  customers: [],
  internalNotes: "",
});

const slugCode = (s) => s.toUpperCase().replace(/[^A-Z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 14);

const CreateSheet = ({ onClose, onSave, initial, mode = "create" }) => {
  const [step, setStep] = useState(mode === "edit" ? "form" : "template"); // template | form
  const [draft, setDraft] = useState(() => initial ? { ...blankMethod(), ...initial } : blankMethod());
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [showAvailability, setShowAvailability] = useState(false);

  const set = (k, v) => setDraft(d => {
    const next = { ...d, [k]: v };
    if (k === "name" && (!d.code || d.code === slugCode(d.name))) next.code = slugCode(v);
    // Customer Pickup forces specific fields and disables others on the form.
    if (k === "type" && v === "Customer Pickup") {
      next.carrier = "";
      next.isDefault = false;
      next.pricing = "Flat Rate";
      next.ownership = "When Delivered";
      next.trackingEnabled = false;
      next.trackingUrl = "";
      next.transit = "";
    }
    // When carrier changes to a known carrier, lock + auto-fill the tracking URL
    // and turn tracking on. When switching away to Custom/blank, keep whatever
    // they had (or blank) so they can author their own.
    if (k === "carrier") {
      if (CARRIER_TRACKING_LOCKED(v)) {
        next.trackingUrl = CARRIER_TRACKING_URLS[v];
        next.trackingEnabled = true;
      } else if (CARRIER_TRACKING_LOCKED(d.carrier)) {
        // Coming from a locked carrier — clear the templated URL so they
        // don't accidentally keep the old one.
        next.trackingUrl = "";
      }
    }
    return next;
  });

  const pickTemplate = (t) => {
    setDraft({
      ...blankMethod(),
      name: t.name, code: slugCode(t.name), type: t.type, carrier: t.carrier,
      transit: String(t.transit), trackingEnabled: t.tracking,
      trackingUrl: CARRIER_TRACKING_LOCKED(t.carrier) ? CARRIER_TRACKING_URLS[t.carrier] : "",
      pricing: t.pricing, flat: t.flat ? t.flat.toFixed(2) : "",
      signature: t.signature, ownership: t.ownership,
      description: t.description, active: true,
      availableInQuoting: true, availableInPurchasing: true,
    });
    setStep("form");
  };

  const startFromScratch = () => {
    setDraft(blankMethod());
    setStep("form");
  };

  const valid = draft.name && draft.code && draft.type && (draft.pricing !== "Flat Rate" || draft.flat !== "") && (draft.carrier !== "Custom" || draft.customCarrierName.trim() !== "") && (draft.pricing !== "Automated (API)" || draft.apiCarrier);

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, background: "rgba(26,27,37,.45)", zIndex: 100,
      display: "flex", justifyContent: "flex-end"
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 720, maxWidth: "100vw", height: "100%", background: "#fff",
        borderLeft: "1px solid var(--mw-border)", boxShadow: "var(--mw-shadow-pop)",
        display: "flex", flexDirection: "column", animation: "slideIn 200ms cubic-bezier(0.2,0.6,0.2,1)"
      }}>
        {/* Header */}
        <div style={{ display: "flex", alignItems: "center", padding: "16px 24px", borderBottom: "1px solid var(--mw-border-soft)", gap: 12 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: "var(--mw-brand-50)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <ShippingTypeIcon type={draft.type || "Parcel"} color="var(--mw-brand-500)" size={18} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 600 }}>{mode === "edit" ? "Edit Shipping Method" : (step === "template" ? "New Shipping Method" : (draft.name || "New Shipping Method"))}</div>
            <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>
              {step === "template" ? "Pick a template or start from scratch." : "Fields marked with * are required."}
            </div>
          </div>
          {mode === "create" && step === "form" && (
            <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "4px 10px 4px 12px", border: "1px solid var(--mw-border)", borderRadius: 9999, background: "#fff" }}>
              <span style={{ fontSize: 12, fontWeight: 500, color: draft.active ? "var(--mw-text-primary)" : "var(--mw-text-tertiary)" }}>{draft.active ? "Active" : "Inactive"}</span>
              <Toggle size="sm" checked={draft.active} onChange={v => set("active", v)} />
            </div>
          )}
          <button onClick={onClose} style={{ width: 32, height: 32, border: 0, background: "transparent", borderRadius: 8, cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <img src="assets/icons/cross.svg" style={{ width: 16, height: 16, opacity: 0.6 }} />
          </button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: "auto" }}>
          {step === "template" && <TemplatePicker onPick={pickTemplate} onScratch={startFromScratch} />}
          {step === "form" && (
            <FormBody draft={draft} set={set} mode={mode} showAdvanced={showAdvanced} setShowAdvanced={setShowAdvanced} showAvailability={showAvailability} setShowAvailability={setShowAvailability} />
          )}
        </div>

        {/* Footer */}
        <div style={{ display: "flex", alignItems: "center", padding: "12px 24px", borderTop: "1px solid var(--mw-border-soft)", gap: 8, background: "#fff" }}>
          {step === "form" && mode === "create" && (
            <Button kind="ghost" icon="chevronRight" onClick={() => setStep("template")} style={{ marginRight: "auto" }}>
              <span style={{ transform: "rotate(180deg)", display: "inline-flex" }}><img src="assets/icons/chevronRight.svg" style={{ width: 14, height: 14 }} /></span>
              Back to templates
            </Button>
          )}
          {step === "template" && <Button kind="ghost" onClick={onClose} style={{ marginRight: "auto" }}>Cancel</Button>}
          <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
            <Button kind="secondary" onClick={onClose}>Cancel</Button>
            {step === "form" && (
              <Button kind="primary" disabled={!valid} onClick={() => onSave(draft)}>
                {mode === "edit" ? "Save Changes" : "Create Method"}
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// ---------- TEMPLATE PICKER ----------------------------------------------
const TemplatePicker = ({ onPick, onScratch }) => {
  const groups = [
    { label: "Freight", items: TEMPLATES.filter(t => ["LTL Freight","FTL Freight","Ocean Freight","Air Freight"].includes(t.type)) },
    { label: "Shipping Carriers", items: TEMPLATES.filter(t => t.type === "Parcel") },
    { label: "Local", items: TEMPLATES.filter(t => ["Local Delivery","Customer Pickup"].includes(t.type)) },
  ];
  return (
    <div style={{ padding: "20px 24px 28px" }}>
      <div style={{ marginBottom: 24 }}>
        <button onClick={onScratch} style={{
          width: "100%", border: "1px solid var(--mw-brand-200)", borderRadius: 12, padding: "16px 18px",
          background: "linear-gradient(135deg, rgba(232,233,246,0.9) 0%, rgba(207,231,255,0.55) 100%)",
          textAlign: "left", cursor: "pointer", fontFamily: "inherit",
          display: "flex", alignItems: "center", gap: 14, transition: "all 120ms"
        }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--mw-brand-500)"; e.currentTarget.style.boxShadow = "var(--mw-shadow-card)"; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--mw-brand-200)"; e.currentTarget.style.boxShadow = "none"; }}>
          <div style={{ width: 36, height: 36, borderRadius: 8, background: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", boxShadow: "0 1px 2px rgba(83,74,255,0.12)" }}>
            <img src="assets/icons/plus.svg" style={{ width: 18, height: 18, opacity: 0.85 }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: "var(--mw-text-primary)" }}>Start from scratch</div>
            <div style={{ fontSize: 12, color: "var(--mw-text-secondary)", marginTop: 2 }}>Build a custom method with your own carrier, pricing, and rules.</div>
          </div>
          <img src="assets/icons/chevronRight.svg" style={{ width: 16, height: 16, opacity: 0.6 }} />
        </button>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "4px 0 16px" }}>
        <div style={{ flex: 1, height: 1, background: "var(--mw-border-soft)" }} />
        <div style={{ fontSize: 11, fontWeight: 600, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: ".08em" }}>Quick Start Templates</div>
        <div style={{ flex: 1, height: 1, background: "var(--mw-border-soft)" }} />
      </div>
      {groups.map(g => (
        <div key={g.label} style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 11, fontWeight: 500, color: "var(--mw-text-tertiary)", textTransform: "uppercase", letterSpacing: ".06em", marginBottom: 10 }}>{g.label}</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            {g.items.map(t => (
              <button key={t.id} onClick={() => onPick(t)} style={{
                border: "1px solid var(--mw-border)", borderRadius: 12, padding: "12px 14px",
                background: "#fff", textAlign: "left", cursor: "pointer", fontFamily: "inherit",
                display: "flex", alignItems: "flex-start", gap: 12, transition: "all 120ms"
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--mw-brand-200)"; e.currentTarget.style.boxShadow = "var(--mw-shadow-card)"; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--mw-border)"; e.currentTarget.style.boxShadow = "none"; }}>
                <TypeEmblem type={t.type} size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: "var(--mw-text-primary)" }}>{t.name}</div>
                  <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 2, lineHeight: 1.4 }}>{t.description}</div>
                  <div style={{ display: "flex", gap: 6, marginTop: 8, flexWrap: "wrap" }}>
                    <Chip tone="neutral" size="sm">{t.type}</Chip>
                    {t.tracking && <Chip tone="info" size="sm">Tracking</Chip>}
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

// ---------- FORM BODY ----------------------------------------------------
const FormBody = ({ draft, set, mode = "create", showAdvanced, setShowAdvanced, showAvailability, setShowAvailability }) => {
  const isPickup = draft.type === "Customer Pickup";
  const showDefault = mode === "edit";
  return (
    <div style={{ padding: "20px 24px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
      {/* Section: Basics */}
      <Section title="Basics">
        <Grid cols={2}>
          <FormRow label="Shipping Method Name" required>
            <Input value={draft.name} onChange={e => set("name", e.target.value)} placeholder="e.g. UPS Ground" />
          </FormRow>
          <FormRow label="Code" required hint="Unique internal identifier used in integrations and reports." helper="Auto-generated from the name. Edit if needed.">
            <Input value={draft.code} onChange={e => set("code", e.target.value.toUpperCase())} placeholder="UPS-GRD" />
          </FormRow>
        </Grid>
        <Grid cols={2}>
          <FormRow label="Carrier">
            <Select value={draft.carrier} onChange={e => set("carrier", e.target.value)} options={["", ...CARRIERS]} placeholder="Optional" disabled={isPickup} />
          </FormRow>
          {draft.carrier === "Custom" ? (
            <FormRow label="Custom Carrier Name" required helper="Used on documents, tracking emails, and reports in place of a standard carrier name.">
              <Input value={draft.customCarrierName} onChange={e => set("customCarrierName", e.target.value)} placeholder="e.g. Hometown Freight Co." />
            </FormRow>
          ) : <div />}
        </Grid>
        <FormRow label="Description">
          <Textarea value={draft.description} onChange={e => set("description", e.target.value)} rows={2} placeholder="Optional. Shown to customers if Customer Visible is enabled." />
        </FormRow>
        <Grid cols={2}>
          <FormRow label="Shipping Type" required>
            <Select value={draft.type} onChange={e => set("type", e.target.value)} options={SHIPPING_TYPES} placeholder="Select type" />
          </FormRow>
          <FormRow label="Shipping Priority" required>
            <Select value={draft.priority} onChange={e => set("priority", e.target.value)} options={SHIPPING_PRIORITIES} />
          </FormRow>
          <div />
          <FormRow label="Estimated Transit Days" helper={isPickup ? "Not applicable for Customer Pickup." : undefined}>
            <Input value={draft.transit} onChange={e => set("transit", e.target.value.replace(/[^\d]/g, ""))} suffix="days" placeholder="0" disabled={isPickup} />
          </FormRow>
        </Grid>

        {(showDefault || mode === "edit") && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, paddingTop: 4 }}>
            <ToggleRow title="Active" description="Available to use on new orders." checked={draft.active} onChange={v => set("active", v)} />
            {showDefault && (
              <ToggleRow title="Default Method" description={isPickup ? "Customer Pickup can't be set as the default method." : "Used when a customer hasn't picked one."} checked={draft.isDefault} onChange={v => set("isDefault", v)} disabled={isPickup} />
            )}
          </div>
        )}
      </Section>

      {/* Section: Pricing */}
      <Section title="Pricing">
        <Grid cols={draft.pricing === "Flat Rate" ? 2 : 1}>
          <FormRow label="Pricing Method" required helper={isPickup ? "Customer Pickup is always Flat Rate." : undefined}>
            <Select value={draft.pricing} onChange={e => set("pricing", e.target.value)} options={PRICING_METHODS} disabled={isPickup} />
          </FormRow>
          {draft.pricing === "Flat Rate" && (
            <FormRow label="Flat Shipping Amount" required helper="Charged once per order, in USD.">
              <Input value={draft.flat} onChange={e => set("flat", e.target.value.replace(/[^\d.]/g, ""))} prefix="$" placeholder="0.00" />
            </FormRow>
          )}
        </Grid>
        {draft.pricing === "Manual" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: "12px 14px", background: "var(--mw-bg)", border: "1px solid var(--mw-border-soft)", borderRadius: 10 }}>
            <FormRow
              label="Shipping Amount Entry Point"
              required
              hint="When users will be prompted to enter the shipping amount during the order lifecycle."
              helper="Most warehouses use 'Shipment' — actual cost is known at fulfillment."
            >
              <EntryPointSelect value={draft.amountEntryPoint} onChange={v => set("amountEntryPoint", v)} />
            </FormRow>
            <Divider />
            <ToggleRow
              title="Require Amount Before Continuing"
              description={`Block progress past the ${draft.amountEntryPoint} step until a shipping amount is entered.`}
              checked={draft.requireAmountBeforeContinuing}
              onChange={v => set("requireAmountBeforeContinuing", v)}
            />
            <ToggleRow
              title="Allow Amount Override"
              description="Authorized users can modify the shipping charge later in the process."
              checked={draft.allowAmountOverride}
              onChange={v => set("allowAmountOverride", v)}
            />
          </div>
        )}
        {draft.pricing === "Automated (API)" && (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: "12px 14px", background: "rgba(232,233,246,.35)", border: "1px solid var(--mw-brand-200)", borderRadius: 10 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 28, height: 28, borderRadius: 8, background: "#fff", border: "1px solid var(--mw-brand-200)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                <img src="assets/icons/ai.svg" style={{ width: 14, height: 14, opacity: 0.8 }} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>Real-time rates from carrier API</div>
                <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)" }}>Rates are quoted live at checkout using the configured carrier integration.</div>
              </div>
              <Chip tone="info" size="sm" dot>Live</Chip>
            </div>
            <Divider />
            <Grid cols={2}>
              <FormRow label="API Carrier" required helper="Must have credentials configured in Integrations.">
                <Select value={draft.apiCarrier} onChange={e => set("apiCarrier", e.target.value)} options={["FedEx", "UPS", "DHL", "USPS"]} placeholder="Select carrier" />
              </FormRow>
              <FormRow label="Service Level">
                <Select value={draft.apiService} onChange={e => set("apiService", e.target.value)} options={["Ground", "2-Day", "Overnight", "International Economy", "International Priority"]} placeholder="Any" />
              </FormRow>
            </Grid>
            <FormRow label="Markup" helper="Added on top of the rate returned by the carrier API.">
              <Input value={draft.apiMarkupPercent} onChange={e => set("apiMarkupPercent", e.target.value.replace(/[^\d.]/g, ""))} suffix="%" placeholder="0" />
            </FormRow>
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", borderRadius: 8, background: "#fff", border: "1px solid var(--mw-border-soft)", fontSize: 12, color: "var(--mw-text-tertiary)" }}>
              <img src="assets/icons/infoCircle.svg" style={{ width: 12, height: 12, opacity: 0.6 }} />
              If the carrier API is unreachable at checkout, the order will fall back to manual pricing.
            </div>
          </div>
        )}
        <FormRow label="Ownership Transfers" hint="When title transfers from your business to the customer." helper={isPickup ? "Customer Pickup transfers ownership when delivered to the customer." : "Most ground methods use 'When Shipped'; freight typically uses 'When Delivered'."}>
          <Select value={draft.ownership} onChange={e => set("ownership", e.target.value)} options={OWNERSHIP_OPTIONS} disabled={isPickup} />
        </FormRow>
      </Section>

      {/* Section: Availability in modules */}
      <Section title="Module Availability">
        <ToggleRow title="Available in Quoting" description="Salespeople can offer this shipping method on customer quotes." checked={draft.availableInQuoting} onChange={v => set("availableInQuoting", v)} />
        <Divider />
        <ToggleRow title="Available in Purchasing" description="Buyers can specify this method on purchase orders to vendors." checked={draft.availableInPurchasing} onChange={v => set("availableInPurchasing", v)} />
        <Divider />
        <ToggleRow title="Available for Internal Transfer" description="Use this method when moving stock between your own warehouses." checked={draft.availableForInternalTransfer} onChange={v => set("availableForInternalTransfer", v)} />
      </Section>

      {/* Section: Tracking & Operations */}
      <Section title="Tracking & Operations">
        <ToggleRow title="Tracking Enabled" description={isPickup ? "Not applicable for Customer Pickup." : "Lets ops staff attach a tracking number and share it with customers."} checked={draft.trackingEnabled} onChange={v => set("trackingEnabled", v)} disabled={isPickup} />
        {draft.trackingEnabled && (
          <div style={{ marginLeft: 0, paddingLeft: 0, display: "flex", flexDirection: "column", gap: 10, marginBottom: 12 }}>
            <FormRow
              label="Tracking URL Template"
              hint="Use {tracking_number} as a placeholder for the package tracking number."
              helper={
                CARRIER_TRACKING_LOCKED(draft.carrier)
                  ? `Managed automatically for ${draft.carrier}. Switch carrier to "Custom" to edit.`
                  : "Use {tracking_number} where the tracking number should appear."
              }
              style={{ marginTop: -4 }}
            >
              {CARRIER_TRACKING_LOCKED(draft.carrier) ? (
                <LockedInput value={draft.trackingUrl} carrier={draft.carrier} />
              ) : (
                <Input
                  value={draft.trackingUrl}
                  onChange={e => set("trackingUrl", e.target.value)}
                  placeholder="https://your-carrier.com/track?id={tracking_number}"
                />
              )}
            </FormRow>
            <ToggleRow title="Requires Tracking Number" description="Block 'Mark as Shipped' until a tracking number is entered." checked={draft.requiresTracking} onChange={v => set("requiresTracking", v)} />
          </div>
        )}
        <Divider />
        <ToggleRow title="Requires Signature" description="Carrier collects a signature on delivery." checked={draft.signature} onChange={v => set("signature", v)} />
      </Section>

      {/* Collapsed: availability */}
      <CollapsibleSection title="Availability" subtitle="Limit this method to specific warehouses, countries, or customers." open={showAvailability} onToggle={() => setShowAvailability(o => !o)}>
        <FormRow label="Available Warehouses" helper="Leave empty to make this method available everywhere.">
          <MultiSelect options={WAREHOUSES} value={draft.warehouses} onChange={v => set("warehouses", v)} placeholder="All warehouses" />
        </FormRow>
        <FormRow label="Available Countries">
          <MultiSelect options={COUNTRIES} value={draft.countries} onChange={v => set("countries", v)} placeholder="All countries" />
        </FormRow>
        <FormRow label="Available Customers" helper="Restrict to specific customers — useful for negotiated freight rates.">
          <MultiSelect options={["Infinity Payroll Services","Northstar Manufacturing","Vector Steel Works","Halcyon Plastics","Crestwood Robotics","Bridgepoint Foundries","Kestrel Aerospace"]} value={draft.customers} onChange={v => set("customers", v)} placeholder="All customers" />
        </FormRow>
      </CollapsibleSection>

      {/* Collapsed: advanced */}
      <CollapsibleSection title="Internal Notes" subtitle="Visible only to your team." open={showAdvanced} onToggle={() => setShowAdvanced(o => !o)}>
        <Textarea value={draft.internalNotes} onChange={e => set("internalNotes", e.target.value)} rows={3} placeholder="Add any internal notes for warehouse staff or admins…" />
      </CollapsibleSection>
    </div>
  );
};

// ---------- SECTION HELPERS ---------------------------------------------
const Section = ({ title, children }) => (
  <section style={{ display: "flex", flexDirection: "column", gap: 12 }}>
    <div style={{ fontSize: 13, fontWeight: 600, color: "var(--mw-text-primary)", letterSpacing: "-0.005em" }}>{title}</div>
    <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: "16px 18px", border: "1px solid var(--mw-border)", borderRadius: 12, background: "#fff" }}>
      {children}
    </div>
  </section>
);

const CollapsibleSection = ({ title, subtitle, open, onToggle, children }) => (
  <section style={{ display: "flex", flexDirection: "column", gap: open ? 12 : 0 }}>
    <button onClick={onToggle} style={{
      display: "flex", alignItems: "center", gap: 12, padding: "12px 16px",
      border: "1px solid var(--mw-border)", borderRadius: open ? "12px 12px 0 0" : 12,
      borderBottom: open ? "1px solid var(--mw-border-soft)" : "1px solid var(--mw-border)",
      background: "#fff", cursor: "pointer", fontFamily: "inherit", textAlign: "left", width: "100%"
    }}>
      <img src="assets/icons/expandDown.svg" style={{ width: 12, height: 12, opacity: 0.6, transform: open ? "none" : "rotate(-90deg)", transition: "transform 120ms" }} />
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 1, fontWeight: 400 }}>{subtitle}</div>}
      </div>
    </button>
    {open && (
      <div style={{ display: "flex", flexDirection: "column", gap: 12, padding: "16px 18px", border: "1px solid var(--mw-border)", borderTop: 0, borderRadius: "0 0 12px 12px", background: "#fff", marginTop: -12 }}>
        {children}
      </div>
    )}
  </section>
);

const Grid = ({ cols = 2, children }) => (
  <div style={{ display: "grid", gridTemplateColumns: `repeat(${cols}, 1fr)`, gap: 12 }}>{children}</div>
);

const Divider = () => <div style={{ height: 1, background: "var(--mw-border-soft)", margin: "0 -2px" }} />;

const LockedInput = ({ value, carrier }) => (
  <div style={{
    display: "flex", alignItems: "center", gap: 8, height: 32, padding: "0 10px",
    border: "1px solid var(--mw-border-soft)", borderRadius: 8,
    background: "var(--mw-bg)", color: "var(--mw-text-secondary)",
  }}>
    <img src="assets/icons/lock.svg" style={{ width: 12, height: 12, opacity: 0.55, flexShrink: 0 }} />
    <span style={{
      flex: 1, fontFamily: "var(--mw-font-mono)", fontSize: 12,
      overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
    }}>{value}</span>
    <Chip tone="neutral" size="sm">Managed</Chip>
  </div>
);

// Rich dropdown for the Shipping Amount Entry Point — shows a one-line hint
// under each option so admins pick the right step without guessing.
const EntryPointSelect = ({ value, onChange }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);
  const current = AMOUNT_ENTRY_POINTS.find(o => o.value === value) || AMOUNT_ENTRY_POINTS[1];
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} style={{
        display: "flex", alignItems: "center", gap: 8, width: "100%", height: 32,
        padding: "0 10px", border: "1px solid var(--mw-border-strong)", borderRadius: 8,
        background: "#fff", cursor: "pointer", fontFamily: "inherit", fontSize: 14,
        color: "var(--mw-text-primary)", textAlign: "left"
      }}>
        <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{current.label}</span>
        <img src="assets/icons/expandDown.svg" style={{ width: 12, height: 12, opacity: 0.5 }} />
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0,
          background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 8,
          boxShadow: "var(--mw-shadow-pop)", zIndex: 10, padding: 4
        }}>
          {AMOUNT_ENTRY_POINTS.map(o => {
            const sel = o.value === value;
            return (
              <button key={o.value} onClick={() => { onChange(o.value); setOpen(false); }} style={{
                display: "flex", alignItems: "flex-start", gap: 10, width: "100%", padding: "8px 10px",
                border: 0, background: sel ? "var(--mw-brand-50)" : "transparent",
                borderRadius: 6, cursor: "pointer", fontFamily: "inherit", textAlign: "left"
              }}
              onMouseEnter={e => { if (!sel) e.currentTarget.style.background = "var(--mw-bg)"; }}
              onMouseLeave={e => { if (!sel) e.currentTarget.style.background = "transparent"; }}>
                <div style={{ width: 16, height: 16, borderRadius: 99, border: `1.5px solid ${sel ? "var(--mw-brand-500)" : "var(--mw-border-strong)"}`, display: "inline-flex", alignItems: "center", justifyContent: "center", marginTop: 2, flexShrink: 0 }}>
                  {sel && <div style={{ width: 8, height: 8, borderRadius: 99, background: "var(--mw-brand-500)" }} />}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: "var(--mw-text-primary)" }}>{o.label}</div>
                  <div style={{ fontSize: 12, color: "var(--mw-text-tertiary)", marginTop: 1, lineHeight: 1.4 }}>{o.hint}</div>
                </div>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

// ---------- MULTISELECT --------------------------------------------------
const MultiSelect = ({ options, value, onChange, placeholder }) => {
  const [open, setOpen] = useState(false);
  const ref = React.useRef(null);
  useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);
  const toggle = (opt) => onChange(value.includes(opt) ? value.filter(v => v !== opt) : [...value, opt]);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <div onClick={() => setOpen(o => !o)} style={{
        minHeight: 32, padding: value.length ? "4px 32px 4px 6px" : "0 32px 0 10px",
        display: "flex", alignItems: "center", flexWrap: "wrap", gap: 4,
        border: "1px solid var(--mw-border-strong)", borderRadius: 8, background: "#fff",
        cursor: "pointer", fontSize: 14
      }}>
        {value.length === 0 && <span style={{ color: "var(--mw-text-tertiary)" }}>{placeholder}</span>}
        {value.map(v => (
          <span key={v} style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "2px 4px 2px 8px", borderRadius: 6, background: "var(--mw-bg)", border: "1px solid var(--mw-border-soft)", fontSize: 12 }}>
            {v}
            <button onClick={e => { e.stopPropagation(); toggle(v); }} style={{ width: 16, height: 16, border: 0, background: "transparent", borderRadius: 4, cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
              <img src="assets/icons/cross.svg" style={{ width: 10, height: 10, opacity: 0.5 }} />
            </button>
          </span>
        ))}
        <img src="assets/icons/expandDown.svg" style={{ position: "absolute", right: 10, top: 10, width: 12, height: 12, opacity: 0.5 }} />
      </div>
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 4px)", left: 0, right: 0, background: "#fff", border: "1px solid var(--mw-border)", borderRadius: 8, boxShadow: "var(--mw-shadow-pop)", zIndex: 10, maxHeight: 240, overflowY: "auto", padding: 4 }}>
          {options.map(opt => {
            const sel = value.includes(opt);
            return (
              <button key={opt} onClick={() => toggle(opt)} style={{
                display: "flex", alignItems: "center", gap: 8, width: "100%", padding: "8px 10px",
                border: 0, background: sel ? "var(--mw-bg)" : "transparent", borderRadius: 6, cursor: "pointer",
                fontFamily: "inherit", fontSize: 13, color: "var(--mw-text-primary)", textAlign: "left"
              }}>
                <div style={{ width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${sel ? "var(--mw-brand-500)" : "var(--mw-border-strong)"}`, background: sel ? "var(--mw-brand-500)" : "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
                  {sel && <img src="assets/icons/check.svg" style={{ width: 10, height: 10, filter: "brightness(0) invert(1)" }} />}
                </div>
                {opt}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

const { useEffect, useRef } = React;

window.CreateSheet = CreateSheet;
