// Global interactivity layer — toasts, modals, smart click handler

// ============ TOAST SYSTEM ============
const __toastListeners = new Set();
let __toastId = 0;
const toast = (msg, kind = 'ok', sub = '') => {
  const id = ++__toastId;
  __toastListeners.forEach(fn => fn({ type: 'add', toast: { id, msg, kind, sub, t: Date.now() } }));
  setTimeout(() => {
    __toastListeners.forEach(fn => fn({ type: 'remove', id }));
  }, 4200);
};
window.toast = toast;

function ToastStack() {
  const [toasts, setToasts] = React.useState([]);
  React.useEffect(() => {
    const handler = (ev) => {
      if (ev.type === 'add') setToasts(ts => [...ts, ev.toast]);
      else if (ev.type === 'remove') setToasts(ts => ts.filter(t => t.id !== ev.id));
    };
    __toastListeners.add(handler);
    return () => __toastListeners.delete(handler);
  }, []);
  return (
    <div style={{
      position: 'fixed', bottom: 36, right: 20,
      display: 'flex', flexDirection: 'column',
      gap: 8, zIndex: 200,
      pointerEvents: 'none',
    }}>
      {toasts.map(t => {
        const color = t.kind === 'err' ? 'var(--danger)' : t.kind === 'warn' ? 'var(--warn)' : t.kind === 'info' ? 'var(--cyan)' : 'var(--good)';
        const Icn = t.kind === 'err' ? Icon.X : t.kind === 'warn' ? Icon.Bell : Icon.Check;
        return (
          <div key={t.id} style={{
            minWidth: 280, maxWidth: 380,
            padding: '12px 16px',
            background: 'rgba(10, 13, 34, 0.92)',
            border: `1px solid ${color}40`,
            borderLeft: `2px solid ${color}`,
            borderRadius: 'var(--radius-lg)',
            display: 'flex', alignItems: 'flex-start', gap: 10,
            boxShadow: '0 12px 40px rgba(0, 0, 0, 0.5)',
            backdropFilter: 'blur(20px)',
            animation: 'slide-in 0.18s ease-out',
            pointerEvents: 'auto',
          }}>
            <Icn style={{ width: 14, height: 14, color, marginTop: 2, flexShrink: 0 }}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, color: 'var(--text)' }}>{t.msg}</div>
              {t.sub && <div className="mono faint" style={{ fontSize: 10, marginTop: 2 }}>{t.sub}</div>}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ============ MODAL SYSTEM ============
const __modalListeners = new Set();
const openModal = (config) => {
  __modalListeners.forEach(fn => fn(config));
};
const closeModal = () => {
  __modalListeners.forEach(fn => fn(null));
};
window.openModal = openModal;
window.closeModal = closeModal;

function ModalHost() {
  const [modal, setModal] = React.useState(null);
  React.useEffect(() => {
    const handler = (config) => setModal(config);
    __modalListeners.add(handler);
    return () => __modalListeners.delete(handler);
  }, []);
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape' && modal) closeModal();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [modal]);

  if (!modal) return null;

  return (
    <div style={{
      position: 'fixed', inset: 0,
      background: 'rgba(3, 4, 12, 0.7)',
      backdropFilter: 'blur(8px)',
      zIndex: 150,
      display: 'grid', placeItems: 'center',
      animation: 'fade-in 0.15s',
    }} onClick={closeModal}>
      <div onClick={e => e.stopPropagation()} style={{
        width: modal.width || 560,
        maxWidth: '90vw',
        maxHeight: '85vh',
        background: 'rgba(10, 13, 34, 0.96)',
        border: '1px solid rgba(139, 107, 255, 0.3)',
        borderRadius: 'var(--radius-lg)',
        boxShadow: '0 24px 80px rgba(0, 0, 0, 0.6), 0 0 80px rgba(139, 107, 255, 0.15)',
        backdropFilter: 'blur(40px)',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
        animation: 'slide-in 0.2s',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'flex-start', gap: 14 }}>
          {modal.icon && (
            <div style={{
              width: 38, height: 38, borderRadius: 10,
              background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.25), rgba(75, 232, 255, 0.15))',
              border: '1px solid rgba(139, 107, 255, 0.3)',
              display: 'grid', placeItems: 'center', flexShrink: 0,
            }}>
              {React.createElement(Icon[modal.icon] || Icon.Sparkles, { style: { width: 16, height: 16, color: 'var(--cyan)' }})}
            </div>
          )}
          <div style={{ flex: 1 }}>
            <h2 className="serif" style={{ margin: 0, fontSize: 22, fontStyle: 'italic', fontWeight: 400 }}>{modal.title}</h2>
            {modal.subtitle && <div className="dim" style={{ fontSize: 12, marginTop: 4 }}>{modal.subtitle}</div>}
          </div>
          <button className="icon-btn" onClick={closeModal}><Icon.X/></button>
        </div>
        <div style={{ padding: 24, overflowY: 'auto', flex: 1 }}>
          {modal.body}
        </div>
        {modal.footer && (
          <div style={{ padding: '16px 24px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
            {modal.footer}
          </div>
        )}
      </div>
    </div>
  );
}

// ============ SMART CLICK HANDLER ============
// Catches button clicks that don't have explicit handlers and responds intelligently.
function smartClickHandler(e) {
  const btn = e.target.closest('button');
  if (!btn) return;
  // Skip if React handler attached (we can't reliably detect — use a marker instead)
  if (btn.dataset.handled === '1') return;
  // Skip if it's a tab / nav-style button (let parent handle)
  if (btn.closest('.segmented') || btn.closest('.nav-item') || btn.closest('.cmdk-item') || btn.closest('.twk-panel')) return;
  // Skip if it's an icon-only chevron / close button
  if (!btn.textContent.trim() && btn.children.length === 1) return;

  const rawTxt = btn.textContent.trim();
  const txt = rawTxt.toLowerCase();

  // 1. data-action attribute → run that action explicitly
  if (btn.dataset.action && window.runAction?.(btn.dataset.action)) return;

  // 2. button text → registered action (Launch Campaign, Run AI Audit, etc.)
  const k = window.actionForText?.(txt);
  if (k && window.runAction?.(k)) return;
  // Match common verbs and respond
  const responses = [
    // Affirmative actions → success toast
    { match: /^send proposal/, msg: 'Proposal sent', sub: 'Recipient will receive email + signature link · audit logged', kind: 'ok' },
    { match: /^send (broadcast|message|email|as-is)/, msg: 'Sent', sub: 'Delivered · tracking enabled', kind: 'ok' },
    { match: /^send$/, msg: 'Sent', sub: 'Audit logged', kind: 'ok' },
    { match: /^deploy operator/, msg: 'New operator deploying…', sub: 'Provisioning compute · indexing knowledge corpus', kind: 'info' },
    { match: /^deploy(\b|$)/, msg: 'Deployment started', sub: 'Will be live in ~30s · check Mission Control', kind: 'info' },
    { match: /^promote/, msg: 'Promoted to all founders segment', sub: 'Calliope rolling out within 2 minutes', kind: 'ok' },
    { match: /^approve/, msg: 'Approved', sub: 'Agent action greenlit · executing now', kind: 'ok' },
    { match: /^reject/, msg: 'Rejected', sub: 'Agent will re-draft within 60 seconds', kind: 'warn' },
    { match: /^pause all/, msg: 'All operators paused', sub: 'Queue preserved · resume any time', kind: 'warn' },
    { match: /^pause operator/, msg: 'Operator paused', sub: 'Queue preserved · resume from Agents', kind: 'warn' },
    { match: /^pause this business/, msg: 'Business paused', sub: 'Billing on hold · data preserved', kind: 'warn' },
    { match: /^pause(\b|$)/, msg: 'Paused', sub: 'Resume when ready', kind: 'warn' },
    { match: /^resume operator/, msg: 'Operator resumed', sub: 'Picking up where it left off', kind: 'ok' },
    { match: /^resume(\b|$)/, msg: 'Resumed', sub: 'Back in flight', kind: 'ok' },
    { match: /^emergency stop/, msg: 'EMERGENCY STOP', sub: 'All agents halted · queue frozen · paged on-call', kind: 'err' },
    { match: /^configure(\b|$)/, msg: 'Opening configuration…', sub: 'Edit playbook, budget, ICP, escalation rules', kind: 'info' },
    { match: /^manage(\b|$)/, msg: 'Opening integration manager…', sub: 'Adjust scopes, sync schedule, webhook URLs', kind: 'info' },
    { match: /^fix(\b|$)/, msg: 'Running diagnostics…', sub: 'Detecting root cause · auto-remediation pending', kind: 'info' },
    { match: /^connect(\b|$)/, msg: 'Connecting…', sub: 'OAuth in new tab · approve permissions to finish', kind: 'info' },
    { match: /^disconnect(\b|$)/, msg: 'Disconnected', sub: 'Webhooks paused · data retained for 30 days', kind: 'warn' },
    { match: /^install/, msg: 'Installing MCP server…', sub: 'Verifying schema · scoping permissions', kind: 'info' },
    { match: /^save/, msg: 'Saved', sub: 'Changes synced across operators', kind: 'ok' },
    { match: /^download/, msg: 'Download started', sub: 'Invoice PDF in your downloads', kind: 'ok' },
    { match: /^upload/, msg: 'Upload ready', sub: 'Drop files in the panel below', kind: 'info' },
    { match: /^export/, msg: 'Export queued', sub: 'You will receive an email when ready', kind: 'info' },
    { match: /^import/, msg: 'Import started', sub: 'Mapping fields · validating rows', kind: 'info' },
    { match: /^upgrade/, msg: 'Plan change initiated', sub: 'Stripe checkout will open shortly', kind: 'info' },
    { match: /^generate/, msg: 'Generating…', sub: 'Output ready in ~8s', kind: 'info' },
    { match: /^regenerate/, msg: 'Regenerating…', sub: 'New variation incoming', kind: 'info' },
    { match: /^edit/, msg: 'Edit mode', sub: 'Make changes and save when ready', kind: 'info' },
    { match: /^retrain/, msg: 'Retraining clone…', sub: 'Recalibrating voice fingerprint · 2-4 min', kind: 'info' },
    { match: /^preview/, msg: 'Playing preview…', sub: 'Audio sample · 8 seconds', kind: 'info' },
    { match: /^sync/, msg: 'Syncing…', sub: 'Pulling latest from all connected systems', kind: 'info' },
    { match: /^refresh/, msg: 'Refreshed', sub: 'Data is current as of now', kind: 'ok' },
    { match: /^launch/, msg: 'Launching…', sub: 'Workflow active in seconds', kind: 'info' },
    { match: /^new automation/, msg: 'New automation wizard', sub: 'Opening workflow canvas with a blank trigger', kind: 'info' },
    { match: /^new workflow/, msg: 'New workflow created', sub: 'Opening canvas · drag a trigger to start', kind: 'info' },
    { match: /^new campaign/, msg: 'New campaign drafted', sub: 'Pick a channel and audience to continue', kind: 'info' },
    { match: /^new funnel/, msg: 'New funnel created', sub: 'Define your first step', kind: 'info' },
    { match: /^new key/, msg: 'API key generated', sub: 'Copy now — shown once', kind: 'ok' },
    { match: /^new(\b|$)/, msg: 'Created', sub: 'New item ready to configure', kind: 'info' },
    { match: /^add (contact|business|tattoo|product)/, msg: 'Added', sub: 'Saved to your workspace', kind: 'ok' },
    { match: /^add/, msg: 'Added', sub: '', kind: 'ok' },
    { match: /^invite/, msg: 'Invitation sent', sub: 'They will receive an email with a workspace link', kind: 'ok' },
    { match: /^review/, msg: 'Opening review…', sub: 'See diff and approve', kind: 'info' },
    { match: /^transfer/, msg: 'Transfer initiated', sub: 'Requires receiving partner to accept', kind: 'info' },
    { match: /^delete/, msg: 'Deletion scheduled', sub: 'Will be permanent in 7 days · cancel any time', kind: 'err' },
    { match: /^remove/, msg: 'Removed', sub: 'Restore from settings within 30 days', kind: 'warn' },
    { match: /^decommission/, msg: 'Operator decommissioned', sub: 'Memory + playbook archived', kind: 'warn' },
    { match: /^enable preview/, msg: 'Preview enabled', sub: 'Customer-facing route now active', kind: 'ok' },
    { match: /^accept/, msg: 'Accepted', sub: 'Setup fee charged · live in 60 seconds', kind: 'ok' },
    { match: /^view all/, msg: 'Opening list…', sub: '', kind: 'info' },
    { match: /^view invoices/, msg: 'Opening invoices…', sub: '', kind: 'info' },
    { match: /^view diagnostics/, msg: 'Diagnostics open', sub: 'See traces, prompts, tool calls', kind: 'info' },
    { match: /^show diagnostics/, msg: 'Diagnostics open', sub: '', kind: 'info' },
    { match: /^suggest replacement/, msg: 'Finding alternatives…', sub: 'Demiurge scanning your sequence library', kind: 'info' },
    { match: /^test/, msg: 'Test running', sub: 'Results in seconds', kind: 'info' },
    { match: /^promote post|^publish/, msg: 'Published', sub: 'Live on selected channels', kind: 'ok' },
    { match: /^email owner/, msg: 'Email drafted', sub: 'Your default editor will open', kind: 'info' },
    { match: /^discard/, msg: 'Discarded', sub: 'Draft removed', kind: 'warn' },
    { match: /^snooze/, msg: 'Snoozed', sub: 'Hidden for 24h', kind: 'info' },
    { match: /^take over/, msg: 'You\'re driving', sub: 'Agent stepped back · your turn', kind: 'info' },
    { match: /^book meeting/, msg: 'Calendar opened', sub: 'Pick a slot · contact will be notified', kind: 'info' },
    { match: /^add to sequence/, msg: 'Added to sequence', sub: 'Calliope will begin within 4 hours', kind: 'ok' },
    { match: /^schedule/, msg: 'Scheduled', sub: 'Will run at the time you specified', kind: 'ok' },
    { match: /^submit/, msg: 'Submitted', sub: 'Demiurge team will review within 24h', kind: 'ok' },
    { match: /^adjust/, msg: 'Adjusting…', sub: 'New values applied', kind: 'info' },
    { match: /^apply/, msg: 'Applied', sub: 'Changes live now', kind: 'ok' },
    { match: /^copy/, msg: 'Copied to clipboard', sub: '', kind: 'ok' },
    { match: /^open ai receptionist/, msg: 'Opening AI Receptionist…', sub: 'Switching to phone agent config', kind: 'info' },
    { match: /^open playbook/, msg: 'Playbook opened', sub: 'See decisions, guardrails, routing', kind: 'info' },
    { match: /^open funnel/, msg: 'Opening funnel…', sub: '', kind: 'info' },
    { match: /^open/, msg: 'Opening…', sub: '', kind: 'info' },
    { match: /^filter/, msg: 'Filter applied', sub: '', kind: 'info' },
    { match: /^segment/, msg: 'Segment created', sub: 'Audience built · use anywhere', kind: 'ok' },
    { match: /^request integration/, msg: 'Request submitted', sub: 'Demiurge engineering team will reach out', kind: 'ok' },
    { match: /^from template/, msg: 'Picking template…', sub: 'Browse library to choose', kind: 'info' },
    { match: /^contact support/, msg: 'Opening support…', sub: '', kind: 'info' },
    { match: /^all businesses/, msg: 'Back to businesses', sub: '', kind: 'info' },
    { match: /^widen daily cap/, msg: 'Cap widened · Atlas +200/day', sub: 'Effective immediately', kind: 'ok' },
  ];

  for (const r of responses) {
    if (r.match.test(txt)) {
      toast(r.msg, r.kind, r.sub);
      return;
    }
  }
  // Default fallback for any button we didn't match
  if (txt && txt.length > 0 && txt.length < 60) {
    toast('Action queued', 'info', `"${btn.textContent.trim()}"`);
  }
}

window.smartClickHandler = smartClickHandler;
window.ToastStack = ToastStack;
window.ModalHost = ModalHost;
