/* ============================================================
   IMTRACK — Action Cockpit
   Surfaces generated Cockpit Action Items by category.
   Each card surfaces generated action rows; all thresholds
   read from cockpitActionsConfig + alertConfig in the store.
   ============================================================ */
(function () {
  const E = window.IMTRACK_ENGINE;
  const { useState, useMemo } = React;

  const SEV_ORDER = { critical: 0, warning: 1, flag: 2 };

  function SevDot({ sev, size }) {
    const sz = size || 8;
    const colors = { critical: '#b45309', warning: '#d97706', flag: '#7c3aed' };
    return (
      <span style={{
        display: 'inline-block', width: sz, height: sz, borderRadius: '50%',
        background: colors[sev] || '#94a3b8', flexShrink: 0,
      }} />
    );
  }

  function SevCountBadge({ sev, count }) {
    if (!count) return null;
    const styles = {
      critical: { background: '#fffbeb', color: '#b45309' },
      warning:  { background: '#fef3c7', color: '#d97706' },
      flag:     { background: '#e0e7ff', color: '#7c3aed' },
      all:      { background: 'var(--color-slate-100)', color: 'var(--text-secondary)' },
    };
    const s = styles[sev] || styles.all;
    return (
      <span style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        minWidth: 20, height: 18, borderRadius: 9, fontSize: 11, fontWeight: 700,
        padding: '0 6px', marginLeft: 4, ...s,
      }}>{count}</span>
    );
  }

  function ActionCard({ cfg, items, navigate }) {
    const highest = items.reduce((best, i) => SEV_ORDER[i.sev] < SEV_ORDER[best] ? i.sev : best, 'flag');
    const [open, setOpen] = useState(highest === 'critical');
    const sorted = items.slice().sort((a, b) => SEV_ORDER[a.sev] - SEV_ORDER[b.sev]);
    const critN = items.filter((i) => i.sev === 'critical').length;
    const warnN = items.filter((i) => i.sev === 'warning').length;
    const flagN = items.filter((i) => i.sev === 'flag').length;

    return (
      <div className="card mb16">
        <div
          className="card-head"
          style={{ cursor: 'pointer', padding: '12px 16px', userSelect: 'none' }}
          onClick={() => setOpen((o) => !o)}
        >
          <div className="row" style={{ gap: 10, alignItems: 'center', flex: 1 }}>
            <SevDot sev={highest} size={10} />
            <span style={{ fontWeight: 600, fontSize: 'var(--text-base)' }}>{cfg.label}</span>
            {critN > 0 && <SevCountBadge sev="critical" count={critN} />}
            {warnN > 0 && <SevCountBadge sev="warning" count={warnN} />}
            {flagN > 0 && <SevCountBadge sev="flag" count={flagN} />}
            <span className="muted" style={{ fontSize: 12, marginLeft: 4 }}>{cfg.desc}</span>
          </div>
          <span className={'caret' + (open ? ' open' : '')} style={{ marginLeft: 8 }}>
            <Icon name="chevron-right" size={16} />
          </span>
        </div>
        {open && (
          <div className="tbl-wrap">
            <table className="tbl tbl-compact">
              <thead>
                <tr>
                  <th style={{ width: 16 }}></th>
                  <th style={{ width: 160 }}>Reference</th>
                  <th>Reason</th>
                  <th style={{ width: 220 }}>Impact</th>
                  <th style={{ width: 240 }}>Next Action</th>
                  <th style={{ width: 72 }}></th>
                </tr>
              </thead>
              <tbody>
                {sorted.map((item, i) => (
                  <tr key={i}>
                    <td><SevDot sev={item.sev} /></td>
                    <td>
                      <div className="mono" style={{ fontWeight: 600, fontSize: 'var(--text-sm)' }}>{item.ref}</div>
                      {item.vendor && <div className="muted" style={{ fontSize: 11, marginTop: 1 }}>{item.vendor}</div>}
                    </td>
                    <td style={{ fontSize: 'var(--text-sm)' }}>{item.reason}</td>
                    <td style={{ fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>{item.impact}</td>
                    <td style={{ fontSize: 'var(--text-sm)' }}>{item.nextAction}</td>
                    <td>
                      {item.link && (
                        <button
                          className="btn btn-ghost btn-sm"
                          style={{ fontSize: 11, whiteSpace: 'nowrap' }}
                          onClick={(e) => { e.stopPropagation(); navigate(item.link.view, item.link); }}
                        >
                          <Icon name="external-link" size={12} />Open
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    );
  }

  function AllClearCard({ cfg }) {
    return (
      <div className="card mb16" style={{ opacity: 0.65 }}>
        <div className="card-head" style={{ padding: '10px 16px' }}>
          <div className="row" style={{ gap: 10, alignItems: 'center' }}>
            <span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: '50%', background: '#16a34a', flexShrink: 0 }} />
            <span style={{ fontWeight: 600, fontSize: 'var(--text-base)' }}>{cfg.label}</span>
            <span className="badge badge-green" style={{ fontSize: 11 }}>All clear</span>
            <span className="muted" style={{ fontSize: 12 }}>{cfg.desc}</span>
          </div>
        </div>
      </div>
    );
  }

  function ActionCockpit() {
    const { store, navigate } = window.useStore();
    const [sevFilter, setSevFilter] = useState('all');

    const allItems = useMemo(() => E.cockpitActionItems(store), [store]);

    const filtered = sevFilter === 'all' ? allItems : allItems.filter((i) => i.sev === sevFilter);

    const critCount = allItems.filter((i) => i.sev === 'critical').length;
    const warnCount = allItems.filter((i) => i.sev === 'warning').length;
    const flagCount = allItems.filter((i) => i.sev === 'flag').length;

    const cockpitConfig = (store.cockpitActionsConfig || [])
      .filter((c) => c.on)
      .sort((a, b) => (a.sortOrder || 99) - (b.sortOrder || 99));

    const dateStr = E.fmtDateNice(E.TODAY);
    const totalActions = allItems.length;

    return (
      <div className="page page-wide">
        <PageHeader
          title="Action Cockpit"
          subtitle={'CBCC daily to-do · ' + dateStr + (totalActions > 0 ? ' · ' + totalActions + ' action' + (totalActions !== 1 ? 's' : '') + ' need attention' : ' · All clear')}
        >
          <span className="field-hint" style={{ fontSize: 12 }}>
            Configure categories in <span className="link" onClick={() => navigate('settings', { section: 'cockpit_actions' })}>Settings → Action Cockpit</span>
          </span>
        </PageHeader>

        {/* Severity filter */}
        <div className="filterbar mb16">
          <div className="subtabs">
            {[
              { key: 'all',      label: 'All',      count: totalActions, sev: 'all' },
              { key: 'critical', label: 'Critical', count: critCount,    sev: 'critical' },
              { key: 'warning',  label: 'Warning',  count: warnCount,    sev: 'warning' },
              { key: 'flag',     label: 'Flag',     count: flagCount,    sev: 'flag' },
            ].map(({ key, label, count, sev }) => (
              <button
                key={key}
                className={'subtab' + (sevFilter === key ? ' active' : '')}
                onClick={() => setSevFilter(key)}
              >
                {label}
                {count > 0 && <SevCountBadge sev={sev} count={count} />}
              </button>
            ))}
          </div>
          <div className="spacer" />
          <span className="muted" style={{ fontSize: 11 }}>Recalculates on every store change · thresholds set in Settings</span>
        </div>

        {/* Action category cards */}
        {cockpitConfig.map((cfg) => {
          const ruleItems = filtered.filter((i) => i.ruleId === cfg.id);
          if (ruleItems.length === 0) {
            return sevFilter === 'all' ? <AllClearCard key={cfg.id} cfg={cfg} /> : null;
          }
          return <ActionCard key={cfg.id} cfg={cfg} items={ruleItems} navigate={navigate} />;
        })}

        {/* Global all-clear */}
        {allItems.length === 0 && (
          <div className="card card-pad" style={{ textAlign: 'center', padding: 56 }}>
            <Icon name="check-circle" size={44} color="#16a34a" />
            <div style={{ fontWeight: 600, fontSize: 'var(--text-lg)', marginTop: 14 }}>All clear for today</div>
            <div className="muted mt8" style={{ maxWidth: 380, margin: '8px auto 0' }}>
              No actions needed across all configured categories. Check back after the next AC cycle or when contracts approach expiry.
            </div>
          </div>
        )}

        {/* No results for active severity filter */}
        {allItems.length > 0 && filtered.length === 0 && sevFilter !== 'all' && (
          <div className="card card-pad" style={{ textAlign: 'center', padding: 40 }}>
            <Icon name="filter" size={32} color="#94a3b8" />
            <div className="muted mt8">No {sevFilter === 'warning' ? 'warning' : sevFilter} items across all categories.</div>
            <button className="btn btn-secondary btn-sm mt12" onClick={() => setSevFilter('all')}>Show all</button>
          </div>
        )}
      </div>
    );
  }

  window.ActionCockpit = ActionCockpit;
  window.Dashboard = ActionCockpit;
})();
