// Ticket detail header actions: Assign, Escalate, Retry strategy, Audit PDF, overflow
const { useState: useStateTA, useEffect: useEffectTA, useRef: useRefTA } = React;

// ---------- Popover shell ----------
const Popover = ({ open, onClose, anchor, children, width = 320 }) => {
  const ref = useRefTA(null);
  useEffectTA(() => {
    if (!open) return;
    const handle = (e) => {
      if (ref.current && !ref.current.contains(e.target) && !anchor?.contains?.(e.target)) onClose();
    };
    document.addEventListener('mousedown', handle);
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', esc);
    return () => { document.removeEventListener('mousedown', handle); document.removeEventListener('keydown', esc); };
  }, [open, onClose, anchor]);
  if (!open || !anchor) return null;
  const rect = anchor.getBoundingClientRect();
  return (
    <div ref={ref} style={{
      position: 'fixed', top: rect.bottom + 6, left: rect.left, width,
      background: 'white', borderRadius: 12, border: '1px solid var(--border)',
      boxShadow: 'var(--shadow-lg)', zIndex: 90, animation: 'popIn 140ms ease',
      overflow: 'hidden',
    }}>
      {children}
      <style>{`@keyframes popIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }`}</style>
    </div>
  );
};

// ---------- Toast ----------
const Toast = ({ open, text, subtext, onClose }) => {
  useEffectTA(() => {
    if (!open) return;
    const t = setTimeout(onClose, 3500);
    return () => clearTimeout(t);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 20, left: '50%', transform: 'translateX(-50%)',
      zIndex: 200, background: 'var(--nyu-deep-purple)', color: 'white',
      padding: '12px 18px', borderRadius: 12, boxShadow: 'var(--shadow-lg)',
      display: 'flex', alignItems: 'center', gap: 10, fontSize: 13,
      animation: 'toastIn 200ms ease', maxWidth: 520,
    }}>
      <div style={{width: 24, height: 24, borderRadius: '50%', background: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
        <Icon name="check" size={12} color="white" strokeWidth={3}/>
      </div>
      <div style={{flex: 1}}>
        <div style={{fontWeight: 600}}>{text}</div>
        {subtext && <div style={{fontSize: 11, opacity: 0.8, marginTop: 2}}>{subtext}</div>}
      </div>
      <button onClick={onClose} style={{background: 'transparent', border: 'none', color: 'white', cursor: 'pointer', opacity: 0.6, padding: 0}}>
        <Icon name="x" size={14} color="white"/>
      </button>
      <style>{`@keyframes toastIn { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } }`}</style>
    </div>
  );
};

// ---------- Main action bar ----------
const TicketActionBar = ({ ticket, onOpenAudit }) => {
  const [assignedTo, setAssignedTo] = useStateTA('violet'); // 'violet' | 'me'
  const [escOpen, setEscOpen] = useStateTA(false);
  const [retryOpen, setRetryOpen] = useStateTA(false);
  const [moreOpen, setMoreOpen] = useStateTA(false);
  const [toast, setToast] = useStateTA(null);

  const escRef = useRefTA(null);
  const retryRef = useRefTA(null);
  const moreRef = useRefTA(null);

  // Escalate state
  const [escTarget, setEscTarget] = useStateTA('L2');
  const [escNote, setEscNote] = useStateTA('');

  // Retry state
  const [retryMode, setRetryMode] = useStateTA('scratch');

  const assignToMe = () => {
    if (assignedTo === 'me') { setAssignedTo('violet'); setToast({ text: 'Re-assigned to Violet', subtext: 'Agent will resume where it left off' }); return; }
    setAssignedTo('me');
    setToast({ text: 'Assigned to a.kotler', subtext: 'Violet paused · you own this ticket' });
  };

  const confirmEscalate = () => {
    setEscOpen(false);
    const queueName = { L2: 'Human Tier 2', SOC: 'Security SOC', EPIC: 'Epic Help Desk' }[escTarget];
    setToast({ text: `Escalated to ${queueName}`, subtext: `ETA: 4m · context + audit packet attached` });
  };

  const confirmRetry = () => {
    setRetryOpen(false);
    const label = { scratch: 'From scratch', lastGood: 'From last known-good step', runbook: 'With different runbook' }[retryMode];
    setToast({ text: `Retry queued · ${label}`, subtext: 'Violet re-planning with new constraints' });
  };

  return (
    <>
      <div style={{display: 'flex', gap: 8, flexWrap: 'wrap'}}>
        <button
          className={assignedTo === 'me' ? 'btn btn-secondary btn-sm' : 'btn btn-primary btn-sm'}
          onClick={assignToMe}
          style={assignedTo === 'me' ? {background: 'var(--mint-tint)', color: '#006B51', borderColor: '#8FD9B8'} : {}}>
          {assignedTo === 'me' ? <><Icon name="check" size={13} color="#006B51" strokeWidth={3}/> Assigned to you</> : <><Icon name="user" size={13}/> Assign to me</>}
        </button>
        <button ref={escRef} className="btn btn-secondary btn-sm" onClick={() => { setEscOpen(o => !o); setRetryOpen(false); setMoreOpen(false); }}>
          <Icon name="route" size={13}/> Escalate
        </button>
        <button ref={retryRef} className="btn btn-secondary btn-sm" onClick={() => { setRetryOpen(o => !o); setEscOpen(false); setMoreOpen(false); }}>
          <Icon name="refresh" size={13}/> Retry strategy
        </button>
        <button className="btn btn-secondary btn-sm" onClick={onOpenAudit}>
          <Icon name="download" size={13}/> Audit PDF
        </button>
        <button ref={moreRef} className="btn btn-ghost btn-sm" onClick={() => { setMoreOpen(o => !o); setEscOpen(false); setRetryOpen(false); }} style={{marginLeft: 'auto'}}>
          <Icon name="ellipsis" size={14}/>
        </button>
      </div>

      {/* Escalate popover */}
      <Popover open={escOpen} onClose={() => setEscOpen(false)} anchor={escRef.current} width={360}>
        <div style={{padding: '14px 16px 10px'}}>
          <div style={{fontSize: 13, fontWeight: 700, marginBottom: 2}}>Escalate to human queue</div>
          <div style={{fontSize: 11, color: 'var(--nyu-text)'}}>Violet will hand off the full context packet</div>
        </div>
        <div style={{padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: 6}}>
          {[
            { id: 'L2', label: 'Human Tier 2', sub: '3 techs online · avg 4m', icon: 'user' },
            { id: 'SOC', label: 'Security SOC', sub: 'On-call rotation · 24/7', icon: 'shield' },
            { id: 'EPIC', label: 'Epic Help Desk', sub: 'Mon–Fri 06:00–22:00', icon: 'route' },
          ].map(opt => (
            <button
              key={opt.id}
              onClick={() => setEscTarget(opt.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 12px', borderRadius: 8, cursor: 'pointer', textAlign: 'left',
                background: escTarget === opt.id ? 'var(--purple-tint)' : 'white',
                border: escTarget === opt.id ? '1px solid var(--nyu-purple)' : '1px solid var(--border)',
                width: '100%',
              }}>
              <div style={{
                width: 28, height: 28, borderRadius: 8,
                background: escTarget === opt.id ? 'var(--nyu-purple)' : 'var(--nyu-gray-50)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name={opt.icon} size={14} color={escTarget === opt.id ? 'white' : 'var(--nyu-text)'}/>
              </div>
              <div style={{flex: 1}}>
                <div style={{fontSize: 12, fontWeight: 600}}>{opt.label}</div>
                <div style={{fontSize: 11, color: 'var(--nyu-text)'}}>{opt.sub}</div>
              </div>
              {escTarget === opt.id && <Icon name="check" size={12} color="var(--nyu-purple)" strokeWidth={3}/>}
            </button>
          ))}
        </div>
        <div style={{padding: '0 12px 12px'}}>
          <textarea
            placeholder="Optional note for the receiving queue..."
            value={escNote}
            onChange={e => setEscNote(e.target.value)}
            style={{
              width: '100%', minHeight: 54, resize: 'vertical',
              padding: 8, fontSize: 12, border: '1px solid var(--border)',
              borderRadius: 8, fontFamily: 'inherit', outline: 'none',
            }}
          />
        </div>
        <div style={{padding: '10px 14px', borderTop: '1px solid var(--border)', display: 'flex', gap: 8, background: 'var(--nyu-gray-50)'}}>
          <button className="btn btn-ghost btn-sm" onClick={() => setEscOpen(false)} style={{flex: 1}}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={confirmEscalate} style={{flex: 1}}>Escalate <Icon name="arrow" size={12}/></button>
        </div>
      </Popover>

      {/* Retry strategy popover */}
      <Popover open={retryOpen} onClose={() => setRetryOpen(false)} anchor={retryRef.current} width={360}>
        <div style={{padding: '14px 16px 10px'}}>
          <div style={{fontSize: 13, fontWeight: 700, marginBottom: 2}}>Retry strategy</div>
          <div style={{fontSize: 11, color: 'var(--nyu-text)'}}>Violet will re-plan from your chosen start point</div>
        </div>
        <div style={{padding: '0 12px 12px', display: 'flex', flexDirection: 'column', gap: 6}}>
          {[
            { id: 'scratch', label: 'From scratch', sub: 'Discard current plan · re-gather context' },
            { id: 'lastGood', label: 'From last known-good step', sub: 'Resume at step 2 (suspend_account ✓)' },
            { id: 'runbook', label: 'With different runbook', sub: 'Switch: Lost device → Lost device + PHI' },
          ].map(opt => (
            <button
              key={opt.id}
              onClick={() => setRetryMode(opt.id)}
              style={{
                padding: '10px 12px', borderRadius: 8, cursor: 'pointer', textAlign: 'left',
                background: retryMode === opt.id ? 'var(--purple-tint)' : 'white',
                border: retryMode === opt.id ? '1px solid var(--nyu-purple)' : '1px solid var(--border)',
                width: '100%',
              }}>
              <div style={{display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, fontWeight: 600, marginBottom: 2}}>
                <div style={{
                  width: 14, height: 14, borderRadius: '50%',
                  border: retryMode === opt.id ? '4px solid var(--nyu-purple)' : '2px solid var(--nyu-gray-200)',
                  background: 'white', flexShrink: 0,
                }}/>
                {opt.label}
              </div>
              <div style={{fontSize: 11, color: 'var(--nyu-text)', marginLeft: 22}}>{opt.sub}</div>
            </button>
          ))}
        </div>
        <div style={{padding: '10px 14px', borderTop: '1px solid var(--border)', display: 'flex', gap: 8, background: 'var(--nyu-gray-50)'}}>
          <button className="btn btn-ghost btn-sm" onClick={() => setRetryOpen(false)} style={{flex: 1}}>Cancel</button>
          <button className="btn btn-primary btn-sm" onClick={confirmRetry} style={{flex: 1}}><Icon name="refresh" size={12}/> Queue retry</button>
        </div>
      </Popover>

      {/* More overflow menu */}
      <Popover open={moreOpen} onClose={() => setMoreOpen(false)} anchor={moreRef.current} width={260}>
        <div style={{padding: 6}}>
          {[
            { icon: 'link', label: 'Copy ticket link', sub: `INC-${ticket.id.slice(-5)}`, action: () => setToast({ text: 'Link copied', subtext: 'Paste anywhere to jump back to this ticket' }) },
            { icon: 'code', label: 'View raw events', sub: 'JSON event stream', action: () => setToast({ text: 'Opening raw event stream...', subtext: '42 events since ticket opened' }) },
            { icon: 'alert', label: 'Mark as false-positive', sub: 'Feedback → Violet retraining', action: () => setToast({ text: 'Flagged as false-positive', subtext: 'Signal added to next training batch' }) },
            { icon: 'sparkle', label: 'Add to training set', sub: 'Improves future resolution', action: () => setToast({ text: 'Added to training set', subtext: '1,247 examples in current batch' }) },
            { icon: 'bell', label: 'Subscribe to updates', sub: 'Ping on state change', action: () => setToast({ text: 'Subscribed', subtext: 'Teams notification when ticket closes' }) },
          ].map((item, i) => (
            <button key={i}
              onClick={() => { item.action(); setMoreOpen(false); }}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px', borderRadius: 8, cursor: 'pointer', textAlign: 'left',
                background: 'transparent', border: 'none', width: '100%',
                transition: 'background 80ms',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--nyu-gray-50)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{width: 24, height: 24, borderRadius: 6, background: 'var(--purple-tint)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0}}>
                <Icon name={item.icon} size={12} color="var(--nyu-purple)"/>
              </div>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 12, fontWeight: 600}}>{item.label}</div>
                <div style={{fontSize: 10, color: 'var(--nyu-text)'}}>{item.sub}</div>
              </div>
            </button>
          ))}
        </div>
      </Popover>

      <Toast open={!!toast} text={toast?.text} subtext={toast?.subtext} onClose={() => setToast(null)}/>
    </>
  );
};

Object.assign(window, { TicketActionBar });
