// ─────────────────────────────────────────────
// DEV_AppDetail_Security.jsx
// Security management panel for an app
//
// Loaded in: do-dev/index.html  (before DEV_AppDetail.jsx)
// Used by:   DEV_AppDetail.jsx  as:
//   {tab === 'security' && <DEVSecurity app={app} />}
//
// Sub-sections (sub-tab bar):
//   Login Settings | IP Access | Country Access
// ─────────────────────────────────────────────

function DEVSecurity({ app }) {
  const [sub,     setSub]     = React.useState('login');
  const [loading, setLoading] = React.useState(true);
  const [saving,  setSaving]  = React.useState(false);
  const [saved,   setSaved]   = React.useState(false);
  const [error,   setError]   = React.useState(null);

  // ── Settings state ──
  const [rememberMe,          setRememberMe]          = React.useState(true);
  const [rememberDays,        setRememberDays]        = React.useState(30);
  const [require2fa,          setRequire2fa]          = React.useState('never');
  const [concurrentSessions,  setConcurrentSessions]  = React.useState(true);
  const [ipMode,              setIpMode]              = React.useState('open');
  const [ipWhitelist,         setIpWhitelist]         = React.useState([]);
  const [ipBlacklist,         setIpBlacklist]         = React.useState([]);
  const [countryMode,         setCountryMode]         = React.useState('open');
  const [countryWhitelist,    setCountryWhitelist]    = React.useState([]);
  const [countryBlacklist,    setCountryBlacklist]    = React.useState([]);

  // ── New IP entry state ──
  const [newIp,   setNewIp]   = React.useState('');
  const [newDesc, setNewDesc] = React.useState('');

  // ── New country entry state ──
  const [newCountry, setNewCountry] = React.useState('');

  // ── Load existing settings ──
  React.useEffect(() => {
    apiFetch(`${API_BASE}/v6/dev/security?app=${app.app_id}`)
      .then(r => r.json())
      .then(data => {
        if (data.status === 'ok' && data.security) {
          const s = data.security;
          setRememberMe(s.remember_me !== false);
          setRememberDays(Number(s.remember_days) || 30);
          setRequire2fa(s.require_2fa || 'never');
          setConcurrentSessions(s.concurrent_sessions !== false);
          setIpMode(s.ip_mode || 'open');
          setIpWhitelist(Array.isArray(s.ip_whitelist) ? s.ip_whitelist : []);
          setIpBlacklist(Array.isArray(s.ip_blacklist) ? s.ip_blacklist : []);
          setCountryMode(s.country_mode || 'open');
          setCountryWhitelist(Array.isArray(s.country_whitelist) ? s.country_whitelist : []);
          setCountryBlacklist(Array.isArray(s.country_blacklist) ? s.country_blacklist : []);
        }
      })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, [app.app_id]);

  // ── Save all settings ──
  async function handleSave() {
    setSaving(true); setSaved(false); setError(null);
    try {
      const res = await apiFetch(`${API_BASE}/v6/dev/security?app=${app.app_id}`, {
        method: 'POST',
        body: JSON.stringify({
          remember_me:         rememberMe,
          remember_days:       rememberDays,
          require_2fa:         require2fa,
          concurrent_sessions: concurrentSessions,
          ip_mode:             ipMode,
          ip_whitelist:        ipWhitelist,
          ip_blacklist:        ipBlacklist,
          country_mode:        countryMode,
          country_whitelist:   countryWhitelist,
          country_blacklist:   countryBlacklist,
        }),
      });
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch(err) { setError(err.message); }
    setSaving(false);
  }

  // ── IP helpers ──
  const activeIpList    = ipMode === 'whitelist' ? ipWhitelist : ipBlacklist;
  const setActiveIpList = ipMode === 'whitelist' ? setIpWhitelist : setIpBlacklist;

  function addIp() {
    const ip = newIp.trim();
    if (!ip) return;
    if (activeIpList.some(e => e.ip === ip)) { setNewIp(''); setNewDesc(''); return; }
    setActiveIpList(prev => [...prev, { ip, desc: newDesc.trim() }]);
    setNewIp(''); setNewDesc('');
  }
  function removeIp(ip) { setActiveIpList(prev => prev.filter(e => e.ip !== ip)); }

  // ── Country helpers ──
  const activeCountryList    = countryMode === 'whitelist' ? countryWhitelist : countryBlacklist;
  const setActiveCountryList = countryMode === 'whitelist' ? setCountryWhitelist : setCountryBlacklist;

  function addCountry() {
    const code = newCountry.trim().toUpperCase();
    if (!code || activeCountryList.includes(code)) { setNewCountry(''); return; }
    setActiveCountryList(prev => [...prev, code]);
    setNewCountry('');
  }
  function removeCountry(code) { setActiveCountryList(prev => prev.filter(c => c !== code)); }

  if (loading) return <div style={{ padding:40, color:'#94a3b8', textAlign:'center' }}>Loading…</div>;

  const SUB_TABS = [
    { id:'login',   label:'🔐 Login Settings' },
    { id:'ip',      label:'🛡 IP Access'       },
    { id:'country', label:'🌍 Country Access'  },
  ];

  return (
    <div>
      {/* Sub-tab bar */}
      <div style={{ display:'flex', gap:0, borderBottom:'2px solid #e2e8f0', marginBottom:24 }}>
        {SUB_TABS.map(t => (
          <button key={t.id}
            onClick={() => setSub(t.id)}
            style={{
              background:'none', border:'none', borderBottom: sub === t.id ? '2px solid #0f1923' : '2px solid transparent',
              padding:'8px 18px', fontSize:13, fontWeight: sub === t.id ? 600 : 400,
              color: sub === t.id ? '#0f1923' : '#64748b',
              cursor:'pointer', fontFamily:'inherit', marginBottom:'-2px',
            }}>
            {t.label}
          </button>
        ))}
      </div>

      {error && <div style={SS.error}>{error}</div>}

      {/* ══ LOGIN SETTINGS ══ */}
      {sub === 'login' && (
        <div style={SS.grid}>

          {/* Remember Me */}
          <div style={SS.card}>
            <div style={SS.cardHeader}>Remember Me</div>
            <div style={SS.row}>
              <div>
                <div style={SS.settingLabel}>Allow "Remember Me"</div>
                <div style={SS.settingDesc}>Users can stay logged in across sessions</div>
              </div>
              <button
                onClick={() => setRememberMe(v => !v)}
                style={{ ...SS.toggle, background: rememberMe ? '#0f1923' : '#e2e8f0' }}>
                <div style={{ ...SS.toggleThumb, transform: rememberMe ? 'translateX(20px)' : 'translateX(2px)' }} />
              </button>
            </div>
            {rememberMe && (
              <div style={{ marginTop:16 }}>
                <div style={SS.settingLabel}>Duration</div>
                <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginTop:6 }}>
                  {[
                    { days:7,   label:'1 Week'   },
                    { days:30,  label:'1 Month'  },
                    { days:90,  label:'3 Months' },
                    { days:180, label:'6 Months' },
                    { days:365, label:'1 Year'   },
                  ].map(o => (
                    <button key={o.days} onClick={() => setRememberDays(o.days)}
                      style={{ ...SS.pill, background: rememberDays === o.days ? '#0f1923' : '#f1f5f9',
                               color: rememberDays === o.days ? '#fff' : '#374151' }}>
                      {o.label}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Two-Factor Authentication */}
          <div style={SS.card}>
            <div style={SS.cardHeader}>Two-Factor Authentication (2FA)</div>
            {[
              { v:'never',           l:'Never required',                  d:'Password login only. No 2FA.' },
              { v:'whitelist_exempt',l:'Whitelist IP exempt',             d:'2FA required unless logging in from a whitelisted IP.' },
              { v:'always',          l:'Always required',                 d:'Every login must verify with 2FA code.' },
            ].map(o => (
              <div key={o.v}
                onClick={() => setRequire2fa(o.v)}
                style={{ ...SS.radioRow, borderColor: require2fa === o.v ? '#0f1923' : '#e2e8f0',
                         background: require2fa === o.v ? '#f8fafc' : '#fff' }}>
                <div style={{ ...SS.radioCircle, borderColor: require2fa === o.v ? '#0f1923' : '#cbd5e1' }}>
                  {require2fa === o.v && <div style={SS.radioDot} />}
                </div>
                <div>
                  <div style={SS.radioLabel}>{o.l}</div>
                  <div style={SS.radioDesc}>{o.d}</div>
                </div>
              </div>
            ))}
          </div>

          {/* Concurrent Sessions */}
          <div style={SS.card}>
            <div style={SS.cardHeader}>Concurrent Sessions</div>
            <div style={SS.row}>
              <div>
                <div style={SS.settingLabel}>Allow multiple simultaneous logins</div>
                <div style={SS.settingDesc}>
                  {concurrentSessions
                    ? 'One account can be logged in from multiple devices at once.'
                    : 'A new login will invalidate all previous sessions for that user.'}
                </div>
              </div>
              <button
                onClick={() => setConcurrentSessions(v => !v)}
                style={{ ...SS.toggle, background: concurrentSessions ? '#0f1923' : '#e2e8f0' }}>
                <div style={{ ...SS.toggleThumb, transform: concurrentSessions ? 'translateX(20px)' : 'translateX(2px)' }} />
              </button>
            </div>
            {!concurrentSessions && (
              <div style={{ marginTop:12, padding:'10px 12px', background:'#fefce8', borderRadius:7, fontSize:12, color:'#92400e', border:'1px solid #fde68a' }}>
                ⚠️ This prevents credential sharing — if user A logs in while user B is already logged in with the same account, user B is immediately logged out.
              </div>
            )}
          </div>

        </div>
      )}

      {/* ══ IP ACCESS ══ */}
      {sub === 'ip' && (
        <div style={SS.grid}>

          {/* IP Mode */}
          <div style={SS.card}>
            <div style={SS.cardHeader}>Access Mode</div>
            {[
              { v:'open',      l:'Open',      d:'No IP restrictions — anyone can access this app.' },
              { v:'whitelist', l:'Whitelist', d:'Only allow logins from IPs in the list below.' },
              { v:'blacklist', l:'Blacklist', d:'Block logins from IPs in the list. Allow everything else.' },
            ].map(o => (
              <div key={o.v}
                onClick={() => setIpMode(o.v)}
                style={{ ...SS.radioRow, borderColor: ipMode === o.v ? '#0f1923' : '#e2e8f0',
                         background: ipMode === o.v ? '#f8fafc' : '#fff' }}>
                <div style={{ ...SS.radioCircle, borderColor: ipMode === o.v ? '#0f1923' : '#cbd5e1' }}>
                  {ipMode === o.v && <div style={SS.radioDot} />}
                </div>
                <div>
                  <div style={SS.radioLabel}>{o.l}</div>
                  <div style={SS.radioDesc}>{o.d}</div>
                </div>
              </div>
            ))}
          </div>

          {/* IP List */}
          {ipMode !== 'open' && (
            <div style={{ ...SS.card, gridColumn: 'span 2' }}>
              <div style={SS.cardHeader}>
                {ipMode === 'whitelist' ? '✅ Whitelist' : '🚫 Blacklist'} — IP Addresses
                {activeIpList.length > 0 && <span style={{ marginLeft:8, fontWeight:400, color:'#64748b' }}>({activeIpList.length})</span>}
              </div>

              {/* Add new IP */}
              <div style={{ display:'flex', gap:8, marginBottom:16, flexWrap:'wrap' }}>
                <input
                  value={newIp}
                  onChange={e => setNewIp(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && addIp()}
                  placeholder="IP address or CIDR (e.g. 208.67.224.30 or 208.67.0.0/16)"
                  style={{ ...SS.input, flex:2, minWidth:220 }}
                />
                <input
                  value={newDesc}
                  onChange={e => setNewDesc(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && addIp()}
                  placeholder="Description (optional)"
                  style={{ ...SS.input, flex:1, minWidth:150 }}
                />
                <button onClick={addIp} style={SS.addBtn}>+ Add</button>
              </div>

              {/* IP list table */}
              {activeIpList.length === 0
                ? <div style={SS.empty}>No IPs added yet.</div>
                : (
                  <div style={SS.listTable}>
                    <div style={SS.listHeader}>
                      <span>IP Address</span>
                      <span>Description</span>
                      <span />
                    </div>
                    {activeIpList.map((entry, i) => (
                      <div key={i} style={SS.listRow}>
                        <span style={{ fontFamily:'DM Mono, monospace', fontSize:13 }}>{entry.ip}</span>
                        <span style={{ fontSize:12, color:'#64748b' }}>{entry.desc || '—'}</span>
                        <button onClick={() => removeIp(entry.ip)} style={SS.deleteBtn}>✕</button>
                      </div>
                    ))}
                  </div>
                )
              }
              <div style={{ fontSize:11, color:'#94a3b8', marginTop:10 }}>
                Supports single IPs (208.67.224.30) and CIDR ranges (208.67.0.0/16)
              </div>
            </div>
          )}
        </div>
      )}

      {/* ══ COUNTRY ACCESS ══ */}
      {sub === 'country' && (
        <div style={SS.grid}>

          {/* Country Mode */}
          <div style={SS.card}>
            <div style={SS.cardHeader}>Access Mode</div>
            {[
              { v:'open',      l:'Open',      d:'No country restrictions.' },
              { v:'whitelist', l:'Whitelist', d:'Only allow logins from countries in the list below.' },
              { v:'blacklist', l:'Blacklist', d:'Block logins from countries in the list. Allow everything else.' },
            ].map(o => (
              <div key={o.v}
                onClick={() => setCountryMode(o.v)}
                style={{ ...SS.radioRow, borderColor: countryMode === o.v ? '#0f1923' : '#e2e8f0',
                         background: countryMode === o.v ? '#f8fafc' : '#fff' }}>
                <div style={{ ...SS.radioCircle, borderColor: countryMode === o.v ? '#0f1923' : '#cbd5e1' }}>
                  {countryMode === o.v && <div style={SS.radioDot} />}
                </div>
                <div>
                  <div style={SS.radioLabel}>{o.l}</div>
                  <div style={SS.radioDesc}>{o.d}</div>
                </div>
              </div>
            ))}
          </div>

          {/* Country List */}
          {countryMode !== 'open' && (
            <div style={{ ...SS.card, gridColumn: 'span 2' }}>
              <div style={SS.cardHeader}>
                {countryMode === 'whitelist' ? '✅ Allowed Countries' : '🚫 Blocked Countries'}
                {activeCountryList.length > 0 && <span style={{ marginLeft:8, fontWeight:400, color:'#64748b' }}>({activeCountryList.length})</span>}
              </div>

              {/* Add country */}
              <div style={{ display:'flex', gap:8, marginBottom:16 }}>
                <select
                  value={newCountry}
                  onChange={e => setNewCountry(e.target.value)}
                  style={{ ...SS.input, flex:1 }}>
                  <option value="">— Select a country —</option>
                  {COUNTRIES.map(c => (
                    <option key={c.code} value={c.code}>{c.flag} {c.name} ({c.code})</option>
                  ))}
                </select>
                <button onClick={addCountry} style={SS.addBtn}>+ Add</button>
              </div>

              {/* Country chips */}
              {activeCountryList.length === 0
                ? <div style={SS.empty}>No countries added yet.</div>
                : (
                  <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                    {activeCountryList.map(code => {
                      const c = COUNTRIES.find(x => x.code === code);
                      return (
                        <div key={code} style={SS.chip}>
                          <span>{c?.flag || '🌐'} {code}</span>
                          <button onClick={() => removeCountry(code)} style={SS.chipX}>✕</button>
                        </div>
                      );
                    })}
                  </div>
                )
              }
            </div>
          )}
        </div>
      )}

      {/* ── Save bar ── */}
      <div style={SS.saveBar}>
        {saved  && <span style={{ fontSize:13, color:'#059669', fontWeight:600 }}>✓ Settings saved</span>}
        {error  && <span style={{ fontSize:13, color:'#dc2626' }}>{error}</span>}
        <button onClick={handleSave} disabled={saving} style={SS.saveBtn}>
          {saving ? 'Saving…' : 'Save Security Settings'}
        </button>
      </div>
    </div>
  );
}

// ── Common country list ──────────────────────
const COUNTRIES = [
  { code:'US', name:'United States',  flag:'🇺🇸' },
  { code:'CA', name:'Canada',         flag:'🇨🇦' },
  { code:'GB', name:'United Kingdom', flag:'🇬🇧' },
  { code:'AU', name:'Australia',      flag:'🇦🇺' },
  { code:'NZ', name:'New Zealand',    flag:'🇳🇿' },
  { code:'IE', name:'Ireland',        flag:'🇮🇪' },
  { code:'DE', name:'Germany',        flag:'🇩🇪' },
  { code:'FR', name:'France',         flag:'🇫🇷' },
  { code:'NL', name:'Netherlands',    flag:'🇳🇱' },
  { code:'ES', name:'Spain',          flag:'🇪🇸' },
  { code:'IT', name:'Italy',          flag:'🇮🇹' },
  { code:'SE', name:'Sweden',         flag:'🇸🇪' },
  { code:'NO', name:'Norway',         flag:'🇳🇴' },
  { code:'DK', name:'Denmark',        flag:'🇩🇰' },
  { code:'CH', name:'Switzerland',    flag:'🇨🇭' },
  { code:'JP', name:'Japan',          flag:'🇯🇵' },
  { code:'KR', name:'South Korea',    flag:'🇰🇷' },
  { code:'SG', name:'Singapore',      flag:'🇸🇬' },
  { code:'IN', name:'India',          flag:'🇮🇳' },
  { code:'BR', name:'Brazil',         flag:'🇧🇷' },
  { code:'MX', name:'Mexico',         flag:'🇲🇽' },
  { code:'CN', name:'China',          flag:'🇨🇳' },
  { code:'RU', name:'Russia',         flag:'🇷🇺' },
  { code:'UA', name:'Ukraine',        flag:'🇺🇦' },
  { code:'PL', name:'Poland',         flag:'🇵🇱' },
  { code:'ZA', name:'South Africa',   flag:'🇿🇦' },
  { code:'NG', name:'Nigeria',        flag:'🇳🇬' },
  { code:'IL', name:'Israel',         flag:'🇮🇱' },
  { code:'AE', name:'UAE',            flag:'🇦🇪' },
  { code:'SA', name:'Saudi Arabia',   flag:'🇸🇦' },
];

// ── Styles ───────────────────────────────────
const SS = {
  grid:        { display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(300px, 1fr))', gap:20, marginBottom:24 },
  card:        { background:'#fff', borderRadius:12, border:'1px solid #e2e8f0', padding:'20px 22px' },
  cardHeader:  { fontSize:12, fontWeight:700, color:'#0f1923', textTransform:'uppercase',
                 letterSpacing:'0.05em', marginBottom:16, paddingBottom:12, borderBottom:'1px solid #f1f5f9' },
  row:         { display:'flex', alignItems:'center', justifyContent:'space-between', gap:12 },
  settingLabel:{ fontSize:13, fontWeight:600, color:'#0f1923', marginBottom:3 },
  settingDesc: { fontSize:12, color:'#94a3b8', lineHeight:1.4 },
  toggle:      { width:44, height:24, borderRadius:12, border:'none', cursor:'pointer',
                 position:'relative', transition:'background 0.2s', flexShrink:0, padding:0 },
  toggleThumb: { position:'absolute', top:2, width:20, height:20, borderRadius:10,
                 background:'#fff', boxShadow:'0 1px 3px rgba(0,0,0,0.2)', transition:'transform 0.2s' },
  radioRow:    { display:'flex', gap:12, alignItems:'flex-start', padding:'12px 14px',
                 borderRadius:8, border:'1.5px solid #e2e8f0', marginBottom:8, cursor:'pointer',
                 transition:'border-color 0.15s, background 0.15s' },
  radioCircle: { width:18, height:18, borderRadius:9, border:'2px solid #cbd5e1', flexShrink:0,
                 display:'flex', alignItems:'center', justifyContent:'center', marginTop:2 },
  radioDot:    { width:8, height:8, borderRadius:4, background:'#0f1923' },
  radioLabel:  { fontSize:13, fontWeight:600, color:'#0f1923', marginBottom:2 },
  radioDesc:   { fontSize:12, color:'#94a3b8', lineHeight:1.4 },
  pill:        { padding:'5px 12px', borderRadius:20, border:'1.5px solid #e2e8f0', fontSize:12,
                 fontWeight:500, cursor:'pointer', fontFamily:'DM Sans, sans-serif',
                 transition:'background 0.15s, color 0.15s' },
  input:       { padding:'8px 12px', border:'1.5px solid #e2e8f0', borderRadius:7, fontSize:13,
                 fontFamily:'DM Sans, sans-serif', outline:'none', color:'#0f1923', background:'#fff' },
  addBtn:      { padding:'8px 16px', background:'#0f1923', color:'#fff', border:'none',
                 borderRadius:7, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'DM Sans, sans-serif',
                 whiteSpace:'nowrap' },
  listTable:   { border:'1px solid #e2e8f0', borderRadius:8, overflow:'hidden' },
  listHeader:  { display:'grid', gridTemplateColumns:'1fr 1fr 40px', gap:8, padding:'8px 14px',
                 background:'#f8fafc', fontSize:11, fontWeight:700, color:'#64748b',
                 textTransform:'uppercase', letterSpacing:'0.05em' },
  listRow:     { display:'grid', gridTemplateColumns:'1fr 1fr 40px', gap:8, padding:'10px 14px',
                 borderTop:'1px solid #f1f5f9', alignItems:'center' },
  deleteBtn:   { background:'none', border:'none', color:'#dc2626', cursor:'pointer',
                 fontSize:14, padding:'2px 6px', borderRadius:4, fontFamily:'DM Sans, sans-serif' },
  chip:        { display:'flex', alignItems:'center', gap:6, padding:'5px 10px',
                 background:'#f1f5f9', borderRadius:20, fontSize:13, fontWeight:500, color:'#0f1923' },
  chipX:       { background:'none', border:'none', color:'#94a3b8', cursor:'pointer',
                 fontSize:12, padding:0, lineHeight:1, fontFamily:'DM Sans, sans-serif' },
  empty:       { padding:'16px', textAlign:'center', color:'#94a3b8', fontSize:13,
                 border:'1px dashed #e2e8f0', borderRadius:8 },
  saveBar:     { display:'flex', alignItems:'center', justifyContent:'flex-end', gap:16,
                 padding:'16px 0', borderTop:'1px solid #f1f5f9', marginTop:8 },
  saveBtn:     { background:'#0f1923', color:'#fff', border:'none', borderRadius:7,
                 padding:'10px 24px', fontSize:13, fontWeight:600, cursor:'pointer',
                 fontFamily:'DM Sans, sans-serif' },
  error:       { background:'#fef2f2', color:'#dc2626', padding:'10px 14px', borderRadius:8,
                 fontSize:12, marginBottom:16, border:'1px solid #fecaca' },
};
