// ─────────────────────────────────────────────
// DEV_Dashboard.jsx — Developer home / dashboard
// Shows summary cards with links to main sections
// ─────────────────────────────────────────────

const DASH_REGIONS = {
  east:'🇺🇸 US East', west:'🇺🇸 US West', eu:'🇪🇺 Europe',
  uk:'🇬🇧 UK', au:'🇦🇺 Australia', jp:'🇯🇵 Japan',
};
function dashRegion(val) { return DASH_REGIONS[val] || val || '—'; }
function dashDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-US', { year:'numeric', month:'short', day:'numeric' }); }
  catch(e) { return d; }
}

function DEVDashboard({ jwt, currentUser, onNav }) {
  const [apps,    setApps]    = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    fetch(`${API_BASE}/v7/dev/apps`, {
      headers: { Authorization: `Bearer ${jwt}` }
    })
      .then(r => r.json())
      .then(d => { if (d.status === 'ok') setApps(d.apps || []); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [jwt]);

  const displayName = currentUser?.first
    ? `${currentUser.first}`
    : (currentUser?.email || 'Developer');

  const activeApps   = apps.filter(a => a.app_status == 1).length;
  const inactiveApps = apps.filter(a => a.app_status == 0).length;

  return (
    <div>
      {/* Greeting */}
      <div style={SDash.greeting}>
        <div>
          <h1 style={SDash.greetH}>Welcome back, {displayName}</h1>
          <p style={SDash.greetSub}>DataObjects Developer Portal</p>
        </div>
      </div>

      {/* Summary stat row */}
      <div style={SDash.statRow}>
        <StatCard
          label="Total Apps"
          value={loading ? '—' : apps.length}
          sub={loading ? '' : `${activeApps} active${inactiveApps ? `, ${inactiveApps} inactive` : ''}`}
          icon="◈"
          color="#2563eb"
          onClick={() => onNav('apps')}
        />
        <StatCard
          label="Developers"
          value="—"
          sub="Manage team members"
          icon="◎"
          color="#7c3aed"
          onClick={() => onNav('account-developers')}
        />
        <StatCard
          label="Billing"
          value="—"
          sub="View current charges"
          icon="◇"
          color="#0891b2"
          onClick={() => onNav('account-billing')}
        />
        <StatCard
          label="Logs"
          value="—"
          sub="Recent activity"
          icon="≡"
          color="#059669"
          onClick={() => onNav('account-logs')}
        />
      </div>

      {/* Main content — two columns: links left, apps right */}
      <div style={SDash.twoCol}>

        {/* Left: Quick links */}
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>

          {/* Account section */}
          <div style={SDash.card}>
            <div style={SDash.cardHead}>
              <span style={SDash.cardTitle}>Account</span>
            </div>
            <div style={SDash.linkList}>
              <QuickLink label="Account Info"   sub="Client profile &amp; stats"   onClick={() => onNav('account')} />
              <QuickLink label="Developers"     sub="Manage dev team access"       onClick={() => onNav('account-developers')} />
              <QuickLink label="Billing"        sub="Current subscription charges" onClick={() => onNav('account-billing')} />
              <QuickLink label="Payment Info"   sub="Manage credit cards"          onClick={() => onNav('account-payment')} />
              <QuickLink label="Invoices"       sub="Past invoices &amp; receipts" onClick={() => onNav('account-invoices')} />
              <QuickLink label="Security"       sub="IP controls, 2FA settings"    onClick={() => onNav('account-security')} />
              <QuickLink label="Logs"           sub="Developer &amp; billing logs" onClick={() => onNav('account-logs')} />
            </div>
          </div>

          {/* Resources section */}
          <div style={SDash.card}>
            <div style={SDash.cardHead}>
              <span style={SDash.cardTitle}>Resources</span>
            </div>
            <div style={SDash.linkList}>
              <QuickLink label="Public Library"  sub="DO-provided tables, layouts &amp; apps" onClick={() => onNav('resources-library-public')} />
              <QuickLink label="Private Library" sub="Your saved templates &amp; apps"        onClick={() => onNav('resources-library-private')} />
              <QuickLink label="Support Tickets" sub="Submit &amp; track issues"               onClick={() => onNav('resources-tickets')} />
              <QuickLink label="Video Tutorials" sub="YouTube walkthroughs"                    onClick={() => onNav('resources-videos')} />
            </div>
          </div>

        </div>

        {/* Right: Recent Apps (wider) */}
        <div style={SDash.card}>
          <div style={SDash.cardHead}>
            <span style={SDash.cardTitle}>Recent Apps</span>
            <button style={SDash.cardLink} onClick={() => onNav('apps')}>View all →</button>
          </div>
          {loading ? (
            <div style={SDash.empty}>Loading…</div>
          ) : apps.length === 0 ? (
            <div style={SDash.empty}>
              No apps yet.{' '}
              <button style={SDash.inlineLink} onClick={() => onNav('apps')}>Create your first app</button>
            </div>
          ) : (
            <table style={SDash.table}>
              <thead>
                <tr>
                  <th style={SDash.th}>Name</th>
                  <th style={SDash.th}>Description</th>
                  <th style={SDash.th}>Region</th>
                  <th style={SDash.th}>Created</th>
                  <th style={SDash.th}>Status</th>
                </tr>
              </thead>
              <tbody>
                {apps.slice(0, 10).map(app => (
                  <tr key={app.app_id} style={SDash.tr}
                    onClick={() => onNav('apps', app)}
                    onMouseEnter={e => e.currentTarget.style.background = '#f8fafc'}
                    onMouseLeave={e => e.currentTarget.style.background = ''}
                  >
                    <td style={SDash.td}><span style={SDash.appName}>{app.app_name}</span></td>
                    <td style={{ ...SDash.td, color:'#64748b' }}>{app.app_desc || <span style={{ color:'#cbd5e1' }}>—</span>}</td>
                    <td style={{ ...SDash.td, color:'#64748b', whiteSpace:'nowrap' }}>{dashRegion(app.app_data)}</td>
                    <td style={{ ...SDash.td, color:'#64748b', whiteSpace:'nowrap' }}>{dashDate(app.app_date_insert)}</td>
                    <td style={SDash.td}>
                      <span style={{ ...SDash.badge, ...(app.app_status == 1 ? SDash.badgeActive : SDash.badgeOff) }}>
                        {app.app_status == 1 ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

      </div>
    </div>
  );
}

// ── Sub-components ────────────────────────────

function StatCard({ label, value, sub, icon, color, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      style={{ ...SDash.statCard, ...(hover ? { borderColor: color, boxShadow:`0 0 0 3px ${color}18` } : {}) }}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <div style={{ ...SDash.statIcon, background: color + '18', color }}>{icon}</div>
      <div style={SDash.statVal}>{value}</div>
      <div style={SDash.statLabel}>{label}</div>
      <div style={SDash.statSub}>{sub}</div>
    </div>
  );
}

function QuickLink({ label, sub, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      style={{ ...SDash.ql, ...(hover ? SDash.qlHover : {}) }}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
    >
      <div style={SDash.qlLabel}>{label}</div>
      <div style={SDash.qlSub} dangerouslySetInnerHTML={{ __html: sub }} />
      <span style={SDash.qlArrow}>›</span>
    </button>
  );
}

// ── Styles ────────────────────────────────────

const SDash = {
  greeting:    { marginBottom:28 },
  greetH:      { margin:0, fontSize:22, fontWeight:700, color:'#0f1923', letterSpacing:'-0.02em' },
  greetSub:    { margin:'4px 0 0', fontSize:13, color:'#94a3b8' },

  statRow:     { display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16, marginBottom:24 },
  statCard:    { background:'#fff', borderRadius:12, border:'1.5px solid #e2e8f0',
                 padding:'20px 20px 16px', cursor:'pointer',
                 transition:'border-color 0.15s, box-shadow 0.15s' },
  statIcon:    { width:36, height:36, borderRadius:8, display:'flex', alignItems:'center',
                 justifyContent:'center', fontSize:18, marginBottom:12 },
  statVal:     { fontSize:28, fontWeight:700, color:'#0f1923', lineHeight:1, marginBottom:4 },
  statLabel:   { fontSize:13, fontWeight:600, color:'#374151', marginBottom:2 },
  statSub:     { fontSize:12, color:'#94a3b8' },

  twoCol:      { display:'grid', gridTemplateColumns:'280px 1fr', gap:20, alignItems:'start' },

  card:        { background:'#fff', borderRadius:12, border:'1px solid #e2e8f0',
                 overflow:'hidden', marginBottom:0 },
  cardHead:    { display:'flex', alignItems:'center', justifyContent:'space-between',
                 padding:'14px 18px', borderBottom:'1px solid #f1f5f9' },
  cardTitle:   { fontSize:13, fontWeight:600, color:'#0f1923', letterSpacing:'0.01em' },
  cardLink:    { background:'none', border:'none', color:'#2563eb', fontSize:12,
                 cursor:'pointer', fontFamily:'inherit', padding:0 },

  empty:       { padding:'24px 18px', fontSize:13, color:'#94a3b8' },
  inlineLink:  { background:'none', border:'none', color:'#2563eb', cursor:'pointer',
                 fontFamily:'inherit', fontSize:13, padding:0 },

  table:       { width:'100%', borderCollapse:'collapse' },
  th:          { padding:'8px 18px', fontSize:11, fontWeight:600, color:'#94a3b8',
                 textAlign:'left', textTransform:'uppercase', letterSpacing:'0.05em',
                 borderBottom:'1px solid #f1f5f9' },
  tr:          { cursor:'pointer', transition:'background 0.1s' },
  td:          { padding:'10px 18px', fontSize:13, color:'#374151',
                 borderBottom:'1px solid #f8fafc' },
  appName:     { fontWeight:500, color:'#0f1923' },
  badge:       { display:'inline-block', fontSize:11, fontWeight:600, padding:'2px 8px',
                 borderRadius:20 },
  badgeActive: { background:'#dcfce7', color:'#166534' },
  badgeOff:    { background:'#f1f5f9', color:'#64748b' },

  linkList:    { padding:'4px 0' },
  ql:          { display:'flex', alignItems:'center', width:'100%', background:'none',
                 border:'none', padding:'10px 18px', cursor:'pointer', fontFamily:'inherit',
                 textAlign:'left', transition:'background 0.1s', gap:0,
                 borderBottom:'1px solid #f8fafc' },
  qlHover:     { background:'#f8fafc' },
  qlLabel:     { fontSize:13, fontWeight:500, color:'#0f1923', flex:1 },
  qlSub:       { fontSize:12, color:'#94a3b8', marginLeft:8, flex:2 },
  qlArrow:     { fontSize:16, color:'#cbd5e1', marginLeft:8 },
};
