// Reusable Opsmera AI affordances used across the whole app, so wherever the
// user sees something due, the system tells them what to do about it - grounded
// in this site's history. Two forms:
//   <AiStrip>  - compact inline row (deadlines, job cards, table rows)
//   <AiBlock>  - larger panel for detail views
// Both share the violet "AI" treatment and always show the historical BASIS.

// Route a label like "Open building" / "View job" to navigation; otherwise toast.
function runAiAction(label, icon) {
  const l = (label || '').toLowerCase();
  const navMap = [
    [/build|portfolio|scheme/, 'portfolio'], [/invoice|payment|approve/, 'invoices'],
    [/job|work order/, 'board'], [/meeting|agm|motion|vote/, 'meetings'],
    [/intake|thread|reply|message|update/, 'intake'], [/complian|cert|afss|logbook|pack/, 'compliance'],
  ];
  if (/^(open|view|go to|see)\b/.test(l) && window.opsNav) {
    for (const [re, dest] of navMap) { if (re.test(l)) { window.opsNav(dest); return; } }
  }
  if (window.opsToast) window.opsToast(label, { kind: 'auto', icon: icon || 'sparkles', sub: 'Opsmera AI is on it — you’ll get a confirmation.' });
}

// compact inline suggestion: ✦ do … (Based on: basis) [action]
function AiStrip({ tip, dense }) {
  if (!tip) return null;
  return (
    <div className={`ai-strip ${dense ? 'dense' : ''}`}>
      <span className="ai-spark"><Icon name="sparkles" /></span>
      <div className="ai-strip-body">
        <div className="ai-do"><span className="ai-tag">Do</span>{tip.do}</div>
        {tip.basis && <div className="ai-basis"><span className="ai-basis-k">Based on</span>{tip.basis}</div>}
      </div>
      {tip.action && <button className="ai-act" onClick={e => { e.stopPropagation(); runAiAction(tip.action); }}>{tip.action}<Icon name="arrow-right" /></button>}
    </div>
  );
}

// larger panel version (detail panes)
function AiBlock({ title, body, basis, actions }) {
  return (
    <div className="ai-card">
      <div className="hd"><Icon name="sparkles" />{title || 'Opsmera AI · recommendation'}</div>
      {body && <p>{body}</p>}
      {basis && <div className="ai-card-basis"><Icon name="history" /><span><b>Based on history:</b> {basis}</span></div>}
      {actions && actions.length > 0 && (
        <div className="ai-card-acts">
          {actions.map(([label, icon], i) => (
            <button key={i} className={`btn ${i === 0 ? 'btn-primary' : 'btn-ghost'} btn-sm`} onClick={() => runAiAction(label, icon)}><Icon name={icon} />{label}</button>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AiStrip, AiBlock, runAiAction });
