/* global React, ReactDOM, YUNO_DATA, YUNO_COMPONENTS, YUNO_PANELS, YUNO_SECTIONS, YUNO_AUTH, YUNO_LOGIN */
(function () {
const { useState, useMemo, useEffect } = React;
const D = window.YUNO_DATA;
const { computeFiltered } = window.YUNO_COMPONENTS;
const { Sidebar, PageFilterBar, AtRiskStrip, Drawer, ExecSummary, ComingSoonPage, ExpandableSidebar } = window.YUNO_PANELS;
const { OverviewSection, AllKpisSection, PipelineSection, RegionsSection,
  SourcesSection, EfficiencySection, CustomerSection, OwnersSection, LeadFunnelSection, TeamsSection } = window.YUNO_SECTIONS;

// Per-page filter dimensions — currently only overview page (owners page temporarily removed)
const PAGE_DIMS = {
  overview:   [], // No filters on overview - clean executive view
  teams:      ['owner'], // Teams page with functional team filtering
  // owners:     ['owner', 'region'], // Department owners with minimal filtering - TEMPORARILY REMOVED
};

const PAGE_TITLES = {
  overview:   ['Executive Overview', 'KPI Dashboard 2026'],
  teams:      ['Teams', 'KPI performance by functional teams'],
  // owners:     ['Department Owners', 'KPI ownership and accountability by business function'], // TEMPORARILY REMOVED
};

// Authentication wrapper - protects dashboard without changing existing functionality
function AuthWrapper() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Check authentication state on mount
    if (typeof YUNO_AUTH !== 'undefined') {
      // Check if using placeholder credentials (development mode)
      if (YUNO_AUTH.isDevelopmentMode && YUNO_AUTH.isDevelopmentMode()) {
        // Development mode: bypass authentication
        console.log('Development mode detected: Bypassing authentication due to placeholder credentials');
        setIsAuthenticated(true);
        setCurrentUser({ email: 'dev@y.uno', name: 'Development User' });
        setIsLoading(false);
        return;
      }

      // Production mode: use real authentication
      const checkAuth = () => {
        const authenticated = YUNO_AUTH.isAuthenticated();
        const user = YUNO_AUTH.getCurrentUser();

        setIsAuthenticated(authenticated);
        setCurrentUser(user);
        setIsLoading(false);
      };

      // Listen for auth changes
      YUNO_AUTH.onAuthChange((isSignedIn, user) => {
        setIsAuthenticated(isSignedIn);
        setCurrentUser(user);
        setIsLoading(false);
      });

      // Initial check
      checkAuth();
    } else {
      // If auth not available, just show dashboard (development mode)
      setIsLoading(false);
      setIsAuthenticated(true);
    }
  }, []);

  const handleAuthSuccess = (user) => {
    setCurrentUser(user);
    setIsAuthenticated(true);
  };

  // Loading state
  if (isLoading) {
    return (
      <div style={{
        height: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#f8fafc'
      }}>
        <div style={{
          width: '40px',
          height: '40px',
          border: '4px solid #e2e8f0',
          borderTop: '4px solid #3E4FE0',
          borderRadius: '50%',
          animation: 'spin 1s linear infinite'
        }} />
      </div>
    );
  }

  // Show login page if not authenticated
  if (!isAuthenticated) {
    if (typeof YUNO_LOGIN !== 'undefined') {
      return <YUNO_LOGIN.LoginPage onAuthSuccess={handleAuthSuccess} />;
    } else {
      // Login system failed to load - show error instead of bypassing auth
      return (
        <div style={{
          height: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#f8fafc',
          fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'
        }}>
          <div style={{
            background: 'white',
            borderRadius: '16px',
            padding: '48px 40px',
            boxShadow: '0 20px 60px rgba(0, 0, 0, 0.1)',
            textAlign: 'center',
            maxWidth: '400px'
          }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#dc2626', marginBottom: '16px' }}>
              Authentication Required
            </div>
            <div style={{ fontSize: '16px', color: '#64748b', marginBottom: '24px' }}>
              Authentication system failed to load. Please refresh the page to try again.
            </div>
            <button
              onClick={() => window.location.reload()}
              style={{
                padding: '12px 24px',
                backgroundColor: '#3b82f6',
                color: 'white',
                border: 'none',
                borderRadius: '8px',
                fontSize: '16px',
                fontWeight: '500',
                cursor: 'pointer'
              }}
            >
              Refresh Page
            </button>
          </div>
        </div>
      );
    }
  }

  // Show dashboard if authenticated
  return <App />;
}

function App() {
  const [activePage, setActivePage] = useState('overview');
  // 'picker' = TeamPicker tile grid (default Teams landing). Leaf team ids
  // navigate directly to their team page. Cluster ids with children also fall
  // through to the picker since clusters don't have their own page.
  const [selectedTeam, setSelectedTeam] = useState('picker');
  // Lifted period state — shared between Executive Overview and Teams pages so the
  // selected month/quarter follows the user across the app.
  // Default: last completed month. Today is mid-Q2 (May 2026), so April is
  // the most recent month with full actuals. Bump when rolling forward.
  const [activeQ, setActiveQ] = useState('Q2');
  const [activeMonth, setActiveMonth] = useState('Apr');

  // Force redirect to overview if trying to access owners page
  React.useEffect(() => {
    if (activePage === 'owners') {
      setActivePage('overview');
    }
  }, [activePage]);
  const [view, setView] = useState('qtd');
  const [granularity, setGranularity] = useState('week');
  const [filters, setFilters] = useState({ region: [], source: [], stage: [], owner: [], vertical: [] });
  const [drawerKpi, setDrawerKpi] = useState(null);
  const [sidebarContent, setSidebarContent] = useState(null);
  const [sidebarExpanded, setSidebarExpanded] = useState(false);

  // Listen for sidebar content updates from within the sidebar
  React.useEffect(() => {
    const handleSidebarUpdate = (event) => {
      setSidebarContent(event.detail);
    };

    window.addEventListener('updateSidebarContent', handleSidebarUpdate);
    return () => {
      window.removeEventListener('updateSidebarContent', handleSidebarUpdate);
    };
  }, []);

  // Handle sidebar content (department functionality temporarily disabled)
  const handleOpenSidebar = (contentOrDeptId) => {
    // Handle new object format (strategic KPIs drill-down)
    if (typeof contentOrDeptId === 'object' && contentOrDeptId.content) {
      setSidebarContent(contentOrDeptId);
      return;
    }

    // DEPARTMENT FUNCTIONALITY TEMPORARILY DISABLED
    // Handle legacy departmentId format (fallback) - COMMENTED OUT
    // const departmentId = contentOrDeptId;
    // const department = D.DEPARTMENTS.find(d => d.id === departmentId);
    // if (department) {
    //   setSidebarContent({
    //     content: 'department',
    //     department: departmentId,
    //     category: 'Department Analysis',
    //     title: department.label,
    //     subtitle: `${department.sub} • ${department.members.length} team members`
    //   });
    // }
  };

  // Handle KPI card clicks to open individual KPI drill-down
  const handleKpiClick = (kpi) => {

    // Open individual KPI drill-down for all KPIs
    setSidebarContent({
      content: 'kpi',
      kpi: kpi,
      category: 'KPI DEEP-DIVE',
      title: kpi.name,
      subtitle: `${kpi.owner || kpi.team || 'Yuno'} • Q2 2026 Performance Analysis`
    });
  };

  const closeSidebar = () => {
    setSidebarContent(null);
    setSidebarExpanded(false);
  };

  const toggleSidebarExpand = () => {
    setSidebarExpanded(!sidebarExpanded);
  };

  // ----- Command palette wiring ------------------------------------------
  // Listen for actions dispatched by the palette and route them to the
  // appropriate state setter. See command-palette.jsx for the action shape.
  React.useEffect(() => {
    const Q_FOR_MONTH = { Jan: 'Q1', Feb: 'Q1', Mar: 'Q1', Apr: 'Q2', May: 'Q2', Jun: 'Q2',
                         Jul: 'Q3', Aug: 'Q3', Sep: 'Q3', Oct: 'Q4', Nov: 'Q4', Dec: 'Q4' };
    const FIRST_MONTH_OF = { Q1: 'Jan', Q2: 'Apr', Q3: 'Jul', Q4: 'Oct' };
    function onPaletteAction(e) {
      const action = e.detail;
      if (!action) return;
      if (action.type === 'navigate-page') {
        setActivePage(action.page);
      } else if (action.type === 'navigate-team') {
        setActivePage('teams');
        setSelectedTeam(action.teamId);
      } else if (action.type === 'switch-period') {
        if (action.month) {
          setActiveQ(Q_FOR_MONTH[action.month] || 'Q2');
          setActiveMonth(action.month);
        } else if (action.quarter) {
          setActiveQ(action.quarter);
          setActiveMonth(FIRST_MONTH_OF[action.quarter] || 'Apr');
        }
      } else if (action.type === 'open-kpi') {
        // Direct KPI click in the palette — open the KPI drill-in if we have
        // one (KPI present in march-data). Cascade-only KPIs fall through to
        // the `open-kpi-cascade` branch below.
        const M = window.YUNO_MARCH_2026 || {};
        const id = action.kpiId;
        const kpi = (M.STRATEGIC || []).find(k => k.id === id)
                 || Object.values(M.HEADLINES || {}).flat().find(k => k.id === id);
        if (kpi) handleKpiClick(kpi);
      } else if (action.type === 'show-insight') {
        // Click on an insight item in the palette. Two scopes:
        //   scope='kpi'    → open that KPI's drill-in (where the "Insights"
        //                    section now renders the insight). For
        //                    cascade-only KPIs without a drill-in, fall back
        //                    to opening the pillar insights sidebar so the
        //                    user still sees the prose they clicked.
        //   scope='pillar' → open the pillar insights sidebar directly. The
        //                    sidebar's chronological list contains the
        //                    insight the user clicked.
        const PILLAR_NAMES = {
          P1: 'Scalable Growth',
          P2: 'Operational Leverage',
          P3: 'Customer Value',
          P4: 'People & Culture',
        };
        const ANCHOR_BY_PILLAR = {
          P1: { id: 'arr',                 name: 'ARR' },
          P2: { id: 'ebitda',              name: 'EBITDA' },
          P3: { id: 'customer_retention',  name: 'Customer Retention' },
          P4: { id: 'enps',                name: 'eNPS' },
        };
        if (action.scope === 'kpi') {
          const M = window.YUNO_MARCH_2026 || {};
          const kpi = (M.STRATEGIC || []).find(k => k.id === action.identifier)
                   || Object.values(M.HEADLINES || {}).flat().find(k => k.id === action.identifier);
          if (kpi) {
            handleKpiClick(kpi);
          } else {
            // Cascade-only KPI — figure out which pillar the cascade record
            // belongs to so we can open the pillar sidebar with it.
            const cd = window.YUNO_CASCADE_DATA || {};
            const ck = (cd.kpis || []).find(k => {
              if (!k.name) return false;
              const id = k.name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
              return id === action.identifier;
            });
            const pillarFull = (ck && ck.pillar) || '';
            const tag = pillarFull.split(':')[0].trim() || 'P1';
            setSidebarContent({
              content: 'pillar_insights',
              pillar: { tag, name: PILLAR_NAMES[tag] || pillarFull },
              anchor: ANCHOR_BY_PILLAR[tag] || { id: null, name: null },
              monthKey: 'apr',
              category: 'PILLAR INSIGHTS',
              title: PILLAR_NAMES[tag] || pillarFull,
              subtitle: `${tag} · curated insights from spreadsheet`,
            });
          }
        } else if (action.scope === 'pillar') {
          const tag = action.identifier;
          setSidebarContent({
            content: 'pillar_insights',
            pillar: { tag, name: PILLAR_NAMES[tag] || tag },
            anchor: ANCHOR_BY_PILLAR[tag] || { id: null, name: null },
            monthKey: 'apr',
            category: 'PILLAR INSIGHTS',
            title: PILLAR_NAMES[tag] || tag,
            subtitle: `${tag} · curated insights from spreadsheet`,
          });
        }
      } else if (action.type === 'open-kpi-cascade') {
        // Cascade-only KPI search result has no drill-in. Open the pillar
        // sidebar so users at least see the curated insights for its pillar
        // (most cascade-only KPIs have insights at the pillar tier).
        const PILLAR_NAMES = {
          P1: 'Scalable Growth', P2: 'Operational Leverage',
          P3: 'Customer Value',  P4: 'People & Culture',
        };
        const ANCHOR_BY_PILLAR = {
          P1: { id: 'arr', name: 'ARR' },
          P2: { id: 'ebitda', name: 'EBITDA' },
          P3: { id: 'customer_retention', name: 'Customer Retention' },
          P4: { id: 'enps', name: 'eNPS' },
        };
        const pillarFull = String(action.pillar || '');
        const tag = pillarFull.split(':')[0].trim() || 'P1';
        setSidebarContent({
          content: 'pillar_insights',
          pillar: { tag, name: PILLAR_NAMES[tag] || pillarFull },
          anchor: ANCHOR_BY_PILLAR[tag] || { id: null, name: null },
          monthKey: 'apr',
          category: 'PILLAR INSIGHTS',
          title: PILLAR_NAMES[tag] || pillarFull,
          subtitle: `${tag} · curated insights from spreadsheet`,
        });
      } else if (action.type === 'open-pillar-insights') {
        // Dispatched by the anchor cards' bottom click zone. Opens the
        // right-side sidebar with all curated insights (cascade.insights)
        // for the pillar + anchor KPI, grouped by month newest-first.
        setSidebarContent({
          content: 'pillar_insights',
          pillar: { tag: action.pillarTag, name: action.pillarName },
          anchor: { id: action.anchorId, name: action.anchorName },
          monthKey: action.monthKey,
          category: 'PILLAR INSIGHTS',
          title: action.pillarName,
          subtitle: `${action.pillarTag} · curated insights from spreadsheet`,
        });
      }
    }
    window.addEventListener('yuno-palette-action', onPaletteAction);
    return () => window.removeEventListener('yuno-palette-action', onPaletteAction);
  }, []);

  const atRisk = useMemo(() => {
    const out = [];
    D.STRATEGIC.forEach(k => {
      const actual = computeFiltered(k, view, filters, 'actual');
      const target = computeFiltered(k, view, filters, 'target');
      const pace = view === 'qtd' && (k.format === 'currencyMM' || k.format === 'currencyK')
        ? target * D.QUARTER_PROGRESS : target;
      const pct = D.pctToTarget(actual, pace, k.higherIsBetter);
      if (pct < -20) out.push({ id: k.id, name: k.name, pct: 100 + pct, kpi: k });
    });
    return out.sort((a, b) => a.pct - b.pct);
  }, [view, filters]);

  function renderSection() {
    const props = { filters, setFilters, view, setView, granularity, onKpiClick: handleKpiClick };

    // Handle global pages only - departments are handled via expandable sidebar
    // NOTE: Owners page temporarily removed - can be restored by uncommenting below
    switch (activePage) {
      case 'overview':   return <OverviewSection view={view} onKpiClick={handleKpiClick} onOpenSidebar={handleOpenSidebar}
                                  activeQ={activeQ} setActiveQ={setActiveQ} activeMonth={activeMonth} setActiveMonth={setActiveMonth}/>;
      case 'teams':      return <TeamsSection {...props} selectedTeam={selectedTeam} onSelectTeam={setSelectedTeam}
                                  activeQ={activeQ} setActiveQ={setActiveQ} activeMonth={activeMonth} setActiveMonth={setActiveMonth}/>;
      // case 'owners':     return <OwnersSection {...props}/>; // TEMPORARILY REMOVED
      default: return <OverviewSection view={view} onKpiClick={handleKpiClick} onOpenSidebar={handleOpenSidebar}
                                  activeQ={activeQ} setActiveQ={setActiveQ} activeMonth={activeMonth} setActiveMonth={setActiveMonth}/>;
    }
  }

  const [title, subtitle] = PAGE_TITLES[activePage] || PAGE_TITLES.overview;

  // Mobile drawer state — on phones the left sidebar is off-screen by default
  // and slides in when the user taps the hamburger in the mobile top bar. The
  // backdrop click + auto-close on navigation keep the open state sane.
  // On desktop (>768px CSS) this state has no visual effect: the sidebar is
  // always visible regardless. We keep it as a single boolean for simplicity.
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  // Auto-close the mobile drawer whenever the user navigates so the new
  // page isn't hidden behind the drawer.
  React.useEffect(() => { setMobileNavOpen(false); }, [activePage, selectedTeam]);
  // Lock body scroll while the drawer is open so the page doesn't scroll
  // behind it on mobile.
  React.useEffect(() => {
    document.body.classList.toggle('mobile-nav-open', mobileNavOpen);
    return () => document.body.classList.remove('mobile-nav-open');
  }, [mobileNavOpen]);

  return (
    <div className={`app${mobileNavOpen ? ' mobile-nav-open' : ''}`}>
      {/* Mobile top bar — visible only at phone widths (CSS @media). Provides
          the hamburger affordance to open the slide-in drawer, plus a Yuno
          wordmark so the page isn't unbranded when the sidebar is off-screen. */}
      <div className="mobile-topbar" role="banner">
        <button
          className="mobile-topbar-menu"
          aria-label="Open menu"
          aria-expanded={mobileNavOpen}
          onClick={() => setMobileNavOpen(v => !v)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
            <path d="M3 6h18M3 12h18M3 18h18"/>
          </svg>
        </button>
        <span className="mobile-topbar-brand">YUNO</span>
        <span className="mobile-topbar-page">{title}</span>
      </div>

      {/* Backdrop shown when the mobile drawer is open. Tap → close. */}
      <div
        className="mobile-nav-backdrop"
        onClick={() => setMobileNavOpen(false)}
        aria-hidden="true"
      />

      <Sidebar
        activePage={activePage} onPage={setActivePage}
        onOpenSidebar={handleOpenSidebar}
        sidebarContent={sidebarContent}
        selectedTeam={selectedTeam}
        onSelectTeam={setSelectedTeam}/>
      <main className="main-content">
        {/* The small top-right palette trigger button was removed in favor of the
            hero search at the top of Executive Overview. Cmd/Ctrl+K still opens
            the palette globally. On the Teams page (no hero search currently)
            the keyboard shortcut is the entry point. */}
        <div className="content" data-screen-label={`YUNO · ${title}`}>
          {renderSection()}
        </div>
      </main>
      {/* Command palette modal — listens for Cmd+K + custom toggle event. */}
      {window.YUNO_PALETTE && window.YUNO_PALETTE.CommandPalette && (
        <window.YUNO_PALETTE.CommandPalette />
      )}
      <Drawer kpi={drawerKpi} view={view} filters={filters} onClose={() => setDrawerKpi(null)}/>
      <ExpandableSidebar
        content={sidebarContent}
        expanded={sidebarExpanded}
        onToggleExpand={toggleSidebarExpand}
        onClose={closeSidebar}
        monthKey={activeQ === 'Q2' && activeMonth === 'Apr' ? 'apr' : 'mar'}
      />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<AuthWrapper/>);
})();
