// ─────────────────────────────────────────────
// DEV_AppList.jsx — Apps list + Create New App
// ─────────────────────────────────────────────

const REGIONS = [
  { value:'east',    label:'US East',    flag:'🇺🇸' },
  { value:'west',    label:'US West',    flag:'🇺🇸' },
  { value:'eu',      label:'Europe',     flag:'🇪🇺' },
  { value:'uk',      label:'UK',         flag:'🇬🇧' },
  { value:'au',      label:'Australia',  flag:'🇦🇺' },
  { value:'jp',      label:'Japan',      flag:'🇯🇵' },
];

function regionLabel(val) {
  const r = REGIONS.find(r => r.value === val);
  return r ? `${r.flag} ${r.label}` : val || '—';
}

function formatDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-US', { year:'numeric', month:'short', day:'numeric' }); }
  catch(e) { return d; }
}

function DEVAppList({ jwt, currentUser, onOpenApp }) {
  const [apps,        setApps]        = React.useState([]);
  const [loading,     setLoading]     = React.useState(true);
  const [error,       setError]       = React.useState(null);
  const [showCreate,  setShowCreate]  = React.useState(false);

  // Create form state
  const [newName,      setNewName]      = React.useState('');
  const [newDesc,      setNewDesc]      = React.useState('');
  const [newRegion,    setNewRegion]    = React.useState('east');
  const [newTemplate,  setNewTemplate]  = React.useState('');
  const [templates,    setTemplates]    = React.useState([]);
  const [creating,     setCreating]     = React.useState(false);
  const [createError,  setCreateError]  = React.useState(null);

  React.useEffect(() => { loadApps(); }, []);

  // Load templates when modal opens
  React.useEffect(() => {
    if (!showCreate) return;
    apiFetch(`${API_BASE}/v6/dev/library/templates`)
      .then(r => r.json())
      .then(data => { if (data.status === 'ok') setTemplates(data.templates || []); })
      .catch(() => {});
  }, [showCreate]);

  async function loadApps() {
    setLoading(true); setError(null);
    try {
      const res  = await apiFetch(`${API_BASE}/v6/dev/apps`);
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setApps(data.apps || []);
    } catch(err) { setError(err.message); }
    setLoading(false);
  }

  async function handleCreate(e) {
    e.preventDefault();
    if (!newName.trim()) return;
    setCreating(true); setCreateError(null);
    try {
      const res  = await apiFetch(`${API_BASE}/v6/dev/apps`, {
        method: 'POST',
        body: JSON.stringify({
          name:       newName.trim(),
          desc:       newDesc.trim(),
          region:     newRegion,
          templateId: newTemplate || null,
        }),
      });
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setShowCreate(false);
      setNewName(''); setNewDesc(''); setNewRegion('east'); setNewTemplate('');
      await loadApps();
      // Open the new app immediately
      if (data.app) onOpenApp(data.app);
    } catch(err) { setCreateError(err.message); }
    setCreating(false);
  }

  return (
    <div>
      {/* Header */}
      <div style={SA.header}>
        <div>
          <div style={SA.pageTitle}>Apps</div>
          <div style={SA.pageSub}>{apps.length} application{apps.length !== 1 ? 's' : ''}</div>
        </div>
        <button style={SA.createBtn} onClick={() => setShowCreate(true)}>
          <span style={{ fontSize:18, lineHeight:1 }}>+</span> Create New App
        </button>
      </div>

      {/* Create modal */}
      {showCreate && (
        <div style={SA.modalBackdrop} onClick={e => { if(e.target === e.currentTarget) setShowCreate(false); }}>
          <div style={SA.modal}>
            <div style={SA.modalHeader}>
              <div style={SA.modalTitle}>Create New App</div>
              <button style={SA.closeBtn} onClick={() => setShowCreate(false)}>✕</button>
            </div>

            {createError && <div style={SA.error}>{createError}</div>}

            <form onSubmit={handleCreate}>
              <label style={SA.label}>App Name <span style={{ color:'#dc2626' }}>*</span></label>
              <input style={SA.input} type="text" value={newName}
                onChange={e => setNewName(e.target.value)}
                placeholder="My CRM, Inventory Tracker…" autoFocus required />

              <label style={SA.label}>Description <span style={{ color:'#94a3b8', fontWeight:400 }}>(optional)</span></label>
              <textarea style={{ ...SA.input, height:80, resize:'vertical' }}
                value={newDesc} onChange={e => setNewDesc(e.target.value)}
                placeholder="What is this app for?" />

              <label style={SA.label}>Data Region</label>
              <select style={SA.input} value={newRegion} onChange={e => setNewRegion(e.target.value)}>
                {REGIONS.map(r => (
                  <option key={r.value} value={r.value}>{r.flag} {r.label}</option>
                ))}
              </select>

              <label style={SA.label}>
                Template <span style={{ color:'#94a3b8', fontWeight:400 }}>(optional)</span>
              </label>
              <select style={SA.input} value={newTemplate} onChange={e => setNewTemplate(e.target.value)}>
                <option value="">— Start from scratch —</option>
                {templates.map(t => (
                  <option key={t.id} value={t.id}>{t.name}{t.desc ? ` — ${t.desc}` : ''}</option>
                ))}
              </select>
              {newTemplate && (
                <div style={{ fontSize:12, color:'#2563eb', marginTop:-12, marginBottom:16 }}>
                  ✓ App will be pre-built with this template's tables and layout
                </div>
              )}

              <div style={SA.modalFooter}>
                <button type="button" style={SA.cancelBtn}
                  onClick={() => setShowCreate(false)}>Cancel</button>
                <button type="submit" style={SA.submitBtn} disabled={creating || !newName.trim()}>
                  {creating ? '⚙ Provisioning…' : 'Create App →'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Loading */}
      {loading && (
        <div style={SA.empty}>Loading apps…</div>
      )}

      {/* Error */}
      {error && !loading && (
        <div style={SA.error}>{error}</div>
      )}

      {/* Empty state */}
      {!loading && !error && apps.length === 0 && (
        <div style={SA.emptyState}>
          <div style={SA.emptyIcon}>⬡</div>
          <div style={SA.emptyTitle}>No apps yet</div>
          <div style={SA.emptySub}>Create your first app to get started</div>
          <button style={SA.createBtn} onClick={() => setShowCreate(true)}>
            + Create New App
          </button>
        </div>
      )}

      {/* Apps table */}
      {!loading && !error && apps.length > 0 && (
        <div style={SA.table}>
          <div style={SA.thead}>
            <div style={{ ...SA.th, flex:2 }}>Name</div>
            <div style={{ ...SA.th, flex:3 }}>Description</div>
            <div style={{ ...SA.th, flex:1 }}>Region</div>
            <div style={{ ...SA.th, flex:1.5 }}>Created</div>
            <div style={{ ...SA.th, flex:1, textAlign:'center' }}>Status</div>
            <div style={{ ...SA.th, flex:'0 0 40px' }}></div>
          </div>
          {apps.map(app => (
            <div key={app.app_id} style={SA.row} onClick={() => onOpenApp(app)}>
              <div style={{ ...SA.td, flex:2, fontWeight:600, color:'#0f1923' }}>
                {app.app_name}
              </div>
              <div style={{ ...SA.td, flex:3, color:'#64748b', fontSize:13 }}>
                {app.app_desc || <span style={{ color:'#cbd5e1' }}>No description</span>}
              </div>
              <div style={{ ...SA.td, flex:1, fontSize:13 }}>
                {regionLabel(app.app_data)}
              </div>
              <div style={{ ...SA.td, flex:1.5, fontSize:13, color:'#64748b' }}>
                {formatDate(app.app_date_insert)}
              </div>
              <div style={{ ...SA.td, flex:1, textAlign:'center' }}>
                <span style={{ ...SA.badge, ...(app.app_status == 1 ? SA.badgeActive : SA.badgeInactive) }}>
                  {app.app_status == 1 ? 'Active' : 'Inactive'}
                </span>
              </div>
              <div style={{ ...SA.td, flex:'0 0 40px', textAlign:'center' }}>
                <span style={{ color:'#94a3b8', fontSize:16 }}>›</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

const SA = {
  header:       { display:'flex', alignItems:'flex-start', justifyContent:'space-between', marginBottom:28 },
  pageTitle:    { fontSize:26, fontWeight:700, color:'#0f1923', letterSpacing:'-0.02em', marginBottom:4 },
  pageSub:      { fontSize:13, color:'#94a3b8' },
  createBtn:    { display:'flex', alignItems:'center', gap:8, background:'#0f1923', color:'#fff',
                  border:'none', borderRadius:8, padding:'10px 18px', fontSize:13, fontWeight:600,
                  cursor:'pointer', fontFamily:'DM Sans, sans-serif' },
  table:        { background:'#fff', borderRadius:12, border:'1px solid #e2e8f0', overflow:'hidden' },
  thead:        { display:'flex', background:'#0f1923', padding:'11px 20px' },
  th:           { fontSize:11, fontWeight:600, color:'rgba(255,255,255,0.5)',
                  letterSpacing:'0.07em', textTransform:'uppercase' },
  row:          { display:'flex', alignItems:'center', padding:'14px 20px',
                  borderBottom:'1px solid #f1f5f9', cursor:'pointer',
                  transition:'background 0.1s' },
  td:           { fontSize:14, paddingRight:12 },
  badge:        { fontSize:11, fontWeight:600, padding:'3px 10px', borderRadius:20,
                  letterSpacing:'0.04em' },
  badgeActive:  { background:'#dcfce7', color:'#16a34a' },
  badgeInactive:{ background:'#f1f5f9', color:'#64748b' },
  empty:        { textAlign:'center', padding:'60px 0', color:'#94a3b8', fontSize:14 },
  emptyState:   { textAlign:'center', padding:'80px 0' },
  emptyIcon:    { fontSize:48, marginBottom:16, color:'#e2e8f0' },
  emptyTitle:   { fontSize:18, fontWeight:600, color:'#374151', marginBottom:8 },
  emptySub:     { fontSize:14, color:'#94a3b8', marginBottom:24 },
  error:        { background:'#fef2f2', color:'#dc2626', padding:'12px 16px',
                  borderRadius:8, fontSize:13, marginBottom:20, border:'1px solid #fecaca' },
  // Modal
  modalBackdrop:{ position:'fixed', inset:0, background:'rgba(0,0,0,0.4)',
                  display:'flex', alignItems:'center', justifyContent:'center', zIndex:200 },
  modal:        { background:'#fff', borderRadius:16, padding:'32px 36px', width:'100%', maxWidth:480,
                  boxShadow:'0 20px 60px rgba(0,0,0,0.2)' },
  modalHeader:  { display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:24 },
  modalTitle:   { fontSize:18, fontWeight:700, color:'#0f1923', letterSpacing:'-0.01em' },
  closeBtn:     { background:'none', border:'none', color:'#94a3b8', fontSize:18,
                  cursor:'pointer', padding:0, lineHeight:1 },
  label:        { display:'block', fontSize:13, fontWeight:500, color:'#374151', marginBottom:6 },
  input:        { width:'100%', padding:'10px 14px', border:'1.5px solid #e2e8f0', borderRadius:8,
                  fontSize:14, fontFamily:'DM Sans, sans-serif', outline:'none', marginBottom:16,
                  color:'#0f1923', background:'#fff' },
  modalFooter:  { display:'flex', justifyContent:'flex-end', gap:10, marginTop:8 },
  cancelBtn:    { padding:'10px 20px', background:'#fff', color:'#374151',
                  border:'1.5px solid #e2e8f0', borderRadius:8, fontSize:13,
                  fontWeight:500, cursor:'pointer', fontFamily:'DM Sans, sans-serif' },
  submitBtn:    { padding:'10px 22px', background:'#0f1923', color:'#fff',
                  border:'none', borderRadius:8, fontSize:13, fontWeight:600,
                  cursor:'pointer', fontFamily:'DM Sans, sans-serif' },
};
