// ─────────────────────────────────────────────
// DEV_Design_Portal.jsx
// Portal inspector component for DEV_Design.jsx
//
// Usage in Inspector:
//   {local.type === 'portal' && (
//     <PortalInspector local={local} set={set} tables={tables} fields={fields} lbl={lbl} sel={sel} inp={inp} />
//   )}
//
// Portal object JSON:
//   {
//     type:          'portal',
//     label:         'Notes',
//     relatedTable:  't2',
//     displayFields: ['1','2','3'],   // o_field numbers (no 'f' prefix)
//     sortField:     '1',
//     sortDir:       'desc',
//     displayAs:     'rows',          // 'rows' | 'columns'
//     allowAdd:      'yes',
//     allowDelete:   'yes',
//     deleteParent:  'no',
//     portalHeight:  200,             // px, 0 = auto
//   }
// ─────────────────────────────────────────────

function PortalInspector({ local, set, tables: tablesProp, fields, lbl, sel, inp }) {

  const [relFields,     setRelFields]     = React.useState([]);
  const [relLoading,    setRelLoading]    = React.useState(false);
  const [allTables,     setAllTables]     = React.useState(tablesProp || []);
  const [displayFields, setDisplayFields] = React.useState(
    Array.isArray(local.displayFields) ? local.displayFields : []
  );

  // Always fetch tables directly — prop may not be populated at mount time
  React.useEffect(() => {
    if (!local._appId) return;
    apiFetch(`${API_BASE}/v7/dev/apps/${local._appId}/tables`)
      .then(r => r.json())
      .then(d => { if (d.status === 'ok') setAllTables(d.tables || []); })
      .catch(() => {});
  }, [local._appId]);

  // Load related table fields — V7 uses /v7/dev/ and nested fields with .code
  React.useEffect(() => {
    if (!local.relatedTable || !local._appId) return;
    setRelLoading(true);
    apiFetch(`${API_BASE}/v7/dev/apps/${local._appId}/tables`)
      .then(r => r.json())
      .then(data => {
        if (data.status !== 'ok') return;
        const tbl = (data.tables || []).find(t =>
          t.tCode === local.relatedTable ||
          t.code  === local.relatedTable ||
          String(t.tNum) === String(local.relatedTable).replace('t','')
        );
        // V7: fields nested in table JSON with .code (f1,f2…) and .name
        setRelFields((tbl?.fields || []).filter(f => f.status !== 0));
      })
      .catch(() => {})
      .finally(() => setRelLoading(false));
  }, [local.relatedTable, local._appId]);

  function toggleDisplayField(key) {
    const cur     = Array.isArray(local.displayFields) ? local.displayFields : [];
    const updated = cur.includes(key) ? cur.filter(f => f !== key) : [...cur, key];
    setDisplayFields(updated);
    set('displayFields', updated);
  }

  // ── Inline helpers ────────────────────────────
  const sectionStyle = {
    background:'#f8fafc', borderRadius:8, padding:'10px 12px',
    marginBottom:10, border:'1px solid #f1f5f9',
  };
  const checkRow = {
    display:'flex', alignItems:'center', gap:8,
    padding:'4px 0', cursor:'pointer', fontSize:12, color:'#374151',
  };
  const toggleGroup = (key, options, defaultVal) => (
    <div style={{ display:'flex', border:'1.5px solid #e2e8f0', borderRadius:6,
                  overflow:'hidden', marginBottom:10 }}>
      {options.map(o => (
        <button key={o.v} type="button" onClick={() => set(key, o.v)}
          style={{ flex:1, padding:'6px', border:'none', fontSize:11, fontWeight:500,
                   cursor:'pointer', fontFamily:'DM Sans, sans-serif',
                   background: (local[key]||defaultVal)===o.v ? '#0f1923' : '#fff',
                   color:      (local[key]||defaultVal)===o.v ? '#fff' : '#64748b' }}>
          {o.l}
        </button>
      ))}
    </div>
  );

  return (
    <>
      {/* ── Label ── */}
      {lbl('Portal Label')}
      {inp('label', { placeholder:'Notes, Employees, Orders…' })}

      {/* ── Related Table ── */}
      {lbl('Related Table')}
      <select
        value={local.relatedTable || ''}
        onChange={e => {
          set('relatedTable', e.target.value);
          set('displayFields', []);
          set('sortField', '');
          setDisplayFields([]);
        }}
        style={{ width:'100%', padding:'6px 8px', border:'1.5px solid #e2e8f0',
                 borderRadius:6, fontSize:12, fontFamily:'DM Sans, sans-serif',
                 color:'#0f1923', background:'#fff', outline:'none', marginBottom:10 }}>
        <option value="">— Select table —</option>
        {(allTables || []).map(t => (
          <option key={t.tCode || t.code || t._oid} value={t.tCode || t.code}>
            {t.name} ({t.tCode || t.code})
          </option>
        ))}
      </select>

      {/* ── Display Fields ── */}
      {local.relatedTable && (
        <>
          {lbl('Display Fields')}
          <div style={sectionStyle}>
            {relLoading && <div style={{ fontSize:12, color:'#94a3b8' }}>Loading…</div>}
            {!relLoading && relFields.length === 0 && (
              <div style={{ fontSize:12, color:'#94a3b8' }}>No fields found</div>
            )}
            {relFields.map(f => {
              // V7: f.code = 'f1', f.name = 'First Name', f.id = UUID
              const key     = f.code || f.field || '';
              const checked = displayFields.includes(key);
              return (
                <label key={f.id || f.code} style={checkRow}
                  onClick={() => toggleDisplayField(key)}>
                  <span style={{
                    width:14, height:14,
                    border:`1.5px solid ${checked ? '#2563eb' : '#cbd5e1'}`,
                    borderRadius:3, background: checked ? '#2563eb' : '#fff',
                    display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                  }}>
                    {checked && <span style={{ color:'#fff', fontSize:9, fontWeight:700 }}>✓</span>}
                  </span>
                  <span>{f.name}</span>
                  <span style={{ fontSize:10, color:'#94a3b8', fontFamily:'DM Mono, monospace', marginLeft:'auto' }}>
                    {f.code || f.field}
                  </span>
                </label>
              );
            })}
          </div>

          {/* ── Display As ── */}
          {lbl('Display As')}
          {toggleGroup('displayAs', [
            { v:'rows',    l:'⊟ Rows (Table)' },
            { v:'columns', l:'⊞ Columns' },
          ], 'rows')}

          {/* ── Sort ── */}
          {lbl('Sort By')}
          <select value={local.sortField || ''}
            onChange={e => set('sortField', e.target.value)}
            style={{ width:'100%', padding:'6px 8px', border:'1.5px solid #e2e8f0',
                     borderRadius:6, fontSize:12, fontFamily:'DM Sans, sans-serif',
                     color:'#0f1923', background:'#fff', outline:'none', marginBottom:6 }}>
            <option value="">— Date created (default) —</option>
            {relFields.map(f => (
              <option key={f.code || f.field} value={f.code || f.field}>
                {f.name}
              </option>
            ))}
          </select>

          {lbl('Sort Direction')}
          {toggleGroup('sortDir', [
            { v:'desc', l:'Newest First' },
            { v:'asc',  l:'Oldest First' },
          ], 'desc')}
        </>
      )}

      {/* ── Permissions ── */}
      <div style={{ height:1, background:'#e2e8f0', margin:'12px 0' }} />
      {lbl('Permissions')}
      <div style={sectionStyle}>
        {[
          { key:'allowAdd',    label:'Allow adding records'             },
          { key:'allowDelete', label:'Allow deleting records'           },
          { key:'deleteParent',label:'Delete related when parent deleted' },
        ].map(({ key, label }) => {
          const on = local[key] === 'yes' || local[key] === true;
          return (
            <label key={key} style={checkRow} onClick={() => set(key, on ? 'no' : 'yes')}>
              <span style={{
                width:14, height:14,
                border:`1.5px solid ${on ? '#2563eb' : '#cbd5e1'}`,
                borderRadius:3, background: on ? '#2563eb' : '#fff',
                display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
              }}>
                {on && <span style={{ color:'#fff', fontSize:9, fontWeight:700 }}>✓</span>}
              </span>
              <span>{label}</span>
            </label>
          );
        })}
      </div>

      {/* ── Height ── */}
      {lbl('Max Height (px, 0 = auto)')}
      {inp('portalHeight', { type:'number', placeholder:'200', min:'0', max:'800' })}

      {/* ── Row limit ── */}
      {lbl('Max Rows')}
      {inp('portalRows', { type:'number', placeholder:'25', min:'1', max:'200' })}
    </>
  );
}
