/*
 * DashboardAIUsageCard.jsx — Compact AI usage widget for Dashboard
 * v1.0.1 — 2026-05-15 (removed buggy super_admin/dev_admin hide check;
 *                       app normalizes those roles to 'sa' which never
 *                       matched the check anyway. SA users see personal
 *                       usage alongside the fleet-wide /aiusage panel —
 *                       different views, both useful.)
 * v1.0.0 — 2026-05-15
 *
 * Wraps GET /account/ai-usage (server.js v1.7.4+).
 * Renders content-only (no outer card chrome) so it slots into
 * Dashboard.jsx's WIDGETS registry — registered as 'ai-usage', the
 * Dashboard's WidgetCard wrapper provides title + icon + tier tag.
 *
 * Graceful failure: silent skeleton on any fetch error rather than
 * breaking the Dashboard grid.
 *
 * Click "View full details" → navigates to /myaiusage (the full
 * AccountAIUsage panel) via window.WPSBD.go.
 *
 * Design Standards 7-point compliance: self-contained .jsx, window
 * namespace, IIFE, theme vars only, mobile responsive, WCAG 2.1 AA,
 * generic placeholders. No hardcoded semantic-state hex (§4G).
 */
(function () {
  'use strict';

  const { useState, useEffect } = window.React;
  const RAILWAY = (window.WPSB && window.WPSB.RAILWAY) || 'https://wpsitebeam-railway-api-production.up.railway.app';

  function fmtInt(n) {
    if (n == null || isNaN(n)) return '\u2014';
    return Number(n).toLocaleString();
  }

  /* ── Progress bar (color logic matches AccountAIUsage.jsx) ────── */
  function ProgressBar(props) {
    const pct = props.pct;
    const clamped = Math.max(0, Math.min(100, pct || 0));
    let color = 'var(--green, #2ecc71)';
    if (clamped >= 100) color = 'var(--red, #e74c3c)';
    else if (clamped >= 80) color = 'var(--warn, #f39c12)';
    else if (clamped >= 60) color = 'var(--yellow, #f1c40f)';

    return window.React.createElement('div', {
      style: {
        width: '100%', height: 8,
        background: 'rgba(0,0,0,.15)',
        borderRadius: 4, overflow: 'hidden',
      },
      role: 'progressbar',
      'aria-valuenow': clamped, 'aria-valuemin': 0, 'aria-valuemax': 100,
      'aria-label': 'Daily AI assists used',
    },
      window.React.createElement('div', {
        style: { width: clamped + '%', height: '100%', background: color, transition: 'width .3s ease' }
      })
    );
  }

  /* ── Skeleton (loading) — content-only, fills WidgetCard chrome ── */
  function Skeleton() {
    return window.React.createElement('div', {
      style: { opacity: 0.6, padding: '4px 0' },
      'aria-busy': 'true', 'aria-label': 'Loading AI usage',
    },
      window.React.createElement('div', { style: { height: 22, width: '50%', background: 'rgba(0,0,0,.08)', borderRadius: 4, marginBottom: 10 } }),
      window.React.createElement('div', { style: { height: 8,  width: '100%', background: 'rgba(0,0,0,.08)', borderRadius: 4 } })
    );
  }

  /* ── Main component ────────────────────────────────────────────── */
  function DashboardAIUsageCard(props) {
    const onOpenFull = props && props.onOpenFull;
    const [data,    setData]    = useState(null);
    const [loading, setLoading] = useState(true);
    const [hidden,  setHidden]  = useState(false);

    useEffect(() => {
      if (hidden) return;
      let cancelled = false;
      (async () => {
        const token = window.WPSB && window.WPSB.getToken && window.WPSB.getToken();
        if (!token) { setHidden(true); setLoading(false); return; }
        try {
          const r = await fetch(RAILWAY + '/account/ai-usage', {
            headers: { 'Authorization': 'Bearer ' + token }
          });
          if (!r.ok) { setHidden(true); return; }
          const j = await r.json();
          if (cancelled) return;
          setData(j);
        } catch (_) {
          setHidden(true);  /* Silent fail — don't break Dashboard */
        } finally {
          if (!cancelled) setLoading(false);
        }
      })();
      return () => { cancelled = true; };
    }, [hidden]);

    function handleOpen(e) {
      e.preventDefault();
      if (typeof onOpenFull === 'function') { onOpenFull(); return; }
      if (window.WPSBD && window.WPSBD.go) window.WPSBD.go('myaiusage');
    }

    if (hidden) return null;
    if (loading) return window.React.createElement(Skeleton);
    if (!data || !data.today) return null;

    const isUnlimited = data.today.limit === -1;
    const usedToday   = data.today.used || 0;
    const limitToday  = data.today.limit;
    const pct         = data.today.pct || 0;
    const allowed     = data.today.allowed !== false;

    /* ── Content render (no outer card chrome — that's WidgetCard) ── */
    return window.React.createElement('div', { style: { padding: '4px 0' } },
      /* Number row */
      window.React.createElement('div', {
        style: { display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }
      },
        isUnlimited
          ? window.React.createElement('div', {
              style: { fontSize: '1.3rem', fontWeight: 700, color: 'var(--text)', lineHeight: 1.2 }
            },
              window.React.createElement('span', { style: { color: 'var(--beam, #00cfef)' } }, fmtInt(usedToday)),
              window.React.createElement('span', {
                style: { color: 'var(--dim)', fontSize: '.8rem', fontWeight: 400, marginLeft: 8 }
              }, 'used today')
            )
          : window.React.createElement('div', {
              style: { fontSize: '1.3rem', fontWeight: 700, color: 'var(--text)', lineHeight: 1.2 }
            },
              fmtInt(usedToday),
              window.React.createElement('span', {
                style: { color: 'var(--dim)', fontSize: '.8rem', fontWeight: 400, marginLeft: 4 }
              }, ' / ', fmtInt(limitToday))
            ),
        /* Status badge */
        !isUnlimited && !allowed && window.React.createElement('span', {
          style: { fontSize: '.68rem', color: 'var(--red, #e74c3c)', fontWeight: 600, letterSpacing: '.04em' }
        }, 'LIMIT REACHED'),
        !isUnlimited && allowed && pct >= 80 && window.React.createElement('span', {
          style: { fontSize: '.68rem', color: 'var(--warn, #f39c12)', fontWeight: 600, letterSpacing: '.04em' }
        }, '80% USED')
      ),

      /* Progress bar (skipped for unlimited) */
      !isUnlimited && window.React.createElement(ProgressBar, { pct: pct }),

      /* Empty-state nudge */
      !isUnlimited && usedToday === 0 && window.React.createElement('div', {
        style: { fontSize: '.72rem', color: 'var(--dim)', marginTop: 8 }
      }, 'Run an alt-text scan or site scan to use today\u2019s assists'),

      /* Unlimited subtitle */
      isUnlimited && window.React.createElement('div', {
        style: { fontSize: '.72rem', color: 'var(--dim)', marginTop: 4 }
      }, 'Enterprise \u2014 unlimited daily assists'),

      /* Footer: view details link + optional upgrade hint */
      window.React.createElement('div', {
        style: {
          fontSize: '.72rem',
          marginTop: 12, paddingTop: 8,
          borderTop: '1px solid var(--border)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }
      },
        window.React.createElement('a', {
          href: '#myaiusage',
          onClick: handleOpen,
          style: { color: 'var(--beam, #00cfef)', textDecoration: 'none', fontWeight: 500 },
          'aria-label': 'Open full AI usage details',
        }, 'View full details \u2192'),
        data.upgrade_target && pct >= 50 && !isUnlimited && window.React.createElement('span', {
          style: { color: 'var(--accent, #F0A830)', fontWeight: 500 }
        }, 'Upgrade for more')
      )
    );
  }

  window.DashboardAIUsageCard = DashboardAIUsageCard;
  console.log('[WPSB] DashboardAIUsageCard v1.0.1 loaded (Dashboard AI usage widget)');
})();
