// ─────────────────────────────────────────────
// DEV_Account.jsx — Account section
//
// Sub-views:
//   account            → Account Info + stats
//   account-developers → Developer list with CRUD
//   account-billing    → Billing items (placeholder)
//   account-payment    → Payment info / Stripe (placeholder)
//   account-invoices   → Invoice list (placeholder)
//   account-security   → IP / 2FA controls (placeholder)
//   account-logs       → Developer activity logs (placeholder)
//
// DEVProfileModal is exported separately and used
// both here (for the logged-in user) and by NavBar.
// ─────────────────────────────────────────────

// ─────────────────────────────────────────────
// Profile / Edit Developer Modal
// Used for: logged-in user profile + developer CRUD
// ─────────────────────────────────────────────
function DEVProfileModal({ jwt, currentUser, devData, onClose, onSaved }) {
  // devData = null → editing own profile; devData = {} → editing a developer
  const isOwn    = !devData;
  const initial  = devData || currentUser || {};

  const [form,    setForm]    = React.useState({
    first: initial.first || initial.user_first || '',
    last:  initial.last  || initial.user_last  || '',
    email: initial.email || initial.user_email || '',
    phone: initial.phone || initial.user_phone || '',
    altEmail: initial.alt_email || '',
  });
  const [pw,      setPw]      = React.useState({ pw1:'', pw2:'' });
  const [saving,  setSaving]  = React.useState(false);
  const [msg,     setMsg]     = React.useState(null);  // { type:'ok'|'err', text }

  function set(k, v) { setForm(f => ({ ...f, [k]: v })); }

  async function handleSave() {
    if (!form.first.trim() || !form.last.trim() || !form.email.trim()) {
      setMsg({ type:'err', text:'First name, last name, and email are required.' });
      return;
    }
    setSaving(true); setMsg(null);
    try {
      // TODO: wire to real endpoint once account routes are built
      // POST /v7/dev/account/profile  or  /v7/dev/account/developers/:userId
      await new Promise(r => setTimeout(r, 600)); // placeholder delay
      setMsg({ type:'ok', text:'Saved successfully.' });
      onSaved && onSaved({ ...form });
    } catch(e) {
      setMsg({ type:'err', text: e.message || 'Save failed.' });
    } finally { setSaving(false); }
  }

  async function handlePwChange() {
    if (!pw.pw1 || pw.pw1 !== pw.pw2) {
      setMsg({ type:'err', text:'Passwords must match and not be empty.' });
      return;
    }
    if (pw.pw1.length < 8) {
      setMsg({ type:'err', text:'Password must be at least 8 characters.' });
      return;
    }
    setSaving(true); setMsg(null);
    try {
      await new Promise(r => setTimeout(r, 600)); // placeholder
      setPw({ pw1:'', pw2:'' });
      setMsg({ type:'ok', text:'Password updated.' });
    } catch(e) {
      setMsg({ type:'err', text: e.message || 'Password change failed.' });
    } finally { setSaving(false); }
  }

  return (
    <div style={SPM.backdrop} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={SPM.modal}>
        {/* Header */}
        <div style={SPM.header}>
          <span style={SPM.title}>{isOwn ? 'My Profile' : (devData?.user_id ? 'Edit Developer' : 'New Developer')}</span>
          <button style={SPM.closeBtn} onClick={onClose}>✕</button>
        </div>

        <div style={SPM.body}>
          {/* Name row */}
          <div style={SPM.row2}>
            <div style={SPM.field}>
              <label style={SPM.label}>First Name</label>
              <input style={SPM.input} value={form.first} onChange={e => set('first', e.target.value)} />
            </div>
            <div style={SPM.field}>
              <label style={SPM.label}>Last Name</label>
              <input style={SPM.input} value={form.last} onChange={e => set('last', e.target.value)} />
            </div>
          </div>

          {/* Email */}
          <div style={SPM.field}>
            <label style={SPM.label}>Email</label>
            <input style={SPM.input} type="email" value={form.email} onChange={e => set('email', e.target.value)} />
          </div>

          {/* Alt email */}
          <div style={SPM.field}>
            <label style={SPM.label}>Alternate Email <span style={SPM.optional}>(optional)</span></label>
            <input style={SPM.input} type="email" value={form.altEmail} onChange={e => set('altEmail', e.target.value)} />
          </div>

          {/* Phone */}
          <div style={SPM.field}>
            <label style={SPM.label}>Phone <span style={SPM.optional}>(optional, used for 2FA)</span></label>
            <input style={SPM.input} type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} />
          </div>

          {/* Status message */}
          {msg && (
            <div style={{ ...SPM.msg, ...(msg.type === 'ok' ? SPM.msgOk : SPM.msgErr) }}>
              {msg.text}
            </div>
          )}

          {/* Save button */}
          <div style={{ display:'flex', justifyContent:'flex-end', marginTop:8 }}>
            <button style={SPM.btnGhost} onClick={onClose}>Cancel</button>
            <button style={SPM.btnPrimary} onClick={handleSave} disabled={saving}>
              {saving ? 'Saving…' : 'Save'}
            </button>
          </div>

          {/* Password change section */}
          <div style={SPM.divider} />
          <div style={SPM.sectionHead}>Change Password</div>

          <div style={SPM.field}>
            <label style={SPM.label}>New Password</label>
            <input style={SPM.input} type="password" value={pw.pw1}
              onChange={e => setPw(p => ({ ...p, pw1: e.target.value }))} />
          </div>
          <div style={SPM.field}>
            <label style={SPM.label}>Confirm Password</label>
            <input style={SPM.input} type="password" value={pw.pw2}
              onChange={e => setPw(p => ({ ...p, pw2: e.target.value }))} />
          </div>

          <div style={{ display:'flex', justifyContent:'flex-end', marginTop:8 }}>
            <button style={SPM.btnPrimary} onClick={handlePwChange} disabled={saving}>
              {saving ? 'Updating…' : 'Update Password'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

const SPM = {
  backdrop:   { position:'fixed', inset:0, background:'rgba(0,0,0,0.45)', zIndex:200,
                display:'flex', alignItems:'center', justifyContent:'center', padding:24 },
  modal:      { background:'#fff', borderRadius:14, width:'100%', maxWidth:520,
                boxShadow:'0 20px 60px rgba(0,0,0,0.2)', overflow:'hidden' },
  header:     { display:'flex', alignItems:'center', justifyContent:'space-between',
                padding:'18px 24px', borderBottom:'1px solid #f1f5f9' },
  title:      { fontSize:15, fontWeight:700, color:'#0f1923' },
  closeBtn:   { background:'none', border:'none', fontSize:16, color:'#94a3b8',
                cursor:'pointer', padding:0, lineHeight:1 },
  body:       { padding:'24px', display:'flex', flexDirection:'column', gap:14 },
  row2:       { display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 },
  field:      { display:'flex', flexDirection:'column', gap:5 },
  label:      { fontSize:12, fontWeight:600, color:'#374151', letterSpacing:'0.01em' },
  optional:   { fontWeight:400, color:'#94a3b8' },
  input:      { padding:'8px 12px', border:'1px solid #d1d5db', borderRadius:7, fontSize:13,
                color:'#0f1923', fontFamily:'inherit', outline:'none' },
  msg:        { padding:'10px 14px', borderRadius:8, fontSize:13 },
  msgOk:      { background:'#dcfce7', color:'#166534' },
  msgErr:     { background:'#fef2f2', color:'#dc2626' },
  divider:    { height:1, background:'#f1f5f9', margin:'8px 0' },
  sectionHead:{ fontSize:13, fontWeight:600, color:'#374151', marginBottom:2 },
  btnPrimary: { background:'#2563eb', color:'#fff', border:'none', borderRadius:8,
                padding:'8px 20px', fontSize:13, fontWeight:600, cursor:'pointer',
                fontFamily:'inherit', marginLeft:8 },
  btnGhost:   { background:'none', color:'#64748b', border:'1px solid #d1d5db',
                borderRadius:8, padding:'8px 20px', fontSize:13, cursor:'pointer',
                fontFamily:'inherit' },
};


// ─────────────────────────────────────────────
// DEVAccount — main account section component
// ─────────────────────────────────────────────
function DEVAccount({ jwt, currentUser, view, onNav }) {
  return (
    <div style={SAcct.layout}>
      {/* Sub-nav sidebar */}
      <div style={SAcct.sidebar}>
        <div style={SAcct.sideHead}>Account</div>
        {[
          { v:'account',           label:'Account Info' },
          { v:'account-developers',label:'Developers' },
          { v:'account-billing',   label:'Billing' },
          { v:'account-payment',   label:'Payment Info' },
          { v:'account-invoices',  label:'Invoices' },
          { v:'account-security',  label:'Security' },
          { v:'account-logs',      label:'Logs' },
        ].map(item => (
          <button
            key={item.v}
            style={{ ...SAcct.sideItem, ...(view === item.v ? SAcct.sideItemActive : {}) }}
            onClick={() => onNav(item.v)}
          >
            {item.label}
          </button>
        ))}
      </div>

      {/* Panel content */}
      <div style={SAcct.panel}>
        {view === 'account'            && <AccountInfo     jwt={jwt} currentUser={currentUser} />}
        {view === 'account-developers' && <AccountDevs     jwt={jwt} currentUser={currentUser} />}
        {view === 'account-billing'    && <PlaceholderPanel title="Billing"      desc="Subscription and per-app billing details will appear here. Powered by Stripe." />}
        {view === 'account-payment'    && <PlaceholderPanel title="Payment Info" desc="Add or update your credit card information via Stripe." />}
        {view === 'account-invoices'   && <PlaceholderPanel title="Invoices"     desc="Past invoices and payment receipts will be listed here with print/download options." />}
        {view === 'account-security'   && <PlaceholderPanel title="Security"     desc="IP whitelist/blacklist, country restrictions, and 2FA settings for developer login." />}
        {view === 'account-logs'       && <PlaceholderPanel title="Logs"         desc="Developer activity log — new apps created, billing changes, login events, and more." />}
      </div>
    </div>
  );
}

// ── Account Info Panel ────────────────────────
function AccountInfo({ jwt, currentUser }) {
  const displayName = [currentUser?.first, currentUser?.last].filter(Boolean).join(' ')
    || currentUser?.email || '—';

  return (
    <div>
      <div style={SAcct.panelTitle}>Account Info</div>

      <div style={SAcct.infoGrid}>
        <InfoRow label="Name"         value={displayName} />
        <InfoRow label="Email"        value={currentUser?.email || '—'} />
        <InfoRow label="Member Since" value="—" />
        <InfoRow label="Last Login"   value="—" />
      </div>

      <div style={{ ...SAcct.statsRow, marginTop:24 }}>
        <MiniStat label="Apps"       value="—" />
        <MiniStat label="Storage"    value="—" />
        <MiniStat label="Developers" value="—" />
      </div>

      <div style={SAcct.placeholderNote}>
        Full account stats and client info will populate once account API endpoints are wired.
      </div>
    </div>
  );
}

function InfoRow({ label, value }) {
  return (
    <div style={SAcct.infoRow}>
      <span style={SAcct.infoLabel}>{label}</span>
      <span style={SAcct.infoValue}>{value}</span>
    </div>
  );
}

function MiniStat({ label, value }) {
  return (
    <div style={SAcct.miniStat}>
      <div style={SAcct.miniVal}>{value}</div>
      <div style={SAcct.miniLabel}>{label}</div>
    </div>
  );
}

// ── Developers Panel ──────────────────────────
function AccountDevs({ jwt, currentUser }) {
  const [devs,    setDevs]    = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [modal,   setModal]   = React.useState(null); // null | 'new' | devObj

  // TODO: fetch from /v7/dev/account/developers once endpoint exists
  React.useEffect(() => {
    // Placeholder — show current user as only dev for now
    setTimeout(() => {
      setDevs([{
        user_id:    currentUser?.userId || '—',
        user_first: currentUser?.first  || '—',
        user_last:  currentUser?.last   || '—',
        user_email: currentUser?.email  || '—',
        user_status: 1,
        _isYou: true,
      }]);
      setLoading(false);
    }, 300);
  }, []);

  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:20 }}>
        <div style={SAcct.panelTitle}>Developers</div>
        <button style={SAcct.btnPrimary} onClick={() => setModal('new')}>+ New Developer</button>
      </div>

      {loading ? (
        <div style={SAcct.loadMsg}>Loading…</div>
      ) : (
        <div style={SAcct.devTable}>
          <div style={SAcct.devHead}>
            <span style={SAcct.devHCell}>Name</span>
            <span style={SAcct.devHCell}>Email</span>
            <span style={SAcct.devHCell}>Status</span>
            <span style={SAcct.devHCell}></span>
          </div>
          {devs.map(dev => (
            <div key={dev.user_id} style={SAcct.devRow}>
              <span style={SAcct.devCell}>
                {dev.user_first} {dev.user_last}
                {dev._isYou && <span style={SAcct.youBadge}>You</span>}
              </span>
              <span style={{ ...SAcct.devCell, color:'#64748b' }}>{dev.user_email}</span>
              <span style={SAcct.devCell}>
                <span style={{ ...SAcct.badge, ...(dev.user_status == 1 ? SAcct.badgeActive : SAcct.badgeOff) }}>
                  {dev.user_status == 1 ? 'Active' : 'Inactive'}
                </span>
              </span>
              <span style={{ ...SAcct.devCell, textAlign:'right' }}>
                <button style={SAcct.editBtn} onClick={() => setModal(dev)}>Edit</button>
              </span>
            </div>
          ))}
        </div>
      )}

      <div style={SAcct.placeholderNote}>
        Developer management API endpoints are planned. CRUD will be fully wired here.
      </div>

      {/* Profile/Edit modal */}
      {modal && (
        <DEVProfileModal
          jwt={jwt}
          currentUser={currentUser}
          devData={modal === 'new' ? {} : modal}
          onClose={() => setModal(null)}
          onSaved={updated => {
            // TODO: refresh list from server
            setModal(null);
          }}
        />
      )}
    </div>
  );
}

// ── Generic placeholder panel ─────────────────
function PlaceholderPanel({ title, desc }) {
  return (
    <div>
      <div style={SAcct.panelTitle}>{title}</div>
      <div style={SAcct.placeholderBox}>
        <div style={SAcct.placeholderIcon}>⚙</div>
        <div style={SAcct.placeholderText}>{desc}</div>
        <div style={SAcct.placeholderSub}>This section is coming soon.</div>
      </div>
    </div>
  );
}

// ── Styles ────────────────────────────────────
const SAcct = {
  layout:       { display:'grid', gridTemplateColumns:'200px 1fr', gap:24, alignItems:'start' },

  sidebar:      { background:'#fff', borderRadius:12, border:'1px solid #e2e8f0',
                  overflow:'hidden', position:'sticky', top:78 },
  sideHead:     { padding:'14px 16px 10px', fontSize:11, fontWeight:700, color:'#94a3b8',
                  textTransform:'uppercase', letterSpacing:'0.08em',
                  borderBottom:'1px solid #f1f5f9' },
  sideItem:     { display:'block', width:'100%', textAlign:'left', background:'none',
                  border:'none', borderLeft:'3px solid transparent',
                  padding:'10px 16px', fontSize:13, color:'#374151', cursor:'pointer',
                  fontFamily:'inherit', transition:'all 0.12s' },
  sideItemActive:{ color:'#2563eb', fontWeight:600, background:'#eff6ff',
                   borderLeftColor:'#2563eb' },

  panel:        { background:'#fff', borderRadius:12, border:'1px solid #e2e8f0', padding:'28px 32px' },
  panelTitle:   { fontSize:17, fontWeight:700, color:'#0f1923', marginBottom:20,
                  letterSpacing:'-0.01em' },

  infoGrid:     { display:'flex', flexDirection:'column', gap:1,
                  border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden' },
  infoRow:      { display:'flex', alignItems:'center', padding:'12px 16px',
                  borderBottom:'1px solid #f1f5f9', gap:16 },
  infoLabel:    { fontSize:12, fontWeight:600, color:'#94a3b8', width:120, flexShrink:0 },
  infoValue:    { fontSize:13, color:'#0f1923' },

  statsRow:     { display:'flex', gap:16 },
  miniStat:     { flex:1, background:'#f8fafc', borderRadius:10, padding:'16px',
                  border:'1px solid #e2e8f0', textAlign:'center' },
  miniVal:      { fontSize:24, fontWeight:700, color:'#0f1923', marginBottom:4 },
  miniLabel:    { fontSize:12, color:'#94a3b8', fontWeight:500 },

  devTable:     { border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden', marginBottom:16 },
  devHead:      { display:'grid', gridTemplateColumns:'1fr 1fr 100px 80px',
                  padding:'8px 16px', background:'#f8fafc',
                  borderBottom:'1px solid #e2e8f0' },
  devHCell:     { fontSize:11, fontWeight:700, color:'#94a3b8',
                  textTransform:'uppercase', letterSpacing:'0.05em' },
  devRow:       { display:'grid', gridTemplateColumns:'1fr 1fr 100px 80px',
                  padding:'11px 16px', borderBottom:'1px solid #f8fafc',
                  alignItems:'center' },
  devCell:      { fontSize:13, color:'#374151' },
  youBadge:     { display:'inline-block', marginLeft:7, fontSize:10, fontWeight:700,
                  padding:'1px 7px', borderRadius:20, background:'#eff6ff', color:'#2563eb' },
  badge:        { display:'inline-block', fontSize:11, fontWeight:600,
                  padding:'2px 8px', borderRadius:20 },
  badgeActive:  { background:'#dcfce7', color:'#166534' },
  badgeOff:     { background:'#f1f5f9', color:'#64748b' },
  editBtn:      { background:'none', border:'1px solid #d1d5db', borderRadius:6,
                  padding:'4px 12px', fontSize:12, color:'#374151', cursor:'pointer',
                  fontFamily:'inherit' },

  btnPrimary:   { background:'#2563eb', color:'#fff', border:'none', borderRadius:8,
                  padding:'8px 16px', fontSize:13, fontWeight:600, cursor:'pointer',
                  fontFamily:'inherit' },

  loadMsg:      { color:'#94a3b8', fontSize:13, padding:'16px 0' },
  placeholderBox:  { background:'#f8fafc', border:'1px dashed #d1d5db', borderRadius:12,
                     padding:'40px 32px', textAlign:'center' },
  placeholderIcon: { fontSize:32, marginBottom:12, opacity:0.3 },
  placeholderText: { fontSize:14, color:'#374151', marginBottom:8, fontWeight:500 },
  placeholderSub:  { fontSize:13, color:'#94a3b8' },
  placeholderNote: { marginTop:16, padding:'10px 14px', background:'#fffbeb',
                     border:'1px solid #fde68a', borderRadius:8, fontSize:12, color:'#92400e' },
};
