;(function () {
/* EditSLTP — small bottom sheet for editing an existing position's
   stop-loss and take-profit. Triggered from the PositionCard's "Edit"
   button. Reuses the OrderTicket's StepperField look + behaviour but
   is intentionally smaller — only two fields, a label, and a Save CTA.
   Calls window.useTradeMutators().editPosition + showToast on save. */

const StepperField = ({ label, value, setValue, step, decimals, placeholder }) => {
  const bump = (dir) => {
    const cur = parseFloat(value);
    const base = isNaN(cur) ? 0 : cur;
    const next = Math.max(0, base + dir * step);
    setValue(next.toFixed(decimals));
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
      <span style={{ fontFamily: 'Inter', fontWeight: 500, fontSize: '12px', color: colors.muted }}>{label}</span>
      <div style={{
        height: '48px',
        padding: '0 14px',
        backgroundColor: '#fff',
        border: `1px solid ${colors.line}`,
        borderRadius: '12px',
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        gap: '8px',
      }}>
        <input
          type="text"
          inputMode="decimal"
          value={value}
          placeholder={placeholder || ''}
          onChange={(e) => setValue(e.target.value)}
          style={{
            flex: 1,
            border: 'none',
            outline: 'none',
            background: 'transparent',
            fontFamily: 'Gilroy',
            fontWeight: 600,
            fontSize: '16px',
            color: colors.ink,
            fontVariantNumeric: 'tabular-nums',
            padding: 0,
            margin: 0,
            width: '100%',
            minWidth: 0,
          }}
        />
        <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
          <button
            onClick={() => bump(+1)}
            aria-label="increase"
            style={{
              border: `1px solid ${colors.line}`, background: '#fff',
              padding: 0, margin: 0, cursor: 'pointer',
              width: '14px', height: '14px', borderRadius: '4px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              lineHeight: 1,
            }}
          >
            <span style={{ fontFamily: 'Gilroy', fontWeight: 700, fontSize: '11px', color: colors.muted, lineHeight: 1 }}>+</span>
          </button>
          <button
            onClick={() => bump(-1)}
            aria-label="decrease"
            style={{
              border: `1px solid ${colors.line}`, background: '#fff',
              padding: 0, margin: 0, cursor: 'pointer',
              width: '14px', height: '14px', borderRadius: '4px',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              lineHeight: 1,
            }}
          >
            <span style={{ fontFamily: 'Gilroy', fontWeight: 700, fontSize: '11px', color: colors.muted, lineHeight: 1 }}>−</span>
          </button>
        </div>
      </div>
    </div>
  );
};

const EditSLTP = ({ position, onClose }) => {
  const sym = window.useSymbol(position.sym);
  const { editPosition } = window.useTradeMutators();
  const isForex = sym && sym.cat === 'forex';
  const priceDecimals = isForex ? 5 : 2;
  const priceStep = isForex ? 0.0001 : 1;

  const [sl, setSl] = React.useState(position.sl != null ? position.sl.toFixed(priceDecimals) : '');
  const [tp, setTp] = React.useState(position.tp != null ? position.tp.toFixed(priceDecimals) : '');

  const save = () => {
    const slNum = parseFloat(sl);
    const tpNum = parseFloat(tp);
    editPosition(
      position.id,
      isFinite(slNum) && slNum > 0 ? slNum : undefined,
      isFinite(tpNum) && tpNum > 0 ? tpNum : undefined,
    );
    onClose();
    if (window.showToast) window.showToast('Stop-loss & Take-profit updated', 'success');
  };

  return (
    <div
      onClick={onClose}
      style={{
        /* position:absolute so the scrim is contained by the .app-frame
           on desktop iPhone mockup, not the whole browser viewport. */
        position: 'absolute',
        inset: 0,
        background: 'rgba(14,20,32,0.45)',
        zIndex: 9999,
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'flex-end',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          backgroundColor: '#fff',
          borderRadius: '24px 24px 0 0',
          /* paddingBottom adds env(safe-area-inset-bottom) so the Save
             button stays above the iOS home indicator on PWA. */
          padding: '20px',
          paddingBottom: 'calc(20px + env(safe-area-inset-bottom, 0px))',
          boxShadow: '0px -12px 40px rgba(14,20,32,0.24)',
          display: 'flex',
          flexDirection: 'column',
          gap: '14px',
        }}
      >
        <div style={{
          width: '60px', height: '4px', borderRadius: '2px',
          backgroundColor: colors.line, alignSelf: 'center',
          marginTop: '-4px', marginBottom: '4px',
        }} />
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          <span style={{ fontFamily: 'Gilroy', fontWeight: 700, fontSize: '18px', color: colors.ink }}>
            Edit Stop-Loss & Take-Profit
          </span>
          <span style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '12px', color: colors.muted2, marginTop: '2px' }}>
            {position.sym + ' · ' + position.size + ' ' + (sym ? (sym.cat === 'stocks' ? 'shares' : 'lots') : 'units')}
          </span>
        </div>
        <StepperField label="Stop Loss" value={sl} setValue={setSl} step={priceStep} decimals={priceDecimals} placeholder="—" />
        <StepperField label="Take Profit" value={tp} setValue={setTp} step={priceStep} decimals={priceDecimals} placeholder="—" />
        <button
          onClick={save}
          style={{
            border: 'none',
            background: colors.teal,
            padding: 0, margin: 0, cursor: 'pointer',
            width: '100%', height: '52px',
            borderRadius: '14px',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginTop: '4px',
          }}
        >
          <span style={{ fontFamily: 'Gilroy', fontWeight: 600, fontSize: '15px', color: '#fff' }}>Save</span>
        </button>
      </div>
    </div>
  );
};

Object.assign(window, { EditSLTP });
})();
