// Login gate + App header + Global filter bar
const DS = window.NCSPresaleDesignSystem_3f9137;

/* ── Login gate ─────────────────────────────────────────── */
function Login({ onEnter }) {
  return (
    <div style={{ minHeight: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 22, padding: 24 }}>
      <div style={{ background: '#fff', padding: '14px 20px', borderRadius: 12, boxShadow: '0 8px 30px rgba(0,0,0,0.4)' }}>
        <img src="../../assets/yip-next-logo.png" alt="YIPINTSOI NEXT" style={{ height: 40, display: 'block' }} />
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 24, fontWeight: 900, letterSpacing: '-0.02em', background: 'var(--grad-heading)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>NCS Presale Dashboard</div>
        <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.35)', fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', marginTop: 6 }}>Network &amp; Cyber Security · 2026</div>
      </div>
      <div style={{ width: 320, padding: 24, borderRadius: 16, background: 'var(--surface-glass)', border: '1px solid var(--border-card)', backdropFilter: 'blur(20px)', display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: '#34d399', fontSize: 11, fontWeight: 800 }}>
          <Icon name="lock" size={13} /> CLOUDFLARE ACCESS
        </div>
        <div style={{ fontSize: 12, color: 'var(--text-body)', lineHeight: 1.55 }}>
          This dashboard is protected. Authenticate with your <strong style={{ color: '#f0f6ff' }}>@ncs.co.th</strong> Google account to continue.
        </div>
        <DS.Button tone="red" fullWidth size="lg" onClick={onEnter} icon={<Icon name="shield" size={15} />}>
          Sign in with Google
        </DS.Button>
        <div style={{ fontSize: 10, color: 'var(--text-disabled)', textAlign: 'center' }}>Session expires after 24h of inactivity</div>
      </div>
    </div>
  );
}

/* ── Presence cluster ───────────────────────────────────── */
function Presence() {
  const online = [
    { name: 'napit.sakunerat@ncs.co.th', mins: 0 },
    { name: 'kanya.wong@ncs.co.th', mins: 1 },
    { name: 'tanawat.p@ncs.co.th', mins: 4 },
  ];
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ position: 'relative' }}>
      <button onClick={() => setOpen(o => !o)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 11px', borderRadius: 8, background: open ? 'rgba(16,185,129,0.15)' : 'rgba(16,185,129,0.08)', border: `1px solid rgba(16,185,129,${open ? 0.45 : 0.2})`, cursor: 'pointer' }}>
        <div style={{ display: 'flex' }}>
          {online.slice(0, 3).map((u, i) => (
            <div key={u.name} style={{ marginLeft: i > 0 ? -6 : 0, border: '1.5px solid rgba(11,17,32,0.9)', borderRadius: '50%', zIndex: 3 - i }}>
              <DS.Avatar name={u.name} size="sm" />
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#10b981', boxShadow: '0 0 6px #10b981' }} className="ncs-pulse-glow" />
          <span style={{ fontSize: 11, fontWeight: 800, color: '#34d399' }}>{online.length}</span>
        </div>
      </button>
      {open && (
        <div style={{ position: 'absolute', top: 'calc(100% + 8px)', right: 0, zIndex: 200, background: 'rgba(11,17,32,0.97)', border: '1px solid rgba(16,185,129,0.25)', borderRadius: 12, padding: '12px 0', minWidth: 230, boxShadow: '0 12px 40px rgba(0,0,0,0.6)' }}>
          <div style={{ padding: '4px 16px 10px', borderBottom: '1px solid rgba(255,255,255,0.06)', fontSize: 11, fontWeight: 800, color: '#34d399', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Online Now · {online.length}</div>
          {online.map(u => (
            <div key={u.name} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 16px' }}>
              <DS.Avatar name={u.name} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: '#f0f6ff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{u.name.split('@')[0].replace(/[._]/g, ' ').replace(/\b\w/g, c => c.toUpperCase())}</div>
                <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.3)' }}>{u.mins === 0 ? 'Just now' : `${u.mins}m ago`}</div>
              </div>
              <div style={{ width: 7, height: 7, borderRadius: '50%', background: u.mins < 2 ? '#10b981' : '#f59e0b' }} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ── App header ─────────────────────────────────────────── */
function AppHeader({ onTab, activeTab, theme, onToggleTheme }) {
  const active = window.PROJECTS.filter(p => p.status === 'Active');
  const activeValue = active.reduce((s, p) => s + p.value, 0);
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', background: 'var(--surface-glass, rgba(11,17,32,0.9))', borderBottom: '1px solid var(--border-brand, rgba(220,38,38,0.25))', boxShadow: 'var(--shadow-header, 0 4px 30px rgba(0,0,0,0.5))' }}>
      <div className="ncs-header-inner" style={{ height: 64, display: 'flex', alignItems: 'center', padding: '0 20px', maxWidth: 1400, margin: '0 auto', gap: 12 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1, minWidth: 0 }}>
          <div style={{ background: '#fff', padding: '6px 8px', borderRadius: 9, flexShrink: 0, boxShadow: '0 2px 8px rgba(0,0,0,0.3)' }}>
            <img src="../../assets/yip-next-logo.png" alt="YIPINTSOI NEXT" style={{ height: 30, display: 'block' }} />
          </div>
          <div>
            <div style={{ fontSize: 18, fontWeight: 900, letterSpacing: '-0.02em', lineHeight: 1.1, background: 'var(--grad-heading)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>NCS Presale Dashboard</div>
            <div style={{ fontSize: 9, color: 'var(--text-faint, rgba(255,255,255,0.35))', fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Network &amp; Cyber Security · 2026</div>
          </div>
          <span style={{ padding: '3px 9px', borderRadius: 6, background: 'rgba(220,38,38,0.15)', border: '1px solid rgba(220,38,38,0.35)', fontSize: 11, fontWeight: 900, color: '#fca5a5', letterSpacing: '0.08em', flexShrink: 0 }}>v6</span>
        </div>

        <div className="ncs-statstrip">
          <DS.StatStrip>
            <DS.StatPill icon="👥" value={window.PRESALES.length} label="Presales" color="#818cf8" />
            <DS.StatPill icon="🤝" value={window.SALES.length} label="Sales" color="#22d3ee" divider />
            <DS.StatPill icon="⚡" value={active.length} label="Active" color="#f87171" divider />
            <DS.StatPill icon="💰" value={baht(activeValue)} label="Value" color="#34d399" divider />
          </DS.StatStrip>
        </div>

        <div className="ncs-actions" style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          <Presence />
          <DS.IconButton aria-label="Toggle theme" onClick={onToggleTheme}>
            <Icon name={theme === 'light' ? 'moon' : 'sun'} size={14} />
          </DS.IconButton>
          <DS.Button tone="emerald" variant={activeTab === 'register' ? 'solid' : 'soft'} size="sm" icon={<Icon name="edit" size={13} />} onClick={() => onTab('register')}><span className="ncs-btn-label">Register</span></DS.Button>
          <DS.Button tone="amber" variant={activeTab === 'update' ? 'solid' : 'soft'} size="sm" icon={<Icon name="refresh-cw" size={13} />} onClick={() => onTab('update')}><span className="ncs-btn-label">Update</span></DS.Button>
          <DS.IconButton aria-label="Refresh"><Icon name="refresh-ccw" size={14} /></DS.IconButton>
        </div>
      </div>
    </header>
  );
}

/* ── Global filter bar ──────────────────────────────────── */
const PRESETS = ['Active', 'At-Risk', 'Stale 30+', 'Won', 'Lost'];
function GlobalFilter({ chips, setChips, query, setQuery }) {
  const addChip = (label) => { if (!chips.includes(label)) setChips([...chips, label]); };
  return (
    <div className="ncs-filter" style={{ background: 'var(--bg-sidebar, rgba(11,17,32,0.97))', borderBottom: '1px solid var(--border-subtle, rgba(255,255,255,0.06))', padding: '10px 24px' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center', marginBottom: 8 }}>
          <span style={{ padding: '4px 8px', borderRadius: 5, fontSize: 8, fontWeight: 900, letterSpacing: '0.18em', textTransform: 'uppercase', background: 'rgba(220,38,38,0.12)', border: '1px solid rgba(220,38,38,0.3)', color: '#fca5a5', whiteSpace: 'nowrap' }}>Global Filter</span>
          <div style={{ flex: 1, minWidth: 260 }}>
            <DS.Input size="sm" icon={<Icon name="search" size={13} />} placeholder="Search NCS, customer, project, presale, sale, vendor…" value={query} onChange={e => setQuery(e.target.value)} />
          </div>
          {PRESETS.map(p => (
            <button key={p} onClick={() => addChip(p)} style={{ padding: '5px 11px', borderRadius: 7, fontSize: 10, fontWeight: 800, cursor: 'pointer', border: '1px solid var(--border-strong, rgba(255,255,255,0.1))', background: 'var(--surface-chip, rgba(255,255,255,0.04))', color: 'var(--text-muted, rgba(255,255,255,0.45))' }}>{p}</button>
          ))}
          <DS.Button tone="red" variant="soft" size="sm">Apply</DS.Button>
          {(chips.length > 0 || query) && <DS.Button tone="neutral" variant="ghost" size="sm" onClick={() => { setChips([]); setQuery(''); }}>Clear</DS.Button>}
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10, alignItems: 'flex-end' }}>
          <DS.Select size="sm" label="Presale" options={window.PRESALES} placeholder="All" onChange={e => e.target.value && addChip('PS: ' + e.target.value)} />
          <DS.Select size="sm" label="Sale" options={window.SALES} placeholder="All" onChange={e => e.target.value && addChip('Sale: ' + e.target.value)} />
          <DS.Select size="sm" label="Group" options={window.GROUPS} placeholder="All" onChange={e => e.target.value && addChip('Grp: ' + e.target.value)} />
          <DS.Select size="sm" label="Stage" options={window.STAGES} placeholder="All" onChange={e => e.target.value && addChip(e.target.value)} />
          <DS.Select size="sm" label="Quarter" options={['Q1 26','Q2 26','Q3 26','Q4 26']} placeholder="All" onChange={e => e.target.value && addChip(e.target.value)} />
        </div>
        {chips.length > 0 && (
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 8 }}>
            {chips.map((c, i) => <DS.FilterChip key={i} onRemove={() => setChips(chips.filter(x => x !== c))}>{c}</DS.FilterChip>)}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Login, AppHeader, GlobalFilter });
