// admin-dashboard.jsx

const AdminSideIcon = ({ type }) => {
  const s = { width: 17, height: 17, flexShrink: 0 };
  if (type === 'overview') return (
    <svg style={s} viewBox="0 0 17 17" fill="none">
      <rect x="1" y="1" width="6.5" height="6.5" rx="1.5" fill="currentColor" />
      <rect x="9.5" y="1" width="6.5" height="6.5" rx="1.5" fill="currentColor" />
      <rect x="1" y="9.5" width="6.5" height="6.5" rx="1.5" fill="currentColor" />
      <rect x="9.5" y="9.5" width="6.5" height="6.5" rx="1.5" fill="currentColor" />
    </svg>
  );
  if (type === 'profiles') return (
    <svg style={s} viewBox="0 0 17 17" fill="none">
      <circle cx="5.5" cy="5" r="3" fill="currentColor" />
      <path d="M1 14.5c0-2.5 2-4.5 4.5-4.5s4.5 2 4.5 4.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" />
      <circle cx="13" cy="5" r="2.2" fill="currentColor" opacity="0.55" />
      <path d="M11 14.5c0-2 1.2-3.5 2.5-3.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" opacity="0.55" />
    </svg>
  );
  if (type === 'crm') return (
    <svg style={s} viewBox="0 0 17 17" fill="none">
      <rect x="1" y="2.5" width="15" height="2.5" rx="1.25" fill="currentColor" />
      <rect x="1" y="7.25" width="15" height="2.5" rx="1.25" fill="currentColor" />
      <rect x="1" y="12" width="9" height="2.5" rx="1.25" fill="currentColor" />
    </svg>
  );
  if (type === 'instructors') return (
    <svg style={s} viewBox="0 0 17 17" fill="none">
      <circle cx="8.5" cy="5" r="3" fill="currentColor" />
      <path d="M2 15c0-3.3 2.9-6 6.5-6s6.5 2.7 6.5 6" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" />
      <path d="M12 8l1.2 1.2L15 7.5" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
  if (type === 'analytics') return (
    <svg style={s} viewBox="0 0 17 17" fill="none">
      <polyline points="1,14 5,9 9,11 13,5 16,3" stroke="currentColor" strokeWidth="1.7" fill="none" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx="5"  cy="9"  r="1.5" fill="currentColor" />
      <circle cx="9"  cy="11" r="1.5" fill="currentColor" />
      <circle cx="13" cy="5"  r="1.5" fill="currentColor" />
    </svg>
  );
  if (type === 'teacher-finder') return (
    <svg style={s} viewBox="0 0 17 17" fill="none">
      {/* Map-pin glyph for Teacher Finder */}
      <path d="M8.5 1.5c2.5 0 4.5 2 4.5 4.5 0 3-4.5 8.5-4.5 8.5S4 9 4 6c0-2.5 2-4.5 4.5-4.5z" fill="currentColor" />
      <circle cx="8.5" cy="6" r="1.6" fill="oklch(19% 0.07 265)" />
    </svg>
  );
  return null;
};

// Chevron for the collapsible nav groups — points right when collapsed and
// rotates down when the group is open.
const AdminNavChevron = ({ open }) => (
  <svg width="10" height="10" viewBox="0 0 10 10" fill="none"
       style={{ transition: 'transform 0.18s ease', transform: open ? 'rotate(90deg)' : 'rotate(0deg)', flexShrink: 0, opacity: 0.65 }}>
    <path d="M3 1.5 L6.5 5 L3 8.5" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

// ── Sidebar navigation ──────────────────────────────────────────────────────
// Overview sits on its own at the top; every other screen lives inside a
// collapsible group so the sidebar stays short and scrolls instead of being a
// 20-plus-item wall that runs off the bottom of a laptop screen with no way to
// reach the items below the fold.
const ADMIN_NAV_STANDALONE = { id: 'overview', label: 'Overview', icon: 'overview' };
const ADMIN_NAV_GROUPS = [
  { key: 'lessons', label: 'Lessons', items: [
    { id: 'calendar',      label: 'Calendar',           icon: 'overview'       },
    { id: 'schedule',      label: 'Schedule',           icon: 'analytics'      },
    { id: 'live-meetings', label: 'Live meetings',      icon: 'analytics'      },
    { id: 'pending',       label: 'Pending Confirms',   icon: 'crm'            },
    { id: 'reminders',     label: 'Reminders',          icon: 'crm'            },
    { id: 'recordings',    label: 'Recordings',         icon: 'analytics'      },
    { id: 'gcal-imports',  label: 'Google imports',     icon: 'crm'            },
    { id: 'gcal-reviews',  label: 'Google Changes',     icon: 'crm'            },
  ]},
  { key: 'people', label: 'People', items: [
    { id: 'payouts',       label: 'Payouts',            icon: 'analytics'      },
    { id: 'instructors',   label: 'Instructors',        icon: 'instructors'    },
    { id: 'applications',  label: 'Applications',       icon: 'crm'            },
    { id: 'students',      label: 'Students',           icon: 'profiles'       },
  ]},
  { key: 'growth', label: 'Growth', items: [
    { id: 'analytics',     label: 'Analytics',          icon: 'analytics'      },
    { id: 'profiles',      label: 'Lead Sources',       icon: 'profiles'       },
    { id: 'leads',         label: 'Leads CRM',          icon: 'crm'            },
    { id: 'tfinder',       label: 'Teacher Finder',     icon: 'teacher-finder' },
    { id: 'teacher-leads', label: 'In-Person Teachers', icon: 'teacher-finder' },
  ]},
  { key: 'communication', label: 'Communication', items: [
    { id: 'messages',      label: 'Messages',           icon: 'crm'            },
    { id: 'maskedcalls',   label: 'Masked Calls',       icon: 'crm'            },
    { id: 'ratings',       label: 'Ratings',            icon: 'analytics'      },
  ]},
  { key: 'labs', label: 'Labs', items: [
    { id: 'violin',        label: 'Violin Lab',         icon: 'analytics'      },
    { id: 'drums',         label: 'Drums Lab',          icon: 'analytics'      },
    { id: 'guitar',        label: 'Guitar Lab',         icon: 'analytics'      },
    { id: 'practice',      label: 'Practice Lab',       icon: 'analytics'      },
    { id: 'piano',         label: 'Piano Lab',          icon: 'analytics'      },
  ]},
  { key: 'system', label: 'System', items: [
    { id: 'terms',         label: 'Terms & Conditions', icon: 'crm'            },
    { id: 'security',      label: 'Security',           icon: 'crm'            },
    { id: 'trash',         label: 'Trash',              icon: 'crm'            },
  ]},
];
// Flat list of every valid tab id, derived from the nav structure so a deep
// link like /#admin?tab=security validates without a second hand-kept array.
const ADMIN_KNOWN_TABS = [ADMIN_NAV_STANDALONE.id, ...ADMIN_NAV_GROUPS.flatMap(g => g.items.map(i => i.id))];
// Which group (if any) a tab id belongs to — null for the standalone Overview.
const adminGroupForTab = (tab) => {
  for (const g of ADMIN_NAV_GROUPS) if (g.items.some(it => it.id === tab)) return g.key;
  return null;
};

const AdminDashboard = ({ onBack }) => {
  // Persist admin auth in localStorage (was sessionStorage) so the admin stays
  // signed in across page refreshes and tab restarts. Clears only on explicit
  // Sign Out (or when the underlying Supabase session expires).
  const [isAuthed, setIsAuthed] = React.useState(() => localStorage.getItem('mastery_admin') === '1');
  // Seed the active tab from a URL-fragment param when present, so a
  // Telegram deep-link like `/#admin?tab=live-meetings&booking=<id>`
  // lands on the right tab. Validates against the known tab IDs so an
  // unknown ?tab= value falls back to 'overview' rather than rendering
  // a blank content area.
  const initialTab = (() => {
    try {
      const hash = (typeof window !== 'undefined' && window.location.hash) || '';
      const qix  = hash.indexOf('?');
      if (qix === -1) return 'overview';
      const t = new URLSearchParams(hash.slice(qix + 1)).get('tab');
      return (t && ADMIN_KNOWN_TABS.includes(t)) ? t : 'overview';
    } catch (_) { return 'overview'; }
  })();
  const [activeTab, setActiveTab] = React.useState(initialTab);
  // Collapsible sidebar groups. Open the group that owns the initial tab and
  // remember the admin's open/closed choices across reloads; fall back to
  // opening "Lessons" so a fresh load isn't a wall of closed headers.
  const [openGroups, setOpenGroups] = React.useState(() => {
    let base = {};
    try {
      const saved = JSON.parse(localStorage.getItem('mastery_admin_nav_groups') || 'null');
      if (saved && typeof saved === 'object') base = { ...saved };
    } catch (_) {}
    const k = adminGroupForTab(initialTab);
    if (k) base[k] = true;
    else if (Object.keys(base).length === 0) base.lessons = true;
    return base;
  });
  React.useEffect(() => {
    try { localStorage.setItem('mastery_admin_nav_groups', JSON.stringify(openGroups)); } catch (_) {}
  }, [openGroups]);
  const toggleGroup = (key) => setOpenGroups(prev => ({ ...prev, [key]: !prev[key] }));
  // Responsive sidebar — auto-collapses on narrow viewports so the content
  // area gets its full width back. Joe noticed the dashboard wasn't usable
  // when he squeezed the laptop window. Threshold (1100px) is roughly a
  // 13" laptop in split-screen mode.
  const isMobileAdmin = window.useIsMobile ? window.useIsMobile(1100) : false;
  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  // Pull the real signed-in email so the sidebar chip reflects who's logged in
  // (instead of a hardcoded "admin@mastery.com").
  const [adminEmail, setAdminEmail] = React.useState('');
  React.useEffect(() => {
    if (!isAuthed) return;
    let cancelled = false;
    window.supa.auth.getUser().then(({ data }) => {
      if (!cancelled) setAdminEmail(data?.user?.email || '');
    }).catch(() => {});
    return () => { cancelled = true; };
  }, [isAuthed]);
  // Today's date, formatted in the user's locale. Was previously hardcoded.
  const todayLabel = new Date().toLocaleDateString(undefined, { month: 'long', day: 'numeric', year: 'numeric' });

  // Refresh admin data from Supabase whenever the admin lands here.
  React.useEffect(() => {
    if (isAuthed) window.ADMIN_DATA.refresh();
  }, [isAuthed]);

  const handleLogout = async () => {
    localStorage.removeItem('mastery_admin');
    sessionStorage.removeItem('mastery_admin'); // legacy cleanup
    try { await window.supa.auth.signOut(); } catch (e) {}
    setIsAuthed(false);
  };

  if (!isAuthed) {
    return <window.AdminLogin
      onLogin={() => { localStorage.setItem('mastery_admin', '1'); setIsAuthed(true); }}
      onBack={onBack}
    />;
  }

  // One nav row. `grouped` items get a touch more left padding so they read as
  // children of their group header.
  const renderNavButton = (item, grouped) => {
    const active = activeTab === item.id;
    return (
      <button
        key={item.id}
        onClick={() => { setActiveTab(item.id); setSidebarOpen(false); }}
        style={{
          display: 'flex', alignItems: 'center', gap: 11,
          width: '100%', padding: grouped ? '10px 14px 10px 18px' : '11px 14px',
          borderRadius: 10,
          background: active ? 'rgba(255,255,255,0.11)' : 'transparent',
          border: 'none', cursor: 'pointer', textAlign: 'left',
          color: active ? '#fff' : 'rgba(255,255,255,0.48)',
          fontSize: 14, fontWeight: active ? 600 : 400,
          fontFamily: "'Plus Jakarta Sans', sans-serif",
          transition: 'all 0.14s',
          marginBottom: 2,
          borderLeft: active ? '3px solid oklch(72% 0.17 80)' : '3px solid transparent',
        }}
      >
        <AdminSideIcon type={item.icon} />
        {item.label}
      </button>
    );
  };

  const tabTitle = {
    overview:    'Overview',
    calendar:    'Calendar · Every teacher’s lessons in one view',
    schedule:    'Schedule · Every class across the business',
    'live-meetings': 'Live meetings · Real-time transcripts + AI alerts',
    payouts:     'Payouts · What you owe teachers · settle by day, week or month',
    instructors: 'Instructors · Studios & schedules',
    applications:'Applications · Teachers waiting to be approved',
    students:    'Students · Enrolled · Classes · Payments',
    analytics:   'Analytics',
    profiles:    'Lead Sources · Third-party platform profiles',
    leads:       'Leads CRM',
    tfinder:     'Teacher Finder · Source & message new tutors',
    'teacher-leads': 'Teacher Leads · Bot replies that ask rate + availability',
    reminders:   'Reminders · Booking reminder emails (platform-wide)',
    'gcal-reviews': 'Google Changes · Approve lesson edits made on Google Calendar',
    ratings:     'Ratings · Per-session feedback from students and teachers',
    terms:       'Terms & Conditions · Publish versions, see who agreed',
    messages:    'Messages · Read every student/teacher conversation',
    maskedcalls: 'Masked Calls · Voice calls between teachers and students',
    pending:     'Pending Confirms · Teachers who haven’t confirmed their new student',
    security:    'Security · Recent activity, signups & audit log',
    trash:       'Trash · Restore recently deleted students and teachers',
    violin:      'Violin Lab · Violin lessons & practice exercises (admin beta)',
    recordings:  'Recordings · Lesson audio captured in the instructor\'s browser',
    drums:       'Drums Lab · Drum basics — lessons + practice (admin beta)',
    guitar:      'Guitar Lab · Lessons + practice for guitar basics (admin beta)',
    practice:    'Practice Lab · Music theory exercises (admin beta)',
    piano:       'Piano Lab · Piano fundamentals + ear training (admin beta)',
  };

  // Sidebar is fixed-width on wide screens; on narrow viewports it slides
  // in as an overlay when the hamburger button is tapped.
  const sidebarVisible = !isMobileAdmin || sidebarOpen;

  return (
    <div style={{ display: 'flex', height: '100vh', overflow: 'hidden', fontFamily: "'Plus Jakarta Sans', sans-serif", background: 'oklch(97% 0.006 60)', position: 'relative' }}>

      {/* Backdrop (mobile only) — tap to close the drawer */}
      {isMobileAdmin && sidebarOpen && (
        <div onClick={() => setSidebarOpen(false)} style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.35)', zIndex:9 }} />
      )}

      {/* ── Sidebar ── */}
      <aside style={{
        width: 232, background: 'oklch(19% 0.07 265)',
        display: 'flex', flexDirection: 'column', flexShrink: 0,
        zIndex: 10,
        ...(isMobileAdmin ? {
          position: 'fixed', top: 0, bottom: 0, left: 0,
          transform: sidebarVisible ? 'translateX(0)' : 'translateX(-100%)',
          transition: 'transform 0.22s ease',
          boxShadow: sidebarVisible ? '0 10px 40px rgba(0,0,0,0.3)' : 'none',
        } : {}),
      }}>
        {/* Logo */}
        <div style={{ padding: '26px 22px 22px', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
          <div style={{ fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 15, fontWeight: 700, color: '#fff', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Mastery</div>
          <div style={{ fontSize: 10, color: 'oklch(72% 0.17 80)', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 5 }}>Admin Dashboard</div>
        </div>

        {/* Nav — Overview on top, every other screen in a collapsible group so
            the list stays short and scrolls instead of overflowing off-screen. */}
        <nav style={{ flex: 1, padding: '14px 10px', overflowY: 'auto' }}>
          {renderNavButton(ADMIN_NAV_STANDALONE, false)}
          {ADMIN_NAV_GROUPS.map(group => {
            const open = !!openGroups[group.key];
            const hasActive = group.items.some(it => it.id === activeTab);
            return (
              <div key={group.key}>
                <button
                  onClick={() => toggleGroup(group.key)}
                  aria-expanded={open}
                  style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    width: '100%', padding: '9px 14px', borderRadius: 8,
                    background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left',
                    color: (hasActive && !open) ? 'oklch(72% 0.17 80)' : 'rgba(255,255,255,0.4)',
                    fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
                    fontFamily: "'Plus Jakarta Sans', sans-serif",
                    marginTop: 10, marginBottom: 2,
                    transition: 'color 0.14s',
                  }}
                >
                  <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                    {group.label}
                    {hasActive && !open && (
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'oklch(72% 0.17 80)' }} />
                    )}
                  </span>
                  <AdminNavChevron open={open} />
                </button>
                {open && group.items.map(item => renderNavButton(item, true))}
              </div>
            );
          })}
        </nav>

        {/* Footer */}
        <div style={{ padding: '16px 18px', borderTop: '1px solid rgba(255,255,255,0.08)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
            <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'oklch(72% 0.17 80)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700, color: 'oklch(22% 0.06 265)', flexShrink: 0 }}>A</div>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>Admin</div>
              <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.38)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={adminEmail || ''}>{adminEmail || '—'}</div>
            </div>
          </div>
          <button
            onClick={handleLogout}
            style={{ width: '100%', background: 'rgba(255,255,255,0.07)', border: 'none', borderRadius: 8, padding: '8px 0', color: 'rgba(255,255,255,0.48)', fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif", transition: 'background 0.14s' }}
            onMouseEnter={e => e.target.style.background = 'rgba(255,255,255,0.13)'}
            onMouseLeave={e => e.target.style.background = 'rgba(255,255,255,0.07)'}
          >Sign Out</button>
        </div>
      </aside>

      {/* ── Main ── */}
      <main style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minWidth: 0 }}>
        {/* Top bar */}
        <header style={{ background: '#fff', borderBottom: '1px solid oklch(90% 0.01 265)', padding: isMobileAdmin ? '12px 16px' : '14px 30px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0, boxShadow: '0 1px 6px oklch(18% 0.06 265 / 0.04)', gap: 10 }}>
          {isMobileAdmin && (
            <button onClick={() => setSidebarOpen(o => !o)} aria-label="Open menu" style={{ width:36, height:36, borderRadius:8, border:'1px solid oklch(88% 0.02 265)', background:'#fff', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:3, cursor:'pointer', padding:0, flexShrink:0 }}>
              {[0,1,2].map(i => <span key={i} style={{ width:16, height:2, borderRadius:1, background:'oklch(28% 0.05 265)' }} />)}
            </button>
          )}
          <div style={{ minWidth:0, flex:1 }}>
            <h1 style={{ fontSize: isMobileAdmin ? 15 : 19, fontWeight: 700, color: 'oklch(18% 0.03 265)', margin: 0, lineHeight: 1.2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{tabTitle[activeTab]}</h1>
            <div style={{ fontSize: 11, color: 'oklch(60% 0.03 265)', marginTop: 2 }}>Mastery · {todayLabel}</div>
          </div>
          {window.AdminSilentModeToggle && <window.AdminSilentModeToggle />}
          <button
            onClick={onBack}
            style={{ background: 'oklch(96% 0.01 265)', border: '1px solid oklch(88% 0.02 265)', borderRadius: 9, padding: '8px 16px', fontSize: 12, fontWeight: 600, color: 'oklch(42% 0.04 265)', cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif", transition: 'background 0.14s', whiteSpace:'nowrap', flexShrink:0 }}
          >{isMobileAdmin ? '←' : '← Back to Site'}</button>
        </header>

        {window.AdminSilentModeBanner && <window.AdminSilentModeBanner />}

        {/* Content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: isMobileAdmin ? '16px 14px' : '26px 30px' }}>
          {activeTab === 'overview'    && <window.AdminOverview />}
          {activeTab === 'calendar'    && <window.AdminCalendar />}
          {activeTab === 'schedule'    && <window.AdminSchedule />}
          {activeTab === 'live-meetings' && <window.AdminLiveMeetings />}
          {activeTab === 'payouts'     && <window.AdminPayouts />}
          {activeTab === 'instructors' && <window.AdminInstructors />}
          {activeTab === 'applications'&& <window.AdminApplications />}
          {activeTab === 'students'    && <window.AdminStudents />}
          {activeTab === 'analytics'   && <window.AdminAnalytics />}
          {activeTab === 'profiles'    && <window.AdminProfiles />}
          {activeTab === 'leads'       && <window.AdminCRM />}
          {activeTab === 'tfinder'     && <window.AdminTeacherFinder />}
          {activeTab === 'teacher-leads' && <window.AdminLeads />}
          {activeTab === 'reminders'   && <window.AdminReminders />}
          {activeTab === 'ratings'     && <window.AdminRatings />}
          {activeTab === 'terms'       && <window.AdminTerms />}
          {activeTab === 'messages'    && <window.AdminMessages />}
          {activeTab === 'maskedcalls' && <window.AdminMaskedCallsTab />}
          {activeTab === 'pending'     && <window.AdminPendingConfirmations />}
          {activeTab === 'security'    && <window.AdminSecurity />}
          {activeTab === 'trash'       && <window.AdminTrash />}
          {activeTab === 'violin'      && window.ViolinLab && window.ViolinLab.ui && window.ViolinLab.ui.ViolinLab && <window.ViolinLab.ui.ViolinLab />}
          {activeTab === 'recordings'  && <window.AdminRecordings />}
          {activeTab === 'gcal-imports'&& <window.AdminGcalImports />}
          {activeTab === 'gcal-reviews'&& <window.AdminGcalReviews />}
          {activeTab === 'drums'       && window.DrumsLab && window.DrumsLab.ui && window.DrumsLab.ui.DrumsLab && <window.DrumsLab.ui.DrumsLab />}
          {activeTab === 'guitar'      && window.GuitarLab   && window.GuitarLab.ui   && window.GuitarLab.ui.GuitarLab     && <window.GuitarLab.ui.GuitarLab />}
          {activeTab === 'practice'    && window.PracticeLab && window.PracticeLab.ui && window.PracticeLab.ui.PracticeLab && <window.PracticeLab.ui.PracticeLab />}
          {activeTab === 'piano'       && window.PianoLab && window.PianoLab.ui && window.PianoLab.ui.PianoLab && <window.PianoLab.ui.PianoLab />}
        </div>
      </main>
    </div>
  );
};

Object.assign(window, { AdminDashboard });
