// admin-users.jsx
const { useState: useStateU } = React;

function UserSlideOver({ user, onClose }) {
  const [tab, setTab] = useStateU('overview');
  const [flags, setFlags] = useStateU({ ...user.flags });
  const [saved, setSaved] = useStateU(false);
  const [note, setNote] = useStateU('');
  const [syncOne, setSyncOne] = useStateU('idle'); // idle | syncing | done | error
  const { features } = window.MOCK;
  const margin = user.mrr > 0 ? ((1 - user.api_cost / user.mrr) * 100).toFixed(0) : 100;
  const saveFlags = () => { setSaved(true); setTimeout(() => setSaved(false), 2000); };

  return (
    <>
      <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(26,43,59,0.35)', zIndex:50, backdropFilter:'blur(2px)' }} />
      <div style={{ position:'fixed', top:0, right:0, bottom:0, width:'min(460px,100vw)', background:'#fff', boxShadow:'-24px 0 60px rgba(0,0,0,0.08)', zIndex:51, display:'flex', flexDirection:'column', animation:'slideIn 0.22s ease-out' }}>

        {/* Header */}
        <div style={{ padding:'20px 24px', borderBottom:'1px solid #E5E7EB', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
          <div style={{ width:38, height:38, borderRadius:'50%', background:'#FFF7ED', display:'flex', alignItems:'center', justifyContent:'center', fontSize:15, fontWeight:800, color:'#F97316', flexShrink:0 }}>
            {user.name[0]}
          </div>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:14, fontWeight:800, color:'#1A2B3B' }}>{user.name}</div>
            <div style={{ fontSize:11, color:'#9CA3AF', marginTop:1 }}>{user.email}</div>
          </div>
          <PlanBadge plan={user.plan} />
          <button onClick={onClose} style={{ padding:6, border:'none', background:'none', cursor:'pointer', display:'flex' }}>
            <Icon name="X" size={16} color="#9CA3AF" />
          </button>
        </div>

        {/* Tabs */}
        <div style={{ padding:'12px 24px', borderBottom:'1px solid #F3F4F6', flexShrink:0 }}>
          <Tabs options={['overview','agency','features','billing','support']} value={tab} onChange={setTab} />
        </div>

        {/* Body */}
        <div style={{ flex:1, overflowY:'auto', padding:24 }}>

          {tab === 'overview' && (
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8 }}>
                {[{l:'MRR',v:`$${user.mrr}`,c:'#10B981'},{l:'API Cost',v:`$${user.api_cost}`,c:'#F43F5E'},{l:'Margin',v:user.mrr>0?`${margin}%`:'—',c:'#3B82F6'}].map(m => (
                  <div key={m.l} style={{ background:'#F9FAFB', borderRadius:10, padding:'12px 10px', textAlign:'center' }}>
                    <div style={{ fontSize:17, fontWeight:900, color:m.c }}>{m.v}</div>
                    <div style={{ fontSize:9, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:'0.07em', marginTop:3 }}>{m.l}</div>
                  </div>
                ))}
              </div>
              <div style={{ background:'#F9FAFB', borderRadius:10, padding:'4px 14px' }}>
                {[
                  {l:'Plan',      v:user.plan.charAt(0).toUpperCase()+user.plan.slice(1)},
                  {l:'Status',    v:user.status},
                  {l:'Joined',    v:new Date(user.joined).toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'})},
                  {l:'Company',   v:user.company||'—'},
                  {l:'Funnels',      v:user.funnels},
                  {l:'Leads (mo)',   v:(user.leads_this_mo||0).toLocaleString()},
                  {l:'Credits',      v:`${(user.credits_used||0).toLocaleString()} / ${(user.credits_total||0).toLocaleString()}`},
                  {l:'Workspace',    v:user.workspace},
                  {l:'LTV',          v:`$${user.lifetime_value.toLocaleString()}`},
                ].map(({l,v},i,arr) => (
                  <div key={l} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'9px 0', borderBottom:i<arr.length-1?'1px solid #E5E7EB':'none', fontSize:13 }}>
                    <span style={{ color:'#9CA3AF', fontWeight:500 }}>{l}</span>
                    <span style={{ color:'#1A2B3B', fontWeight:700 }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === 'agency' && (() => {
            const ap = user.agency_profile || {};
            const hasAny = ap && (
              (Array.isArray(ap.tools) && ap.tools.length) ||
              ap.tools_other || ap.lead_gen_spend ||
              (Array.isArray(ap.client_sources) && ap.client_sources.length) ||
              ap.client_count || ap.funnel_count || ap.main_focus
            );
            const toolsCombined = [
              ...(Array.isArray(ap.tools) ? ap.tools : []),
              ...(ap.tools_other ? [ap.tools_other] : []),
            ];
            const renderChips = (arr) => arr.length === 0
              ? <span style={{ color:'#9CA3AF', fontWeight:500, fontSize:13 }}>—</span>
              : (
                <div style={{ display:'flex', flexWrap:'wrap', gap:6, justifyContent:'flex-end' }}>
                  {arr.map(v => (
                    <span key={v} style={{ fontSize:11, fontWeight:700, color:'#1A2B3B', background:'#FFF7ED', border:'1px solid #FED7AA', padding:'3px 8px', borderRadius:999 }}>{v}</span>
                  ))}
                </div>
              );
            return (
              <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
                <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                  <span style={{ fontSize:11, fontWeight:800, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:'0.07em' }}>Onboarding</span>
                  {user.onboarding_skipped ? (
                    <span style={{ fontSize:10, fontWeight:800, color:'#92400E', background:'#FEF3C7', padding:'2px 8px', borderRadius:999 }}>SKIPPED</span>
                  ) : user.onboarding_completed ? (
                    <span style={{ fontSize:10, fontWeight:800, color:'#065F46', background:'#D1FAE5', padding:'2px 8px', borderRadius:999 }}>COMPLETED</span>
                  ) : (
                    <span style={{ fontSize:10, fontWeight:800, color:'#9CA3AF', background:'#F3F4F6', padding:'2px 8px', borderRadius:999 }}>PENDING</span>
                  )}
                </div>
                {!hasAny ? (
                  <div style={{ background:'#F9FAFB', border:'1px dashed #E5E7EB', borderRadius:10, padding:'20px 14px', textAlign:'center', fontSize:12, color:'#9CA3AF' }}>
                    {user.onboarding_skipped ? 'User skipped agency profiling.' : 'No agency profile data captured yet.'}
                  </div>
                ) : (
                  <div style={{ background:'#F9FAFB', borderRadius:10, padding:'4px 14px' }}>
                    {[
                      { l:'Tools',          v:renderChips(toolsCombined) },
                      { l:'Lead Gen Spend', v:ap.lead_gen_spend || '—' },
                      { l:'Client Sources', v:renderChips(Array.isArray(ap.client_sources) ? ap.client_sources : []) },
                      { l:'Clients',        v:ap.client_count !== '' && ap.client_count != null ? ap.client_count : '—' },
                      { l:'Funnels',        v:ap.funnel_count !== '' && ap.funnel_count != null ? ap.funnel_count : '—' },
                      { l:'Main Focus',     v:ap.main_focus || '—' },
                    ].map(({l,v},i,arr) => (
                      <div key={l} style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:14, padding:'10px 0', borderBottom:i<arr.length-1?'1px solid #E5E7EB':'none', fontSize:13 }}>
                        <span style={{ color:'#9CA3AF', fontWeight:500, flexShrink:0 }}>{l}</span>
                        <span style={{ color:'#1A2B3B', fontWeight:700, textAlign:'right', maxWidth:'70%' }}>{v}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })()}

          {tab === 'features' && (
            <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
              <div style={{ fontSize:11, color:'#9CA3AF', marginBottom:14 }}>Toggle features for this workspace.</div>
              {features.map((f,i) => (
                <div key={f.key} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'11px 0', borderBottom:i<features.length-1?'1px solid #F3F4F6':'none' }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:600, color:'#1A2B3B' }}>{f.label}</div>
                    <div style={{ fontSize:11, color:'#9CA3AF', marginTop:1 }}>{f.desc}</div>
                  </div>
                  <Toggle on={flags[f.key]} onClick={() => setFlags(p => ({...p,[f.key]:!p[f.key]}))} />
                </div>
              ))}
              <Btn variant="primary" onClick={saveFlags} style={{ marginTop:16, width:'100%', justifyContent:'center' }}>
                <Icon name="Save" size={13} color="#fff" />{saved?'Saved!':'Save Changes'}
              </Btn>
            </div>
          )}

          {tab === 'billing' && (
            <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
              <div style={{ background:'#F9FAFB', borderRadius:10, padding:'4px 14px' }}>
                {[
                  {l:'Plan',        v:user.plan.charAt(0).toUpperCase()+user.plan.slice(1)},
                  {l:'Status',      v:user.status},
                  {l:'Monthly',     v:user.mrr>0?`$${user.mrr}/mo`:'—'},
                  {l:'Next Billing',v:user.next_billing?new Date(user.next_billing).toLocaleDateString():'—'},
                  {l:'LTV',         v:`$${user.lifetime_value.toLocaleString()}`},
                ].map(({l,v},i,arr) => (
                  <div key={l} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'9px 0', borderBottom:i<arr.length-1?'1px solid #E5E7EB':'none', fontSize:13 }}>
                    <span style={{ color:'#9CA3AF', fontWeight:500 }}>{l}</span>
                    <span style={{ color:'#1A2B3B', fontWeight:700 }}>{v}</span>
                  </div>
                ))}
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                <Btn variant="secondary" style={{ width:'100%', justifyContent:'center' }}>Upgrade Plan</Btn>
                <Btn variant="secondary" style={{ width:'100%', justifyContent:'center' }}>Apply Coupon</Btn>
                <Btn variant="secondary" style={{ width:'100%', justifyContent:'center' }}>Extend Trial by 7 Days</Btn>
                <Btn variant="danger"    style={{ width:'100%', justifyContent:'center', marginTop:4 }}>Cancel Subscription</Btn>
              </div>
            </div>
          )}

          {tab === 'support' && (
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:'0.07em', marginBottom:4 }}>Quick Actions</div>
              {[
                {l:'Send Password Reset',  d:'Email a reset link now',         v:'secondary'},
                {l:'Resend Welcome Email', d:'Trigger onboarding sequence',    v:'secondary'},
                {l:'Extend Trial',         d:'Add 7 days to trial',            v:'secondary'},
                {l:'View Activity Log',    d:'See funnel visits & events',     v:'secondary'},
                {l:'Suspend Account',      d:'Block access immediately',       v:'danger'},
              ].map(({l,d,v}) => (
                <button key={l} style={{ display:'flex', flexDirection:'column', alignItems:'flex-start', gap:2, padding:'10px 14px', borderRadius:8, border:v==='danger'?'1px solid #FECDD3':'1px solid #E5E7EB', background:v==='danger'?'#FFF1F2':'#F9FAFB', cursor:'pointer', width:'100%', fontFamily:'inherit', textAlign:'left' }}>
                  <span style={{ fontSize:13, fontWeight:700, color:v==='danger'?'#F43F5E':'#1A2B3B' }}>{l}</span>
                  <span style={{ fontSize:11, color:'#9CA3AF' }}>{d}</span>
                </button>
              ))}
              <button
                onClick={async () => {
                  if (syncOne === 'syncing') return;
                  setSyncOne('syncing');
                  try {
                    await syncUserToResend(user);
                    setSyncOne('done');
                    setTimeout(() => setSyncOne('idle'), 3000);
                  } catch(e) {
                    setSyncOne('error');
                    setTimeout(() => setSyncOne('idle'), 3000);
                  }
                }}
                style={{
                  display:'flex', flexDirection:'column', alignItems:'flex-start', gap:2,
                  padding:'10px 14px', borderRadius:8,
                  border: syncOne==='done' ? '1px solid #6EE7B7' : '1px solid #E5E7EB',
                  background: syncOne==='done' ? '#D1FAE5' : syncOne==='syncing' ? '#FFF7ED' : '#F9FAFB',
                  cursor: syncOne==='syncing' ? 'default' : 'pointer', width:'100%', fontFamily:'inherit', textAlign:'left',
                }}>
                <span style={{ fontSize:13, fontWeight:700, color: syncOne==='done' ? '#065F46' : syncOne==='error' ? '#F43F5E' : '#1A2B3B' }}>
                  {syncOne==='syncing' ? 'Syncing…' : syncOne==='done' ? '✓ Synced to Resend' : syncOne==='error' ? 'Sync failed' : 'Sync to Resend'}
                </span>
                <span style={{ fontSize:11, color:'#9CA3AF' }}>
                  {syncOne==='done' ? 'Contact updated in WiseFunnel Users audience' : 'Push this contact to Resend audience'}
                </span>
              </button>
              <div style={{ marginTop:6 }}>
                <div style={{ fontSize:11, fontWeight:700, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:'0.07em', marginBottom:8 }}>Internal Note</div>
                <textarea value={note} onChange={e=>setNote(e.target.value)} placeholder="Add a note about this customer…"
                  style={{ width:'100%', padding:'10px 12px', border:'1px solid #E5E7EB', borderRadius:8, fontFamily:'inherit', fontSize:13, color:'#1A2B3B', resize:'none', outline:'none', lineHeight:1.5 }} rows={3} />
                <Btn variant="primary" style={{ marginTop:8, width:'100%', justifyContent:'center' }}>Save Note</Btn>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

const RESEND_AUDIENCE_ID = 'b59cb437-feec-4eab-b898-072d65c8aa5c';

async function syncUserToResend(u) {
  const db = window.supabase.createClient(
    window.SUPABASE_URL || 'https://iwvlmpgeodctctmaacja.supabase.co',
    window.SUPABASE_ANON_KEY || 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Iml3dmxtcGdlb2RjdGN0bWFhY2phIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjYwMzY3MTUsImV4cCI6MjA4MTYxMjcxNX0.hMs9OGPTdhPAs0lSKzDWE1Cc-K27NoW11--niolkoWY'
  );
  const nameParts = (u.name || '').trim().split(' ');
  const firstName = nameParts[0] || '';
  const lastName  = nameParts.slice(1).join(' ') || undefined;
  return db.functions.invoke('resend-proxy', {
    body: {
      op:         'upsertContact',
      audienceId: RESEND_AUDIENCE_ID,
      email:      u.email,
      firstName,
      lastName,
      properties: {
        plan_type:            u.raw_plan_type  || u.plan   || 'Free',
        subscription_status:  u.raw_sub_status || u.status || 'none',
        onboarding_completed: String(u.onboarding_completed ?? false),
      },
    },
  });
}

function UsersPage() {
  const [search, setSearch] = useStateU('');
  const [planFilter, setPlanFilter] = useStateU('all');
  const [selected, setSelected] = useStateU(null);
  const [syncState, setSyncState] = useStateU('idle'); // idle | syncing | done | error
  const [syncProgress, setSyncProgress] = useStateU({ done: 0, total: 0 });
  const { users } = window.MOCK;

  const filtered = users.filter(u => {
    const q = search.toLowerCase();
    const ms = !q || u.email.includes(q) || u.name.toLowerCase().includes(q) || u.plan.includes(q) || (u.company||'').toLowerCase().includes(q);
    const mp = planFilter==='all' || u.plan===planFilter;
    return ms && mp;
  });

  const handleSyncAll = async () => {
    if (syncState === 'syncing') return;
    setSyncState('syncing');
    setSyncProgress({ done: 0, total: users.length });
    let done = 0;
    for (const u of users) {
      try { await syncUserToResend(u); } catch(e) { /* continue on individual failure */ }
      done++;
      setSyncProgress({ done, total: users.length });
    }
    setSyncState('done');
    setTimeout(() => setSyncState('idle'), 4000);
  };

  const syncLabel = syncState === 'syncing'
    ? `Syncing… ${syncProgress.done}/${syncProgress.total}`
    : syncState === 'done'
    ? `✓ Synced ${syncProgress.total}`
    : '↑ Sync All → Resend';

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      <div style={{ display:'flex', gap:10, flexWrap:'wrap', alignItems:'center' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8, background:'#fff', border:'1px solid #E5E7EB', borderRadius:9, padding:'7px 12px', flex:1, minWidth:180 }}>
          <Icon name="Search" size={13} color="#9CA3AF" />
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search by name, email or plan…"
            style={{ border:'none', outline:'none', fontFamily:'inherit', fontSize:13, color:'#1A2B3B', background:'transparent', flex:1 }}/>
          {search && <button onClick={()=>setSearch('')} style={{ border:'none', background:'none', cursor:'pointer', padding:0, display:'flex' }}><Icon name="X" size={12} color="#9CA3AF"/></button>}
        </div>
        <Tabs
          options={[{label:'All',value:'all'},{label:'Scale',value:'scale'},{label:'Growth',value:'growth'},{label:'Lite',value:'lite'},{label:'Trial',value:'trial'}]}
          value={planFilter} onChange={setPlanFilter}
        />
        <button onClick={handleSyncAll} disabled={syncState==='syncing'}
          style={{
            padding:'7px 14px', borderRadius:9, border:'1px solid #E5E7EB',
            background: syncState==='done' ? '#D1FAE5' : syncState==='syncing' ? '#FFF7ED' : '#fff',
            color: syncState==='done' ? '#065F46' : syncState==='syncing' ? '#92400E' : '#1A2B3B',
            fontSize:12, fontWeight:700, cursor: syncState==='syncing' ? 'default' : 'pointer',
            fontFamily:'inherit', whiteSpace:'nowrap', transition:'all 0.2s',
          }}>
          {syncLabel}
        </button>
      </div>

      <div style={{ fontSize:11, color:'#9CA3AF', fontWeight:600 }}>{filtered.length} of {users.length} users</div>

      <div style={{ background:'#fff', border:'1px solid #E5E7EB', borderRadius:14, overflow:'hidden' }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 78px 96px 64px 72px 20px', padding:'9px 20px', borderBottom:'1px solid #E5E7EB', background:'#F9FAFB' }}>
          {['User','Plan','Status','MRR','API Cost',''].map(h => (
            <span key={h} style={{ fontSize:10, fontWeight:800, color:'#9CA3AF', textTransform:'uppercase', letterSpacing:'0.07em' }}>{h}</span>
          ))}
        </div>
        {filtered.map((u,i) => (
          <div key={u.id} onClick={()=>setSelected(u)}
            style={{ display:'grid', gridTemplateColumns:'1fr 78px 96px 64px 72px 20px', alignItems:'center', padding:'11px 20px', borderBottom:i<filtered.length-1?'1px solid #F3F4F6':'none', cursor:'pointer', transition:'background 0.1s' }}
            onMouseEnter={e=>e.currentTarget.style.background='#F9FAFB'}
            onMouseLeave={e=>e.currentTarget.style.background='transparent'}
          >
            <div style={{ minWidth:0 }}>
              <div style={{ fontSize:13, fontWeight:600, color:'#1A2B3B', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{u.name}</div>
              <div style={{ fontSize:11, color:'#9CA3AF', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{u.email}</div>
            </div>
            <PlanBadge plan={u.plan} />
            <StatusDot status={u.status} />
            <span style={{ fontSize:13, fontWeight:700, color:u.mrr>0?'#10B981':'#9CA3AF' }}>{u.mrr>0?`$${u.mrr}`:'—'}</span>
            <span style={{ fontSize:13, fontWeight:600, color:'#F43F5E' }}>${u.api_cost.toFixed(2)}</span>
            <Icon name="ChevronRight" size={13} color="#D1D5DB" />
          </div>
        ))}
        {filtered.length===0 && (
          <div style={{ padding:'48px 20px', textAlign:'center', color:'#9CA3AF', fontSize:13 }}>No users match your search.</div>
        )}
      </div>

      {selected && <UserSlideOver user={selected} onClose={()=>setSelected(null)} />}
    </div>
  );
}

Object.assign(window, { UsersPage });
