/**
 * ═══════════════════════════════════════════════════════════════════
 * Analytics In-App Component (Admin-Gated)
 * ═══════════════════════════════════════════════════════════════════
 * 
 * Wrapper component that mounts Analytics dashboard inside app shell.
 * Uses extracted logic from pages/logic/analyticsLogic.js
 * 
 * SYSTEM_MAP COMPLIANT:
 * - Bearer token is the ONLY identity source
 * - NO URL identity params
 * - All authenticated calls use window.SylvanFlowAuth.authenticatedFetch
 * - Admin-gated (isAdmin === true required)
 */

(function() {
  'use strict';

  const { useState, useEffect, useRef } = React;

  function AnalyticsInApp() {
    const containerRef = useRef(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [analyticsData, setAnalyticsData] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [activeTab, setActiveTab] = useState('overview');

    useEffect(() => {
      // ✅ HARD GATING: Admin check is enforced by app.js renderComponent
      // Double-check here for safety
      const sessionToken = localStorage.getItem('sylvanflow_session_token');
      if (!sessionToken) {
        setError('Authentication required. Please log in.');
        setLoading(false);
        return;
      }

      // ✅ Use extracted logic
      if (!window.AnalyticsLogic) {
        setError('Analytics logic not loaded');
        setLoading(false);
        return;
      }

      // Check admin access first
      window.AnalyticsLogic.checkAdminAccess(
        (adminData) => {
          setIsAdmin(true);
          // Load metrics
          window.AnalyticsLogic.loadAllMetrics(
            (data) => {
              setAnalyticsData(data);
              setLoading(false);
            },
            (errorMsg) => {
              setError(errorMsg);
              setLoading(false);
            }
          );
        },
        (errorMsg) => {
          setError(errorMsg || 'Access denied. Admin privileges required.');
          setLoading(false);
        }
      );
    }, []);

    if (loading) {
      return (
        <div className="p-4 text-center text-slate-500">
          <p>Loading Analytics...</p>
        </div>
      );
    }

    if (error) {
      return (
        <div className="p-4 text-center text-red-600">
          <p>{error}</p>
        </div>
      );
    }

    if (!isAdmin) {
      return (
        <div className="p-4 text-center text-red-600">
          <p>Access denied. Admin privileges required.</p>
        </div>
      );
    }

    return (
      <div ref={containerRef} className="w-full h-full overflow-y-auto bg-white relative">
        {/* ✅ FIX: Back Button - Fixed Top-Left (Mobile Safe) */}
        <div 
          className="fixed z-50"
          style={{ 
            top: 'calc(env(safe-area-inset-top, 0px) + 10px)',
            left: '12px'
          }}
        >
          <button
            onClick={() => window.appState?.set({ view: 'power-up' })}
            className="inline-flex items-center gap-2 px-3.5 py-2.5 rounded-xl text-sm font-semibold text-slate-800 bg-white/90 backdrop-blur-md border-2 border-slate-300 shadow-lg transition-all hover:bg-white hover:border-slate-400 hover:shadow-xl active:translate-y-0"
            style={{ backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)' }}
          >
            ← Back to PowerUpAI
          </button>
        </div>

        {/* ✅ FIX: Mobile top padding for content to avoid back button overlap */}
        <div 
          className="max-w-6xl mx-auto p-4"
          style={{ 
            paddingTop: 'calc(env(safe-area-inset-top, 0px) + 64px)'
          }}
        >
          {/* Header */}
          <div className="text-center mb-6 py-6 px-5 rounded-2xl bg-gradient-to-br from-[#0f2810] to-[#1a3d0f] shadow-lg relative overflow-hidden border-5 border-transparent" style={{ borderImage: 'linear-gradient(135deg, #d4af37 0%, #f4d03f 50%, #d4af37 100%) 1' }}>
            <h1 className="text-4xl font-extrabold text-white mb-2" style={{ letterSpacing: '-1px', textShadow: '0 2px 8px rgba(0, 0, 0, 0.3)' }}>
              🌊 SylvanFlow Analytics Dashboard
            </h1>
            <p className="text-white/95 text-lg font-medium">
              Comprehensive metrics and insights for system performance and user engagement
            </p>
          </div>

          {/* ✅ FIX: Tab Bar - Horizontal Scrolling (Mobile Safe) */}
          <div 
            className="flex gap-3.5 overflow-x-auto overflow-y-hidden whitespace-nowrap pb-2 mb-5 border-b-2 border-slate-200"
            style={{ 
              WebkitOverflowScrolling: 'touch',
              scrollbarWidth: 'none',
              msOverflowStyle: 'none'
            }}
          >
            <style>{`
              .analytics-tabs::-webkit-scrollbar {
                display: none;
              }
            `}</style>
            <div className="analytics-tabs flex gap-3.5 px-3">
              {['overview', 'features', 'engagement', 'satisfaction', 'errors', 'poi-catalog', 'questionnaire', 'approvals', 'compliance', 'admin'].map((tab) => {
                const tabLabels = {
                  'overview': 'Overview',
                  'features': 'Feature Usage',
                  'engagement': 'Engagement',
                  'satisfaction': 'Satisfaction',
                  'errors': 'Errors & Concerns',
                  'poi-catalog': 'POI Catalog',
                  'questionnaire': 'Flow Finder',
                  'approvals': 'Approvals',
                  'compliance': 'Compliance & Monitoring',
                  'admin': 'Admin Tools'
                };
                return (
                  <button
                    key={tab}
                    onClick={() => setActiveTab(tab)}
                    className={`flex-shrink-0 whitespace-nowrap px-6 py-3 rounded-lg font-semibold text-sm transition-all ${
                      activeTab === tab
                        ? 'bg-[#1a3d0f] text-white border-2 border-[#d4af37]'
                        : 'bg-slate-100 text-slate-700 border-2 border-transparent hover:bg-slate-200'
                    }`}
                  >
                    {tabLabels[tab]}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Tab Content */}
          {analyticsData ? (
            <div className="space-y-4">
              {activeTab === 'overview' && (
                <div className="bg-white rounded-2xl p-6 shadow-lg border-2 border-[#d4af37]">
                  <h2 className="text-2xl font-bold mb-4 text-[#1a3d0f] border-b-3 border-[#d4af37] pb-2">
                    📊 System Overview
                  </h2>
                  <div className="bg-slate-50 rounded-lg p-4">
                    <h3 className="text-lg font-semibold mb-2">Smart Brain Metrics</h3>
                    <pre className="text-xs overflow-auto">
                      {JSON.stringify(analyticsData.smartBrain || {}, null, 2)}
                    </pre>
                  </div>
                  <div className="bg-slate-50 rounded-lg p-4 mt-4">
                    <h3 className="text-lg font-semibold mb-2">POI Catalog Analytics</h3>
                    <pre className="text-xs overflow-auto">
                      {JSON.stringify(analyticsData.poiCatalog || {}, null, 2)}
                    </pre>
                  </div>
                </div>
              )}
              {activeTab !== 'overview' && (
                <div className="bg-white rounded-2xl p-6 shadow-lg border-2 border-[#d4af37]">
                  <h2 className="text-2xl font-bold mb-4 text-[#1a3d0f] border-b-3 border-[#d4af37] pb-2">
                    {activeTab === 'features' && '🎯 Feature Usage'}
                    {activeTab === 'engagement' && '👥 User Engagement'}
                    {activeTab === 'satisfaction' && '😊 User Satisfaction'}
                    {activeTab === 'errors' && '⚠️ Errors & User Concerns'}
                    {activeTab === 'poi-catalog' && '🗺️ POI Catalog Analytics'}
                    {activeTab === 'questionnaire' && '📝 Flow Finder Analytics'}
                    {activeTab === 'approvals' && '👤 User Approvals'}
                    {activeTab === 'compliance' && '✅ Compliance & Monitoring Dashboard'}
                    {activeTab === 'admin' && '🛠️ Admin Tools'}
                  </h2>
                  <p className="text-slate-600 text-center py-8">
                    {activeTab} tab content will be displayed here. This requires integration with the full dashboard logic from the standalone page.
                  </p>
                </div>
              )}
            </div>
          ) : (
            <p className="text-slate-600">No analytics data available.</p>
          )}
        </div>
      </div>
    );
  }

  // Export to window
  if (typeof window !== 'undefined') {
    window.AnalyticsInApp = AnalyticsInApp;
  }
})();

