/* Admin panel shell — login + sidebar nav + topbar. */

/* ---------- Admin session (sessionStorage) ---------- */
function useAdminSession() {
  const [user, setUser] = useState(() => {
    try {
      const raw = sessionStorage.getItem('sf_admin_session');
      return raw ? JSON.parse(raw) : null;
    } catch (e) { return null; }
  });
  const login = (username) => {
    const u = { username, since: Date.now() };
    sessionStorage.setItem('sf_admin_session', JSON.stringify(u));
    setUser(u);
  };
  const logout = () => {
    sessionStorage.removeItem('sf_admin_session');
    setUser(null);
  };
  return { user, login, logout };
}

/* ---------- Login ---------- */
function AdminLogin({ onLogin }) {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('');
  const [err, setErr] = useState('');
  const submit = (e) => {
    e && e.preventDefault();
    if (username === 'admin' && password === 'ChangeMe2026!') {
      setErr('');
      // Store for API auth headers
      sessionStorage.setItem('sf_admin_token', password);
      onLogin(username);
    } else {
      setErr('Invalid credentials. Hint: admin / ChangeMe2026!');
    }
  };
  return (
    <div style={{
      minHeight: '100vh', background: 'var(--grey-50)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 22,
      position: 'relative', overflow: 'hidden',
    }}>
      {/* dot grid + diagonal */}
      <div aria-hidden="true" className="dot-grid" style={{ position: 'absolute', inset: 0, opacity: 0.4 }} />
      <div aria-hidden="true" style={{
        position: 'absolute', left: -60, top: '30%', width: '70%', height: 8,
        background: 'var(--orange)', transform: 'skewX(-12deg)',
      }} />

      <form onSubmit={submit} style={{
        position: 'relative',
        background: '#fff',
        border: '1px solid var(--grey-200)',
        borderRadius: 12,
        boxShadow: '0 8px 32px rgba(17,6,24,0.14)',
        padding: 36, width: '100%', maxWidth: 420,
      }}>
        <SunFrontLogo height={32} />
        <div className="font-display" style={{
          fontSize: 28, marginTop: 22, letterSpacing: '-0.02em',
        }}>
          Admin Console
        </div>
        <div style={{ color: 'var(--grey-600)', fontSize: 13.5, marginTop: 6 }}>
          Sign in to manage the campaign.
        </div>

        <div style={{ marginTop: 24, display: 'grid', gap: 14 }}>
          <label>
            <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>Username</div>
            <input value={username} onChange={(e) => setUsername(e.target.value)} autoFocus
              style={{ ...inputStyle }} />
          </label>
          <label>
            <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 700, marginBottom: 6 }}>Password</div>
            <input value={password} onChange={(e) => setPassword(e.target.value)} type="password"
              placeholder="••••••••"
              style={{ ...inputStyle }} />
          </label>
        </div>

        {err && (
          <div style={{
            marginTop: 14, padding: '10px 12px', background: '#fee2e2', color: '#b91c1c',
            border: '1px solid #fecaca', fontSize: 13,
          }}>{err}</div>
        )}

        <button type="submit" className="font-display btn-press" style={{
          marginTop: 22, width: '100%',
          background: 'var(--orange)', color: '#fff', border: 'none',
          borderRadius: 6,
          padding: '16px 22px', fontSize: 15, letterSpacing: '0.06em', textTransform: 'uppercase',
          boxShadow: '0 4px 16px rgba(241,86,35,0.30)',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        }}>
          Sign in
          <Icon name="arrow" size={18} />
        </button>

        <div style={{ marginTop: 16, fontSize: 12, color: 'var(--grey-500)', textAlign: 'center' }}>
          Default: <span className="font-mono" style={{ color: 'var(--ink)' }}>admin</span> /
          {' '}<span className="font-mono" style={{ color: 'var(--ink)' }}>ChangeMe2026!</span>
          <br />
          <span style={{ color: '#b91c1c', fontWeight: 600 }}>Change immediately after deploy.</span>
        </div>
      </form>
    </div>
  );
}

/* ---------- Sidebar nav ---------- */
const ADMIN_NAV = [
  { key: 'overview',     label: 'Overview',     icon: 'bolt' },
  { group: 'Matches' },
  { key: 'matches',      label: 'All matches',  icon: 'flag' },
  { key: 'create',       label: 'Schedule new', icon: 'calendar' },
  { key: 'settle',       label: 'Settle result',icon: 'check' },
  { key: 'draw',         label: 'Lucky draw',   icon: 'trophy' },
  { group: 'Data' },
  { key: 'predictions',  label: 'Predictions',  icon: 'receipt' },
  { key: 'outlets',      label: 'Outlets',      icon: 'pin' },
  { group: 'Site' },
  { key: 'content',      label: 'Content & images', icon: 'message' },
  { key: 'settings',     label: 'Settings',     icon: 'target' },
];

function AdminSidebar({ active, onPick, openMobile, setOpenMobile }) {
  const Item = ({ item }) => {
    const isActive = active === item.key;
    return (
      <button onClick={() => { onPick(item.key); setOpenMobile(false); }} style={{
        background: isActive ? 'var(--orange)' : 'transparent',
        color: isActive ? '#fff' : '#d4d4d8',
        border: 'none',
        width: '100%', textAlign: 'left',
        padding: '12px 18px',
        display: 'flex', alignItems: 'center', gap: 12,
        fontSize: 13.5, fontWeight: isActive ? 700 : 500, letterSpacing: '0.02em',
        cursor: 'pointer',
        position: 'relative',
        transition: 'background 0.12s, color 0.12s',
      }}
      onMouseEnter={(e) => { if (!isActive) e.currentTarget.style.background = '#2a1f30'; }}
      onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
      >
        {isActive && (
          <span style={{
            position: 'absolute', left: 0, top: 8, bottom: 8, width: 4, background: '#fff',
          }} />
        )}
        <Icon name={item.icon} size={17} color={isActive ? '#fff' : 'var(--orange)'} stroke={1.8} />
        {item.label}
      </button>
    );
  };

  return (
    <>
      {openMobile && (
        <div onClick={() => setOpenMobile(false)} style={{
          position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 39,
        }} />
      )}
      <aside className={`admin-sidebar ${openMobile ? 'open' : ''}`} style={{
        background: 'var(--ink)', color: '#fff',
        width: 240, flexShrink: 0,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '20px 18px 18px', borderBottom: '1px solid #2a1f30' }}>
          <SunFrontLogo height={28} onWhite={false} />
          <div style={{
            marginTop: 8, fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase',
            color: 'var(--orange)', fontWeight: 700,
          }}>
            Admin Console
          </div>
        </div>
        <nav style={{ padding: '12px 0', flex: 1, overflowY: 'auto' }}>
          {ADMIN_NAV.map((item, i) =>
            item.group ? (
              <div key={`g-${i}`} style={{
                padding: '14px 18px 6px', fontSize: 10, letterSpacing: '0.22em',
                textTransform: 'uppercase', color: 'var(--grey-500)', fontWeight: 700,
              }}>{item.group}</div>
            ) : (
              <Item key={item.key} item={item} />
            )
          )}
        </nav>
        <div style={{
          padding: '14px 18px', borderTop: '1px solid #2a1f30',
          fontSize: 11, color: 'var(--grey-500)', letterSpacing: '0.06em',
        }}>
          v1.0 · campaign 2026
        </div>
      </aside>
    </>
  );
}

/* ---------- Topbar ---------- */
function AdminTopbar({ user, onLogout, onSync, syncing, title, onMenu }) {
  return (
    <header style={{
      background: '#fff', borderBottom: '1px solid var(--grey-200)',
      padding: '12px 22px',
      display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between',
      position: 'sticky', top: 0, zIndex: 20,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
        <button className="only-mobile" onClick={onMenu} style={{
          background: 'none', border: '1.5px solid var(--grey-300)', borderRadius: 6, padding: 8, cursor: 'pointer',
        }} aria-label="Open menu">
          <svg width="18" height="18" viewBox="0 0 24 24" stroke="currentColor" fill="none" strokeWidth="2.4" strokeLinecap="round">
            <path d="M3 7h18M3 12h18M3 17h18"/>
          </svg>
        </button>
        <div className="font-display" style={{ fontSize: 20, letterSpacing: '-0.01em' }}>{title}</div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <button onClick={onSync} disabled={syncing} className="font-display" style={{
          background: '#fff', color: 'var(--ink)', border: '1.5px solid var(--grey-300)', borderRadius: 6,
          padding: '9px 14px', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase',
          display: 'inline-flex', alignItems: 'center', gap: 8,
          cursor: syncing ? 'wait' : 'pointer', opacity: syncing ? 0.6 : 1,
        }} title="Manually run the SCHEDULED→OPEN→CLOSED transition logic">
          <Icon name="bolt" size={14} />
          {syncing ? 'Syncing…' : 'Sync statuses'}
        </button>
        <div className="hide-mobile" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 8px', borderLeft: '1px solid var(--grey-200)' }}>
          <div style={{
            width: 30, height: 30, borderRadius: '50%',
            background: 'var(--ink)', color: 'var(--orange)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13,
            fontFamily: "'Nunito', sans-serif",
          }}>
            {user.username.slice(0, 1).toUpperCase()}
          </div>
          <div>
            <div style={{ fontSize: 13, fontWeight: 700 }}>{user.username}</div>
            <div style={{ fontSize: 11, color: 'var(--grey-500)' }}>Administrator</div>
          </div>
        </div>
        <button onClick={onLogout} style={{
          background: 'none', border: '1.5px solid var(--grey-300)', borderRadius: 6,
          padding: '8px 12px', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase',
          fontWeight: 700, color: 'var(--grey-700)', cursor: 'pointer',
        }}>
          Log out
        </button>
      </div>
    </header>
  );
}

/* ---------- Toast ---------- */
function AdminToast({ toast, onDone }) {
  useEffect(() => {
    if (!toast) return;
    const id = setTimeout(onDone, 3500);
    return () => clearTimeout(id);
  }, [toast, onDone]);
  if (!toast) return null;
  const tone = toast.tone || 'success';
  const palette = {
    success: { bg: 'var(--success-bg)', fg: '#0f5f2e', bd: 'var(--success)' },
    info:    { bg: 'var(--orange-50)',   fg: 'var(--orange-dark)', bd: 'var(--orange)' },
    error:   { bg: '#fee2e2',            fg: '#b91c1c', bd: '#ef4444' },
  }[tone];
  return (
    <div className="toast-in" style={{
      position: 'fixed', top: 22, left: '50%', zIndex: 50,
      background: palette.bg, color: palette.fg,
      border: `1px solid ${palette.bd}`,
      borderRadius: 8,
      boxShadow: '0 4px 20px rgba(17,6,24,0.12)',
      padding: '12px 18px', maxWidth: 520,
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <Icon name={tone === 'error' ? 'bolt' : 'check'} size={18} stroke={3} />
      <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.4 }}>{toast.message}</div>
    </div>
  );
}

/* ---------- Page section wrapper ---------- */
function AdminSection({ title, sub, right, children }) {
  return (
    <div>
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'end',
        gap: 16, flexWrap: 'wrap', marginBottom: 22,
      }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--orange)', fontWeight: 700 }}>
            Admin
          </div>
          <h1 className="font-display" style={{ fontSize: 'clamp(24px, 4vw, 34px)', lineHeight: 1, margin: '6px 0 6px', letterSpacing: '-0.02em' }}>
            {title}
          </h1>
          {sub && <p style={{ margin: 0, color: 'var(--grey-600)', fontSize: 14 }}>{sub}</p>}
        </div>
        {right}
      </div>
      {children}
    </div>
  );
}

/* ---------- White card panel ---------- */
function Panel({ title, action, children, padding = 22 }) {
  return (
    <div style={{
      background: '#fff', border: '1px solid var(--grey-200)',
      borderRadius: 10,
      boxShadow: '0 2px 12px rgba(17,6,24,0.06)',
    }}>
      {(title || action) && (
        <div style={{
          padding: '14px 18px', borderBottom: '1px solid var(--grey-200)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        }}>
          <div className="font-display" style={{ fontSize: 16, letterSpacing: '-0.01em' }}>{title}</div>
          {action}
        </div>
      )}
      <div style={{ padding }}>{children}</div>
    </div>
  );
}

/* ---------- Primary / secondary admin buttons ---------- */
function AdminBtn({ kind = 'primary', icon, children, ...rest }) {
  const styles = {
    primary:   { bg: 'var(--orange)', fg: '#fff',         bd: 'transparent',     sh: '0 4px 12px rgba(241,86,35,0.28)' },
    ink:       { bg: 'var(--ink)',    fg: '#fff',         bd: 'transparent',     sh: '0 4px 12px rgba(17,6,24,0.20)' },
    outline:   { bg: '#fff',          fg: 'var(--ink)',   bd: 'var(--ink)',      sh: '0 2px 8px rgba(17,6,24,0.08)' },
    ghost:     { bg: '#fff',          fg: 'var(--ink)',   bd: 'var(--grey-300)', sh: 'none' },
    danger:    { bg: '#fff',          fg: '#b91c1c',      bd: '#fecaca',         sh: 'none' },
  }[kind];
  return (
    <button {...rest} className="font-display btn-press" style={{
      background: styles.bg, color: styles.fg,
      border: `1.5px solid ${styles.bd}`,
      borderRadius: 6,
      padding: '11px 16px',
      fontSize: 12.5, letterSpacing: '0.06em', textTransform: 'uppercase',
      display: 'inline-flex', alignItems: 'center', gap: 8,
      boxShadow: styles.sh,
      cursor: rest.disabled ? 'not-allowed' : 'pointer',
      opacity: rest.disabled ? 0.55 : 1,
      ...rest.style,
    }}>
      {icon && <Icon name={icon} size={14} />}
      {children}
    </button>
  );
}

/* ---------- Time-ago ---------- */
function timeAgo(ms) {
  const diff = Date.now() - ms;
  const min = Math.floor(diff / 60000);
  if (min < 1) return 'just now';
  if (min < 60) return `${min}m ago`;
  const h = Math.floor(min / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

/* ---------- Main admin app ---------- */
function AdminApp({ onLeave }) {
  const session = useAdminSession();
  const [tab, setTab] = useState('overview');
  const [openMobile, setOpenMobile] = useState(false);
  const [toast, setToast] = useState(null);
  const [syncing, setSyncing] = useState(false);

  // Local mutable copies — in prod these are server state.
  const [matchesState, setMatchesState] = useState(() => [...MATCHES]);
  const [outletsState, setOutletsState] = useState(() => [...OUTLETS]);
  const [contentState, setContentState] = useState(() => ({ ...SITE_CONTENT_DEFAULTS }));

  if (!session.user) return <AdminLogin onLogin={session.login} />;

  const titleMap = {
    overview: 'Overview',
    matches: 'All matches',
    create: 'Schedule a new match',
    settle: 'Settle a match',
    draw: 'Run the lucky draw',
    predictions: 'Predictions',
    outlets: 'Outlets',
    content: 'Content & images',
    settings: 'Settings',
  };

  function doSync() {
    setSyncing(true);
    setTimeout(() => {
      setSyncing(false);
      setToast({ message: 'Match statuses synced. 0 transitions made.', tone: 'success' });
    }, 900);
  }

  const adminToken = (() => {
    try { return sessionStorage.getItem('sf_admin_token') || ''; } catch(e) { return ''; }
  })();

  const ctx = {
    user: session.user,
    adminToken,
    matchesState, setMatchesState,
    outletsState, setOutletsState,
    contentState, setContentState,
    setToast,
    goTab: setTab,
  };

  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--grey-50)' }}>
      <AdminToast toast={toast} onDone={() => setToast(null)} />
      <AdminSidebar active={tab} onPick={setTab} openMobile={openMobile} setOpenMobile={setOpenMobile} />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <AdminTopbar
          user={session.user}
          onLogout={() => { session.logout(); onLeave && onLeave(); }}
          onSync={doSync}
          syncing={syncing}
          title={titleMap[tab] || 'Admin'}
          onMenu={() => setOpenMobile(true)}
        />
        <div style={{
          flex: 1, padding: 22, overflowX: 'hidden',
        }}>
          {tab === 'overview'    && <AdminOverview ctx={ctx} />}
          {tab === 'matches'     && <AdminMatches ctx={ctx} />}
          {tab === 'create'      && <AdminCreate ctx={ctx} />}
          {tab === 'settle'      && <AdminSettle ctx={ctx} />}
          {tab === 'draw'        && <AdminDraw ctx={ctx} />}
          {tab === 'predictions' && <AdminPredictions ctx={ctx} />}
          {tab === 'outlets'     && <AdminOutlets ctx={ctx} />}
          {tab === 'content'     && <AdminContent ctx={ctx} />}
          {tab === 'settings'    && <AdminSettings ctx={ctx} />}
        </div>
      </div>

      <style>{`
        @media (max-width: 900px) {
          .admin-sidebar {
            position: fixed; left: 0; top: 0; bottom: 0; z-index: 40;
            transform: translateX(-100%);
            transition: transform 0.24s cubic-bezier(.2,.7,.2,1);
            box-shadow: 12px 0 24px rgba(0,0,0,0.2);
          }
          .admin-sidebar.open { transform: translateX(0); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, {
  AdminApp, AdminLogin, AdminBtn, Panel, AdminSection, timeAgo, useAdminSession,
});
