/* ══ OM Group ERP — Analysis Studio · shell ═══════════════════════════════
   The second workspace of the Analytics module. It shares the Intelligence
   Center's ctx verbatim — same period, same comparison, same cross-filters,
   same live Store subscription — so switching workspaces never re-queries
   or re-copies anything. Panels are mounted on demand and unmounted on
   leave, which keeps the heavy panels off the critical path.             */
const { useState: stuSt, useMemo: stuMemo, useEffect: stuEf } = React;

const STU_TABS = [
  { id: 'canvas', label: 'Canvas', icon: 'ruler', hint: 'Draw on the live series' },
  { id: 'sim', label: 'Simulator', icon: 'calculator', hint: 'Test an assumption' },
  { id: 'forecast', label: 'Forecast Lab', icon: 'telescope', hint: 'Every model, explained' },
  { id: 'drivers', label: 'Drivers', icon: 'steering', hint: 'What changed, and who' },
  { id: 'opps', label: 'Opportunities', icon: 'trendUp', hint: 'Value left on the table' },
  { id: 'risks', label: 'Risks', icon: 'shield', hint: 'Where we are exposed' },
  { id: 'corr', label: 'Correlations', icon: 'nodes', hint: 'What moves with what' },
  { id: 'brief', label: 'Briefing', icon: 'doc', hint: 'Read it as a report' },
];

function AnalysisStudio({ ctx }) {
  const DEng = window.DecisionEngine;
  const [tab, setTab] = stuSt(() => localStorage.getItem('omStudioTab') || 'canvas');
  const [canvas, setCanvas] = stuSt({ draws: [], metric: null, active: null });
  const patchCanvas = p => setCanvas(c => Object.assign({}, c, p));
  stuEf(() => { localStorage.setItem('omStudioTab', tab); }, [tab]);

  const counts = stuMemo(() => {
    let op = [], rk = [];
    try { op = DEng.opportunities(ctx); } catch (e) { }
    try { rk = DEng.risks(ctx); } catch (e) { }
    return { opps: op.length, risks: rk.length, oppValue: op.reduce((s, o) => s + o.value, 0), rkList: rk };
  }, [ctx]);

  const alerts = stuMemo(() => DEng.alerts(ctx, counts.rkList), [ctx, counts]);

  const panel = stuMemo(() => {
    switch (tab) {
      case 'canvas': return <window.StudioCanvas ctx={ctx} store={canvas} onStore={patchCanvas} />;
      case 'sim': return <window.StudioSimulator ctx={ctx} />;
      case 'forecast': return <window.StudioForecast ctx={ctx} />;
      case 'drivers': return <window.StudioDrivers ctx={ctx} />;
      case 'opps': return <window.StudioOpportunities ctx={ctx} />;
      case 'risks': return <window.StudioRisks ctx={ctx} />;
      case 'corr': return <window.StudioCorrelation ctx={ctx} />;
      case 'brief': return <window.StudioBriefing ctx={ctx} />;
      default: return null;
    }
  }, [tab, ctx, canvas]);

  const cur = STU_TABS.find(t => t.id === tab) || STU_TABS[0];

  return (
    <div>
      {alerts.length > 0 && (
        <div className="st-alerts" style={{ marginTop: 4 }}>
          {alerts.map((a, i) => (
            <div className="st-alert" key={i} style={{ '--ac': a.kind === 'opportunity' ? '#16A34A' : a.kind === 'action' ? '#F97316' : '#DC2626', animationDelay: (i * 60) + 'ms' }}>
              <span className="st-alert-i">{window.OMIcon ? <window.OMIcon name={a.kind === 'opportunity' ? 'trendUp' : a.kind === 'action' ? 'bulb' : 'warn'} size={13} /> : null}</span>
              <div className="st-alert-txt"><b>{a.title}</b><span>{a.detail}</span></div>
            </div>
          ))}
        </div>
      )}

      <div className="st-rail" role="tablist">
        {STU_TABS.map(t => (
          <button key={t.id} className={tab === t.id ? 'on' : ''} role="tab" aria-selected={tab === t.id} onClick={() => setTab(t.id)} title={t.hint}>
            {window.OMIcon ? <window.OMIcon name={t.icon} size={14} /> : <i></i>}{t.label}
            {t.id === 'opps' && counts.opps > 0 && <b>{counts.opps}</b>}
            {t.id === 'risks' && counts.risks > 0 && <b>{counts.risks}</b>}
          </button>
        ))}
      </div>

      <div className="st-body" key={tab}>{panel}</div>
    </div>
  );
}

/* ── workspace switch used by the Intelligence Center hero ─────────────── */
function IWorkspaceSwitch({ value, onChange }) {
  const T = [
    { id: 'intel', label: 'Intelligence', icon: 'brain' },
    { id: 'studio', label: 'Analysis Studio', icon: 'compass' },
  ];
  return (
    <div className="i-ws" role="tablist">
      {T.map(t => (
        <button key={t.id} className={value === t.id ? 'on' : ''} role="tab" aria-selected={value === t.id} onClick={() => onChange(t.id)}>
          {window.OMIcon ? <window.OMIcon name={t.icon} size={13} /> : null}
          {t.label}
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { AnalysisStudio, IWorkspaceSwitch, STU_TABS });
