/*
 * AccountAIUsage.jsx — Customer AI usage dashboard
 * v1.0.0 — 2026-05-15
 *
 * Wraps GET /account/ai-usage (server.js v1.7.4+).
 * Shows daily AI quota burndown vs plan limit + monthly breakdown by
 * module + upgrade CTA when nearing daily limit.
 *
 * Customer-facing (every plan tier sees their own usage). Distinct from
 * SA-only AIUsage.jsx which shows aggregate data across all accounts.
 *
 * Auth: window.WPSB.getToken() — defined in index.html bootstrap.
 *
 * Design Standards 7-point compliance: self-contained .jsx, window namespace,
 * IIFE, theme vars only, mobile responsive, WCAG 2.1 AA, generic placeholders.
 */
(function () {
  'use strict';

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

  /* ── helpers ─────────────────────────────────────────────────────── */
  function fmtInt(n) {
    if (n == null || isNaN(n)) return '\u2014';
    return Number(n).toLocaleString();
  }
  function fmtCents(c) {
    if (c == null || isNaN(c)) return '\u2014';
    if (c === 0) return '$0.00';
    return '$' + (c / 100).toFixed(2);
  }
  function fmtPlan(p) {
    if (!p) return '\u2014';
    return p.charAt(0).toUpperCase() + p.slice(1).replace('_', ' ');
  }
  function fmtCountdown(iso) {
    if (!iso) return '\u2014';
    try {
      const diff = new Date(iso).getTime() - Date.now();
      if (diff <= 0) return 'resetting now';
      const hrs = Math.floor(diff / 3600000);
      const mins = Math.floor((diff % 3600000) / 60000);
      if (hrs >= 1) return hrs + 'h ' + mins + 'm';
      return mins + 'm';
    } catch (_) { return '\u2014'; }
  }
  function moduleLabel(key) {
    const map = {
      alt_text_gen:            'Alt Text Generator',
      brain_chat:              'AI Chat',
      brain_scan_summary:      'Scan AI Summary',
      brain_scan_authenticated: 'Scan AI (Authenticated)',
      seo_analysis:            'SEO Analysis',
      content_generation:      'Content Generation',
    };
    return map[key] || key.replace(/_/g, ' ');
  }

  /* ── KPI card ────────────────────────────────────────────────────── */
  function KPI({ label, value, sub, accent }) {
    return React.createElement('div', {
      style: {
        background: 'var(--panel)',
        border: '1px solid var(--border)',
        borderRadius: 10,
        padding: '14px 16px',
        flex: '1 1 160px',
        minWidth: 0,
      }
    },
      React.createElement('div', {
        style: { fontSize: '.72rem', color: 'var(--dim)', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 4 }
      }, label),
      React.createElement('div', {
        style: { fontSize: '1.6rem', fontWeight: 700, color: accent || 'var(--text)', lineHeight: 1 }
      }, value),
      sub && React.createElement('div', {
        style: { fontSize: '.74rem', color: 'var(--dim)', marginTop: 4 }
      }, sub)
    );
  }

  /* ── Progress bar ────────────────────────────────────────────────── */
  function ProgressBar({ pct, accent }) {
    const clamped = Math.max(0, Math.min(100, pct || 0));
    /* Color logic: green <60, yellow 60-80, orange 80-100, red >=100 */
    let color = accent || '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 React.createElement('div', {
      style: {
        width: '100%',
        height: 12,
        background: 'rgba(0,0,0,.15)',
        borderRadius: 6,
        overflow: 'hidden',
        position: 'relative',
      },
      role: 'progressbar',
      'aria-valuenow': clamped,
      'aria-valuemin': 0,
      'aria-valuemax': 100,
      'aria-label': 'AI usage progress',
    },
      React.createElement('div', {
        style: {
          width: clamped + '%',
          height: '100%',
          background: color,
          transition: 'width .4s ease, background .3s ease',
        }
      })
    );
  }

  /* ── Main component ──────────────────────────────────────────────── */
  function AccountAIUsage() {
    const [data, setData]       = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError]     = useState(null);

    /* Mobile responsive */
    const [isNarrow, setIsNarrow] = useState(
      typeof window !== 'undefined' && window.matchMedia('(max-width: 700px)').matches
    );
    useEffect(() => {
      const mq = window.matchMedia('(max-width: 700px)');
      const handler = e => setIsNarrow(e.matches);
      mq.addEventListener('change', handler);
      return () => mq.removeEventListener('change', handler);
    }, []);

    async function loadUsage() {
      const token = window.WPSB && window.WPSB.getToken && window.WPSB.getToken();
      if (!token) { setError('Not authenticated.'); setLoading(false); return; }
      setLoading(true);
      setError(null);
      try {
        const r = await fetch(RAILWAY + '/account/ai-usage', {
          headers: { 'Authorization': 'Bearer ' + token }
        });
        const j = await r.json();
        if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));
        setData(j);
      } catch (e) {
        setError('Could not load usage: ' + e.message);
      } finally {
        setLoading(false);
      }
    }

    useEffect(() => { loadUsage(); }, []);

    /* ── render ───────────────────────────────────────────────────── */
    if (loading) {
      return React.createElement('div', {
        style: { padding: 40, textAlign: 'center', color: 'var(--dim)' }
      }, 'Loading AI usage\u2026');
    }
    if (error) {
      return React.createElement('div', {
        style: { padding: 24 }
      },
        React.createElement('div', {
          style: {
            background: 'rgba(231,76,60,.08)',
            border: '1px solid rgba(231,76,60,.3)',
            borderRadius: 8, padding: '14px 18px',
            color: 'var(--text)',
          }
        },
          React.createElement('strong', { style: { color: 'var(--red, #e74c3c)' } }, 'Error: '),
          error,
          React.createElement('button', {
            type: 'button',
            onClick: loadUsage,
            style: {
              marginLeft: 12,
              padding: '4px 12px',
              fontSize: '.78rem',
              background: 'transparent',
              color: 'var(--text)',
              border: '1px solid var(--border)',
              borderRadius: 6,
              cursor: 'pointer',
              fontFamily: 'inherit',
            }
          }, 'Retry')
        )
      );
    }
    if (!data) return null;

    const isUnlimited = data.today.limit === -1;
    const plan = data.plan || 'starter';
    const moduleKeys = Object.keys(data.this_month.by_module || {}).sort((a, b) =>
      (data.this_month.by_module[b] || 0) - (data.this_month.by_module[a] || 0)
    );

    return React.createElement('div', {
      style: { padding: isNarrow ? 16 : 24 }
      /* U1 fix 2026-05-18 (Sprint 1) — was `padding: ..., maxWidth: 1000, margin: '0 auto'`
         which made AI Usage narrower than other pages in the app. Removed the
         maxWidth+margin so it matches the standard content container width.
         Other pages (Dashboard, Account, Billing) use the full content area. */
    },
      /* Header */
      React.createElement('div', {
        style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, marginBottom: 20 }
      },
        React.createElement('div', null,
          React.createElement('h1', {
            style: { fontSize: '1.5rem', fontWeight: 700, color: 'var(--text)', margin: 0, fontFamily: "'Orbitron', system-ui, sans-serif" }
          }, 'AI Usage'),
          React.createElement('div', {
            style: { fontSize: '.85rem', color: 'var(--dim)', marginTop: 4 }
          }, 'Your AI assist usage on the ', React.createElement('strong', { style: { color: 'var(--text)' } }, fmtPlan(plan)), ' plan')
        ),
        React.createElement('button', {
          type: 'button',
          onClick: loadUsage,
          style: {
            padding: '6px 14px',
            fontSize: '.78rem',
            background: 'transparent',
            color: 'var(--text)',
            border: '1px solid var(--border)',
            borderRadius: 6,
            cursor: 'pointer',
            fontFamily: 'inherit',
          }
        }, 'Refresh')
      ),

      /* Daily usage card — the headline */
      React.createElement('div', {
        style: {
          background: 'var(--panel)',
          border: '1px solid var(--border)',
          borderRadius: 12,
          borderLeft: '4px solid var(--beam, #00cfef)',
          padding: isNarrow ? 16 : 22,
          marginBottom: 16,
        }
      },
        React.createElement('div', {
          style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8, marginBottom: 10 }
        },
          React.createElement('div', { style: { fontSize: '.9rem', fontWeight: 600, color: 'var(--text)' } },
            'Today\u2019s AI assists'
          ),
          React.createElement('div', { style: { fontSize: '.78rem', color: 'var(--dim)' } },
            isUnlimited
              ? React.createElement('span', null, 'Unlimited on ', fmtPlan(plan))
              : React.createElement('span', null, 'Resets in ', React.createElement('strong', { style: { color: 'var(--text)' } }, fmtCountdown(data.reset_at)))
          )
        ),

        isUnlimited
          ? React.createElement('div', {
              style: {
                background: 'rgba(0,207,239,0.08)',
                border: '1px solid rgba(0,207,239,0.2)',
                borderRadius: 8,
                padding: '14px 18px',
                color: 'var(--text)',
              }
            },
              React.createElement('div', { style: { fontSize: '1.2rem', fontWeight: 600, marginBottom: 4 } },
                React.createElement('strong', { style: { color: 'var(--beam, #00cfef)' } }, fmtInt(data.today.used || 0)),
                ' used today'
              ),
              React.createElement('div', { style: { fontSize: '.78rem', color: 'var(--dim)' } },
                'Enterprise plan \u2014 no daily limit'
              )
            )
          : React.createElement('div', null,
              React.createElement('div', {
                style: { display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }
              },
                React.createElement('div', { style: { fontSize: '1.4rem', fontWeight: 700, color: 'var(--text)' } },
                  fmtInt(data.today.used || 0),
                  React.createElement('span', { style: { color: 'var(--dim)', fontSize: '.85rem', fontWeight: 400, marginLeft: 6 } },
                    ' / ', fmtInt(data.today.limit), ' assists'
                  )
                ),
                React.createElement('div', { style: { fontSize: '.85rem', color: 'var(--dim)' } },
                  fmtInt(data.today.remaining || 0), ' remaining'
                )
              ),
              React.createElement(ProgressBar, { pct: data.today.pct }),

              /* Soft warning at 80% */
              !data.today.allowed && React.createElement('div', {
                style: {
                  marginTop: 10,
                  padding: '10px 14px',
                  background: 'rgba(231,76,60,.08)',
                  border: '1px solid rgba(231,76,60,.3)',
                  borderRadius: 8,
                  fontSize: '.82rem',
                  color: 'var(--text)',
                }
              },
                React.createElement('strong', { style: { color: 'var(--red, #e74c3c)' } }, 'Daily limit reached. '),
                'AI features pause until midnight UTC. ',
                data.upgrade_target && React.createElement('span', null,
                  'Upgrade to ', React.createElement('strong', { style: { color: 'var(--text)' } }, fmtPlan(data.upgrade_target)),
                  ' for ',
                  React.createElement('strong', { style: { color: 'var(--text)' } },
                    data.upgrade_benefits?.ai_calls_per_day === -1 ? 'unlimited' : fmtInt(data.upgrade_benefits?.ai_calls_per_day) + ' assists/day'
                  ),
                  '.'
                )
              ),
              data.today.allowed && data.today.pct >= 80 && React.createElement('div', {
                style: {
                  marginTop: 10,
                  padding: '10px 14px',
                  background: 'rgba(243,156,18,.08)',
                  border: '1px solid rgba(243,156,18,.3)',
                  borderRadius: 8,
                  fontSize: '.82rem',
                  color: 'var(--text)',
                }
              },
                React.createElement('strong', { style: { color: 'var(--warn, #f39c12)' } }, 'Approaching daily limit. '),
                data.upgrade_target && React.createElement('span', null,
                  'Upgrade to ', React.createElement('strong', { style: { color: 'var(--text)' } }, fmtPlan(data.upgrade_target)),
                  ' for more headroom.'
                )
              )
            )
      ),

      /* Monthly summary KPIs */
      React.createElement('div', {
        style: { display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }
      },
        React.createElement(KPI, {
          label: 'This month',
          value: fmtInt(data.this_month.calls || 0),
          sub: 'total AI assists'
        }),
        React.createElement(KPI, {
          label: 'Most used',
          value: moduleKeys.length > 0 ? moduleLabel(moduleKeys[0]) : '\u2014',
          sub: moduleKeys.length > 0 ? fmtInt(data.this_month.by_module[moduleKeys[0]]) + ' calls' : 'no usage yet',
          accent: 'var(--beam, #00cfef)'
        }),
        React.createElement(KPI, {
          label: 'Active plan',
          value: fmtPlan(plan),
          sub: isUnlimited ? 'unlimited assists' : fmtInt(data.today.limit) + ' assists/day'
        })
      ),

      /* Monthly breakdown by module */
      moduleKeys.length > 0 && React.createElement('div', {
        style: {
          background: 'var(--panel)',
          border: '1px solid var(--border)',
          borderRadius: 12,
          padding: isNarrow ? 14 : 18,
          marginBottom: 16,
        }
      },
        React.createElement('div', {
          style: { fontSize: '.9rem', fontWeight: 600, color: 'var(--text)', marginBottom: 12 }
        }, 'Usage by feature (this month)'),
        React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
          moduleKeys.map(key => {
            const count = data.this_month.by_module[key] || 0;
            const total = data.this_month.calls || 1;
            const pct = Math.round((count / total) * 100);
            return React.createElement('div', { key },
              React.createElement('div', {
                style: { display: 'flex', justifyContent: 'space-between', fontSize: '.82rem', marginBottom: 4 }
              },
                React.createElement('span', { style: { color: 'var(--text)' } }, moduleLabel(key)),
                React.createElement('span', { style: { color: 'var(--dim)' } }, fmtInt(count), ' \u00b7 ', pct, '%')
              ),
              React.createElement(ProgressBar, { pct, accent: 'var(--beam, #00cfef)' })
            );
          })
        )
      ),

      /* Empty state */
      moduleKeys.length === 0 && React.createElement('div', {
        style: {
          background: 'var(--panel)',
          border: '1px dashed var(--border)',
          borderRadius: 12,
          padding: '28px 20px',
          textAlign: 'center',
          color: 'var(--dim)',
          marginBottom: 16,
        }
      },
        React.createElement('div', { style: { fontSize: '.9rem', marginBottom: 4 } },
          'No AI usage this month yet'
        ),
        React.createElement('div', { style: { fontSize: '.78rem' } },
          'Run an alt-text generator, scanner AI summary, or AI chat to start tracking.'
        )
      ),

      /* Upgrade CTA card (only if not enterprise, only if upgrade target exists, only if > 50% used) */
      data.upgrade_target && data.upgrade_benefits && data.today.pct >= 50 && React.createElement('div', {
        style: {
          background: 'rgba(0,207,239,0.06)',
          border: '1px solid rgba(0,207,239,0.25)',
          borderRadius: 12,
          padding: isNarrow ? 16 : 20,
        }
      },
        React.createElement('div', {
          style: { fontSize: '.9rem', fontWeight: 600, color: 'var(--text)', marginBottom: 8 }
        }, 'Need more AI headroom?'),
        React.createElement('div', {
          style: { fontSize: '.85rem', color: 'var(--text)', marginBottom: 12 }
        },
          'Upgrade to ',
          React.createElement('strong', { style: { color: 'var(--beam, #00cfef)' } }, fmtPlan(data.upgrade_target)),
          ' for ',
          React.createElement('strong', null,
            data.upgrade_benefits.ai_calls_per_day === -1 ? 'unlimited' : fmtInt(data.upgrade_benefits.ai_calls_per_day) + ' assists/day'
          ),
          data.upgrade_benefits.monthly_price_diff > 0 && React.createElement('span', null,
            ' for an additional ',
            React.createElement('strong', null, '$', data.upgrade_benefits.monthly_price_diff),
            '/mo'
          ),
          '.'
        ),
        React.createElement('button', {
          type: 'button',
          onClick: () => { window.WPSBD && window.WPSBD.go && window.WPSBD.go('billing'); },
          style: {
            padding: '8px 18px',
            fontSize: '.85rem',
            background: 'var(--accent, #F0A830)',
            color: '#000',
            border: 'none',
            borderRadius: 6,
            cursor: 'pointer',
            fontFamily: 'inherit',
            fontWeight: 600,
          }
        }, 'View plans')
      )
    );
  }

  window.AccountAIUsage = AccountAIUsage;
  console.log('[WPSB] AccountAIUsage v1.0.0 loaded (Customer AI usage panel)');
})();
