;(function () {
/* CashFlowNotification — slide-down banner at the top of the frame
   for cash-flow demo failures (deposit failed, withdrawal pending due
   to provider issues) and trading-related demo gates (market closed
   for symbols without a live tick feed). Two visual states:

     pill  : compact 350×74 row with alert icon + title + compact copy.
             Slides down from above the frame on first show.
     card  : expanded panel with the same icon + title + body copy +
             "Talk to Equiti+" button + close X. Grows in place from
             the pill — same top anchor, height + inner content morph.

   Triggered globally via window.showCashFlowNotification(kind, ctx)
   where kind ∈ {'deposit', 'withdraw', 'marketClosed', 'liquidityDown'}.
   ctx is an optional object — for the symbol-aware kinds it holds
   {sym, name} so the copy can mention the specific instrument.
   Tapping the pill expands it and minimises any open cash-flow sheet
   via window.openCashFlow(null). The Talk-to button calls
   window.openVoice() and dismisses. */

const ANIM_MS = 380;
const EASE = 'cubic-bezier(0.32, 0.72, 0.24, 1)';

/* Build the copy block for the active notification. Symbol-aware kinds
   pull from ctx so the body copy can name the instrument. Other kinds
   ignore ctx. */
function buildCopy(kind, ctx) {
  if (kind === 'liquidityDown') {
    const symLabel = (ctx && (ctx.name || ctx.sym)) || 'this symbol';
    const symId = (ctx && ctx.sym) || 'this symbol';
    return {
      title: 'Liquidity price stream down',
      compact: 'Click here for more insight on why this trade is unavailable.',
      body: `${symLabel} is currently unavailable for trading because our liquidity providers' price stream for ${symId} is offline. We're working on restoring the feed — please try again shortly.`,
    };
  }
  if (kind === 'marketClosed') {
    const symLabel = (ctx && (ctx.name || ctx.sym)) || 'this symbol';
    const symId = (ctx && ctx.sym) || 'this symbol';
    return {
      title: 'Market closed',
      compact: 'Click here for more insight on why this trade is unavailable.',
      body: `Trading on ${symLabel} is closed at the moment. We don't have a live price feed for ${symId} right now, so orders can't be placed. Please try again during regular market hours for this instrument.`,
    };
  }
  if (kind === 'withdraw') {
    return {
      title: 'Withdrawal pending',
      compact: 'Click here for more insight on the delay reason.',
      body: 'Withdrawals are taking longer than usual due to a delay with our payment providers. Your request is queued and will process automatically once their systems are back online.',
    };
  }
  /* default: deposit */
  return {
    title: 'Deposit failed',
    compact: 'Click here for more insight on the failure reason.',
    body: "Deposits are temporarily unavailable due to scheduled maintenance with our payment providers. To bypass the downtime, we've sent a secure payment link to your email — completing the deposit there will credit your account immediately. No funds were taken from your card.",
  };
}

const Alert = ({ size = 22, color = '#F04438' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
    <circle cx={12} cy={12} r={10} fill={color}/>
    <path d="M12 7v6" stroke="#fff" strokeWidth={2} strokeLinecap="round"/>
    <circle cx={12} cy={16.5} r={1.1} fill="#fff"/>
  </svg>
);

const ChevR = ({ color = '#98A2B3' }) => (
  <svg width={16} height={16} viewBox="0 0 16 16" fill="none">
    <path d="M6 4l4 4-4 4" stroke={color} strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const CloseX = ({ color = '#98A2B3' }) => (
  <svg width={14} height={14} viewBox="0 0 24 24" fill="none">
    <path d="M6 6l12 12M18 6L6 18" stroke={color} strokeWidth={2} strokeLinecap="round"/>
  </svg>
);

const CashFlowNotification = () => {
  const [kind, setKind] = React.useState(null);
  const [ctx, setCtx] = React.useState(null);
  const [mounted, setMounted] = React.useState(false);
  const [shown, setShown] = React.useState(false);
  const [expanded, setExpanded] = React.useState(false);
  /* Cache the latest non-null kind + ctx so close animation has copy
     to render until unmount. */
  const [activeKind, setActiveKind] = React.useState(null);
  const [activeCtx, setActiveCtx] = React.useState(null);

  React.useEffect(() => {
    if (kind) {
      setActiveKind(kind);
      setActiveCtx(ctx);
    }
  }, [kind, ctx]);

  React.useEffect(() => {
    window.showCashFlowNotification = (k, c) => {
      if (!k) return;
      setKind(k);
      setCtx(c || null);
      setExpanded(false);
    };
    return () => { delete window.showCashFlowNotification; };
  }, []);

  /* Mount / show choreography. */
  React.useEffect(() => {
    if (kind) {
      setMounted(true);
      let raf2;
      const raf1 = requestAnimationFrame(() => {
        raf2 = requestAnimationFrame(() => setShown(true));
      });
      return () => {
        cancelAnimationFrame(raf1);
        if (raf2) cancelAnimationFrame(raf2);
      };
    } else if (mounted) {
      setShown(false);
      const t = setTimeout(() => {
        setMounted(false);
        setActiveKind(null);
        setActiveCtx(null);
      }, ANIM_MS);
      return () => clearTimeout(t);
    }
  }, [kind]);

  if (!mounted || !activeKind) return null;
  const copy = buildCopy(activeKind, activeCtx);

  const dismiss = () => { setKind(null); setCtx(null); };

  const expand = () => {
    /* Tapping the pill expands it AND closes any open cash-flow
       sheet ("minimise the deposit page"). The cash-flow sheet hooks
       into window.openCashFlow at App level — null clears it. */
    setExpanded(true);
    if (window.openCashFlow) window.openCashFlow(null);
  };

  const handleTalk = () => {
    setKind(null);
    setCtx(null);
    if (window.openVoice) window.openVoice();
  };

  /* The wordmark used inside the Talk-to button. Re-use the one
     exposed by hero.jsx (Equiti). */
  const Wordmark = window.EquitiWordmark;

  return (
    <div
      style={{
        position: 'absolute',
        top: '20px',
        left: '20px',
        right: '20px',
        zIndex: 9100,
        display: 'flex',
        flexDirection: 'column',
        opacity: shown ? 1 : 0,
        transform: shown ? 'translateY(0)' : 'translateY(-24px)',
        transition: `opacity ${ANIM_MS}ms ${EASE}, transform ${ANIM_MS}ms ${EASE}`,
        pointerEvents: shown ? 'auto' : 'none',
      }}
    >
      <div
        onClick={expanded ? undefined : expand}
        style={{
          backgroundColor: '#fff',
          borderRadius: '14px',
          boxShadow: '0px 14px 32px rgba(14,20,32,0.22)',
          border: '1px solid #FEE4E2',
          overflow: 'hidden',
          /* Height transition gives the "grow in place" feel. We use
             maxHeight rather than height so the content drives the
             expanded size naturally. */
          maxHeight: expanded ? '320px' : '74px',
          transition: `max-height ${ANIM_MS}ms ${EASE}`,
          cursor: expanded ? 'default' : 'pointer',
        }}
      >
        {/* Top row — always visible. Same in both states.
           Pill (collapsed): title + compact subtitle stacked vertically.
           Card (expanded): title alone — body copy lives in the panel
           below. */}
        <div style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          gap: '12px',
          paddingTop: '12px',
          paddingBottom: '12px',
          paddingLeft: '14px',
          paddingRight: '12px',
          height: expanded ? '60px' : '74px',
          boxSizing: 'border-box',
        }}>
          <Alert />
          <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: '3px' }}>
            <span style={{
              fontFamily: 'Gilroy',
              fontWeight: 700,
              fontSize: '14px',
              lineHeight: 1.1,
              color: colors.ink,
            }}>{copy.title}</span>
            {!expanded ? (
              <span style={{
                fontFamily: 'Inter',
                fontWeight: 400,
                fontSize: '11px',
                lineHeight: 1.3,
                color: colors.muted,
              }}>{copy.compact}</span>
            ) : null}
          </div>
          {expanded ? (
            <button
              onClick={(e) => { e.stopPropagation(); dismiss(); }}
              aria-label="Dismiss"
              style={{
                border: 'none', background: '#F2F4F7', padding: 0, margin: 0,
                cursor: 'pointer',
                width: '24px', height: '24px',
                borderRadius: '12px',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}
            >
              <CloseX />
            </button>
          ) : (
            <ChevR />
          )}
        </div>

        {/* Expanded content — body copy + Talk-to button. Hidden when
           collapsed via the parent's maxHeight. */}
        {expanded ? (
          <div style={{
            paddingLeft: '14px',
            paddingRight: '14px',
            paddingBottom: '14px',
            display: 'flex',
            flexDirection: 'column',
            gap: '12px',
          }}>
            <span style={{
              fontFamily: 'Inter',
              fontWeight: 400,
              fontSize: '12px',
              lineHeight: '17px',
              color: colors.muted,
            }}>{copy.body}</span>
            <button
              onClick={handleTalk}
              style={{
                border: 'none',
                background: 'linear-gradient(135deg, #0E1420 0%, #003E3C 50%, #00AFAB 100%)',
                cursor: 'pointer',
                padding: 0,
                margin: 0,
                height: '40px',
                borderRadius: '10px',
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                gap: '6px',
                /* Use a single shared row baseline for all three children.
                   Each child is wrapped in an inline-flex span with the
                   same line-height:1 + display height so flex centring
                   lines them up by their own visual centre rather than
                   by the differing line-boxes of the underlying glyphs. */
              }}
            >
              <span style={{
                fontFamily: 'Gilroy',
                fontWeight: 600,
                fontSize: '13px',
                lineHeight: 1,
                color: '#fff',
              }}>Talk to</span>
              {/* Inner lockup — wordmark + plus align ONLY to each other,
                 decoupled from the "Talk to" baseline so the plus's
                 cross-point sits exactly on the wordmark's letter
                 midline regardless of where "Talk to" lands. */}
              <span style={{
                display: 'inline-flex',
                flexDirection: 'row',
                alignItems: 'center',
                gap: '4px',
              }}>
                {Wordmark ? (
                  <Wordmark width={56} height={18} color="#fff" />
                ) : (
                  <span style={{
                    fontFamily: 'Gilroy',
                    fontWeight: 800,
                    fontSize: '14px',
                    lineHeight: 1,
                    color: '#fff',
                  }}>equiti</span>
                )}
                <span style={{
                  fontFamily: 'Gilroy',
                  fontWeight: 800,
                  fontSize: '23px',
                  lineHeight: '23px',
                  color: '#7FFFFA',
                  textShadow: '0 0 6px rgba(0,175,171,0.7), 0 0 12px rgba(0,175,171,0.45)',
                }}>+</span>
              </span>
            </button>
          </div>
        ) : null}
      </div>
    </div>
  );
};

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