// ─────────────────────────────────────────────
// DEV_ValueLists.jsx  (V7)
// ValueListPicker — dropdown for inspector
// ValueListsPanel — full editor with library
//
// Options support two formats:
//   Plain string:  "California"
//   Name|Value:    "California | CA"
// Both stored in options[] array —
//   plain → string, pipe → {label, value}
// ─────────────────────────────────────────────

// ─────────────────────────────────────────────
// ValueListPicker — compact selector for inspector
// ─────────────────────────────────────────────
function ValueListPicker({ appId, value, onChange }) {
  const [lists,   setLists]   = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!appId) return;
    apiFetch(`${API_BASE}/v7/dev/apps/${appId}/valuelists`)
      .then(r => r.json())
      .then(d => { if (d.status === 'ok') setLists(d.lists); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [appId]);

  if (loading) return (
    <div style={{ fontSize:12, color:'#94a3b8', marginBottom:10 }}>Loading lists…</div>
  );
  if (!lists.length) return (
    <div style={{ padding:'8px 10px', background:'#fef9ec', border:'1px solid #fde68a',
      borderRadius:6, fontSize:12, color:'#92400e', marginBottom:10 }}>
      No value lists. Create one in the Value Lists tab.
    </div>
  );

  return (
    <select value={value || ''} onChange={e => onChange(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:10 }}>
      <option value="">— select a value list —</option>
      {lists.map(vl => (
        <option key={vl.id} value={vl.name}>
          {vl.icon ? vl.icon + ' ' : ''}{vl.name} ({(vl.options||[]).length} options)
        </option>
      ))}
    </select>
  );
}

// ─────────────────────────────────────────────
// ValueListsPanel — full editor
// ─────────────────────────────────────────────
function ValueListsPanel({ app }) {
  const [lists,         setLists]         = React.useState([]);
  const [loading,       setLoading]       = React.useState(true);
  const [selected,      setSelected]      = React.useState(null);
  const [editing,       setEditing]       = React.useState(null);
  const [saving,        setSaving]        = React.useState(false);
  const [msg,           setMsg]           = React.useState(null);
  const [newName,       setNewName]       = React.useState('');
  const [creating,      setCreating]      = React.useState(false);
  const [library,       setLibrary]       = React.useState({ public:[], private:[] });
  const [libLoading,    setLibLoading]    = React.useState(false);
  const [showSaveToLib, setShowSaveToLib] = React.useState(false);
  const [vlIconBrowser, setVlIconBrowser] = React.useState(false);

  React.useEffect(() => { loadLists(); loadLibrary(); }, [app?.app_id]);

  async function loadLists() {
    if (!app?.app_id) return;
    setLoading(true);
    try {
      const res  = await apiFetch(`${API_BASE}/v7/dev/apps/${app.app_id}/valuelists`);
      const data = await res.json();
      if (data.status === 'ok') setLists(data.lists);
    } catch(e) { console.error(e); }
    setLoading(false);
  }

  // ── Options text ↔ array conversion ──────────
  // Supports both "California" and "California | CA"
  function optionsToText(options) {
    if (!options?.length) return '';
    return options.map(o => {
      if (typeof o === 'string') return o;
      if (o.label !== undefined && o.value !== undefined) return `${o.label} | ${o.value}`;
      return JSON.stringify(o);
    }).join('\n');
  }

  function textToOptions(text) {
    return text.split('\n')
      .map(s => s.trim())
      .filter(Boolean)
      .map(line => {
        const pipeIdx = line.indexOf(' | ');
        if (pipeIdx !== -1) {
          return { label: line.slice(0, pipeIdx).trim(), value: line.slice(pipeIdx + 3).trim() };
        }
        return line;
      });
  }

  async function loadLibrary() {
    if (!app?.app_id) return;
    setLibLoading(true);
    try {
      const res  = await apiFetch(`${API_BASE}/v7/dev/library`);
      const data = await res.json();
      if (data.status === 'ok') {
        setLibrary({ public: data.public || [], private: data.private || [] });
      }
    } catch(e) { console.error(e); }
    setLibLoading(false);
  }

  async function addFromLibrary(libItem) {
    try {
      const res  = await apiFetch(`${API_BASE}/v7/dev/library/add-to-app`, {
        method: 'POST',
        body: JSON.stringify({ appId: app.app_id, libId: libItem.id }),
      });
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setMsg('✓ Added to app');
      setTimeout(() => setMsg(null), 2500);
      await loadLists();
      selectList({ id: data.id, name: data.name, options: data.options || [], desc: '' });
    } catch(e) { setMsg('⚠ ' + e.message); }
  }

  async function saveToLibrary() {
    if (!editing?.id) return;
    setShowSaveToLib(false);
    try {
      const res  = await apiFetch(`${API_BASE}/v7/dev/library/save-to-private`, {
        method: 'POST',
        body: JSON.stringify({ appId: app.app_id, vlId: editing.id }),
      });
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setMsg('✓ Saved to private library');
      setTimeout(() => setMsg(null), 2500);
      await loadLibrary();
    } catch(e) { setMsg('⚠ ' + e.message); }
  }

  function sortOptions() {
    if (!editing) return;
    const sorted = textToOptions(editing.optionsText || '');
    sorted.sort((a, b) => {
      const la = (typeof a === 'string' ? a : a.label).toLowerCase();
      const lb = (typeof b === 'string' ? b : b.label).toLowerCase();
      return la < lb ? -1 : la > lb ? 1 : 0;
    });
    setEditing(p => ({ ...p, optionsText: optionsToText(sorted) }));
  }

  function selectList(vl) {
    setSelected(vl);
    setEditing({ ...vl, icon: vl.icon || '', optionsText: optionsToText(vl.options) });
    setMsg(null);
  }

  async function saveList() {
    if (!editing) return;
    setSaving(true); setMsg(null);
    try {
      const options = textToOptions(editing.optionsText || '');
      const res  = await apiFetch(
        `${API_BASE}/v7/dev/apps/${app.app_id}/valuelists/${editing.id}`,
        { method:'POST', body: JSON.stringify({
            name: editing.name, desc: editing.desc,
            icon: editing.icon || '', options
        })}
      );
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setMsg('✓ Saved');
      setTimeout(() => setMsg(null), 2500);
      await loadLists();
      setEditing(prev => ({ ...prev, options, optionsText: optionsToText(options) }));
    } catch(e) { setMsg('⚠ ' + e.message); }
    setSaving(false);
  }

  async function deleteList() {
    if (!editing) return;
    if (!window.confirm(`Delete "${editing.name}"? This cannot be undone.`)) return;
    setSaving(true);
    try {
      await apiFetch(
        `${API_BASE}/v7/dev/apps/${app.app_id}/valuelists/${editing.id}`,
        { method:'POST', body: JSON.stringify({ action:'delete' }) }
      );
      setSelected(null); setEditing(null);
      await loadLists();
    } catch(e) { setMsg('⚠ ' + e.message); }
    setSaving(false);
  }

  async function createList() {
    if (!newName.trim()) return;
    setSaving(true);
    try {
      const res  = await apiFetch(
        `${API_BASE}/v7/dev/apps/${app.app_id}/valuelists`,
        { method:'POST', body: JSON.stringify({ name: newName.trim(), options: [] }) }
      );
      const data = await res.json();
      if (data.status !== 'ok') throw new Error(data.message);
      setNewName(''); setCreating(false);
      await loadLists();
      selectList({ id: data.id, name: data.name, options: [], desc: '' });
    } catch(e) { setMsg('⚠ ' + e.message); }
    setSaving(false);
  }

  const optionCount = (editing?.optionsText || '').split('\n').filter(s => s.trim()).length;

  return (
    <div style={{ display:'table', width:'100%', tableLayout:'fixed' }}>
      <div style={{ display:'table-row' }}>

        {/* ── LEFT: list sidebar ── */}
        <div style={{ display:'table-cell', width:220, verticalAlign:'top',
          borderRight:'1px solid #e2e8f0', background:'#fafafa' }}>

          <div style={{ padding:'10px 12px', borderBottom:'1px solid #e2e8f0',
            display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <span style={{ fontSize:11, fontWeight:700, color:'#64748b',
              textTransform:'uppercase', letterSpacing:'0.06em' }}>Value Lists</span>
            <button onClick={() => setCreating(true)}
              style={{ background:'#0f1923', border:'none', color:'#fff',
                width:22, height:22, borderRadius:4, cursor:'pointer', fontSize:16,
                display:'flex', alignItems:'center', justifyContent:'center',
                fontFamily:'DM Sans, sans-serif', lineHeight:1 }}>+</button>
          </div>

          {creating && (
            <div style={{ padding:'8px 10px', borderBottom:'1px solid #f1f5f9',
              background:'#eff6ff' }}>
              <input autoFocus value={newName} onChange={e => setNewName(e.target.value)}
                onKeyDown={e => {
                  if (e.key==='Enter')  createList();
                  if (e.key==='Escape') { setCreating(false); setNewName(''); }
                }}
                placeholder="List name…"
                style={{ width:'100%', padding:'5px 8px', border:'1.5px solid #2563eb',
                  borderRadius:5, fontSize:12, fontFamily:'DM Sans, sans-serif',
                  outline:'none', marginBottom:6, boxSizing:'border-box' }} />
              <div style={{ display:'flex', gap:6 }}>
                <button onClick={createList}
                  style={{ flex:1, padding:'4px', background:'#0f1923', color:'#fff',
                    border:'none', borderRadius:4, fontSize:11, cursor:'pointer',
                    fontFamily:'DM Sans, sans-serif' }}>Create</button>
                <button onClick={() => { setCreating(false); setNewName(''); }}
                  style={{ padding:'4px 8px', background:'#fff', color:'#64748b',
                    border:'1px solid #e2e8f0', borderRadius:4, fontSize:11,
                    cursor:'pointer', fontFamily:'DM Sans, sans-serif' }}>Cancel</button>
              </div>
            </div>
          )}

          {loading ? (
            <div style={{ padding:20, textAlign:'center', color:'#94a3b8', fontSize:12 }}>
              Loading…
            </div>
          ) : lists.length === 0 ? (
            <div style={{ padding:20, textAlign:'center', color:'#94a3b8', fontSize:12 }}>
              No value lists yet.<br/>Click + to create one.
            </div>
          ) : (
            <div style={{ overflowY:'auto', maxHeight:600 }}>
              {lists.map(vl => (
                <div key={vl.id} onClick={() => selectList(vl)}
                  style={{ padding:'8px 12px', cursor:'pointer',
                    borderBottom:'1px solid #f1f5f9',
                    background: selected?.id===vl.id ? '#eff6ff' : 'transparent',
                    borderLeft: selected?.id===vl.id ? '3px solid #2563eb' : '3px solid transparent' }}>
                  <div style={{ fontSize:12, fontWeight:600, color:'#1e293b',
                    overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap',
                    display:'flex', alignItems:'center', gap:5 }}>
                    {vl.icon && <span style={{ fontSize:14 }}>{vl.icon}</span>}
                    {vl.name}
                  </div>
                  <div style={{ fontSize:11, color:'#94a3b8', marginTop:1 }}>
                    {(vl.options||[]).length} options
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* ── CENTER: editor ── */}
        <div style={{ display:'table-cell', verticalAlign:'top',
          background:'#fff', padding:0 }}>
          {!editing ? (
            <div style={{ padding:60, textAlign:'center', color:'#94a3b8', fontSize:13 }}>
              Select a value list to edit,<br/>or click + to create one.
            </div>
          ) : (
            <div style={{ padding:16, maxWidth:600 }}>

              {/* Name */}
              <div style={SVL.lbl}>List Name</div>
              <input value={editing.name || ''}
                onChange={e => setEditing(p => ({...p, name: e.target.value}))}
                style={SVL.input} />

              {/* Icon */}
              <div style={{ ...SVL.lbl, display:'flex', alignItems:'center',
                justifyContent:'space-between' }}>
                Icon
                <button type="button" onClick={() => setVlIconBrowser(true)}
                  style={{ background:'none', border:'1px solid #e2e8f0', borderRadius:5,
                    padding:'2px 7px', fontSize:11, color:'#2563eb', cursor:'pointer',
                    fontFamily:'DM Sans, sans-serif', fontWeight:600, textTransform:'none' }}>
                  🔍 Browse
                </button>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
                <input value={editing.icon || ''}
                  onChange={e => setEditing(p => ({...p, icon: e.target.value}))}
                  placeholder="😀"
                  style={{ width:60, height:44, padding:'4px', border:'1.5px solid #e2e8f0',
                    borderRadius:7, fontSize:24, textAlign:'center',
                    fontFamily:'DM Sans, sans-serif', outline:'none' }} />
                {editing.icon && (
                  <button onClick={() => setEditing(p => ({...p, icon:''}))}
                    style={{ background:'none', border:'none', color:'#94a3b8',
                      cursor:'pointer', fontSize:13 }}>✕</button>
                )}
              </div>

              {/* Description */}
              <div style={SVL.lbl}>Description (optional)</div>
              <input value={editing.desc || ''}
                onChange={e => setEditing(p => ({...p, desc: e.target.value}))}
                placeholder="e.g. US State codes"
                style={SVL.input} />

              {/* Options */}
              <div style={{ display:'flex', alignItems:'center',
                justifyContent:'space-between', marginBottom:4 }}>
                <div style={SVL.lbl}>Options — one per line</div>
                <span style={{ fontSize:11, color:'#94a3b8',
                  fontFamily:'DM Mono, monospace' }}>{optionCount} values</span>
              </div>
              <textarea
                value={editing.optionsText || ''}
                onChange={e => setEditing(p => ({...p, optionsText: e.target.value}))}
                placeholder={'Plain value\nLabel | StoredValue\nPolice Dept | PD'}
                style={{ width:'100%', height:280, padding:'8px 10px',
                  border:'1.5px solid #e2e8f0', borderRadius:6, fontSize:13,
                  fontFamily:'DM Mono, monospace', outline:'none', resize:'vertical',
                  lineHeight:1.6, boxSizing:'border-box', marginBottom:4 }} />
              <div style={{ fontSize:10, color:'#94a3b8', marginBottom:12, lineHeight:1.5 }}>
                Plain text = simple value.
                Use <strong>Label | Value</strong> for name/value pairs.
              </div>

              {/* Actions */}
              <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                <button onClick={saveList} disabled={saving}
                  style={{ flex:1, padding:'9px', background:'#0f1923', color:'#fff',
                    border:'none', borderRadius:6, fontSize:13, fontWeight:600,
                    cursor:'pointer', fontFamily:'DM Sans, sans-serif' }}>
                  {saving ? 'Saving…' : 'Save'}
                </button>
                <button onClick={sortOptions} title="Sort A→Z"
                  style={SVL.actionBtn}>A↓Z</button>
                <button onClick={() => setShowSaveToLib(true)} disabled={saving}
                  style={{ ...SVL.actionBtn, color:'#2563eb', borderColor:'#bfdbfe' }}>
                  📚 Save to Library
                </button>
                <button onClick={deleteList} disabled={saving}
                  style={{ ...SVL.actionBtn, color:'#dc2626', borderColor:'#fecaca' }}>
                  Delete
                </button>
              </div>

              {msg && (
                <div style={{ marginTop:8, fontSize:12, fontWeight:500,
                  color: msg.startsWith('✓') ? '#22c55e' : '#dc2626' }}>{msg}</div>
              )}

              {showSaveToLib && (
                <div style={{ marginTop:10, padding:10, background:'#eff6ff',
                  border:'1px solid #bfdbfe', borderRadius:6, fontSize:12 }}>
                  <div style={{ marginBottom:8, color:'#1e40af', fontWeight:600 }}>
                    Save "{editing.name}" to private library?
                  </div>
                  <div style={{ display:'flex', gap:8 }}>
                    <button onClick={saveToLibrary}
                      style={{ flex:1, padding:'6px', background:'#2563eb', color:'#fff',
                        border:'none', borderRadius:5, fontSize:12, cursor:'pointer',
                        fontFamily:'DM Sans, sans-serif' }}>Confirm</button>
                    <button onClick={() => setShowSaveToLib(false)}
                      style={{ padding:'6px 12px', background:'#fff', color:'#64748b',
                        border:'1px solid #e2e8f0', borderRadius:5, fontSize:12,
                        cursor:'pointer', fontFamily:'DM Sans, sans-serif' }}>Cancel</button>
                  </div>
                </div>
              )}

              {/* Preview */}
              {optionCount > 0 && (
                <div style={{ marginTop:16, padding:12, background:'#f8fafc',
                  border:'1px solid #e2e8f0', borderRadius:8 }}>
                  <div style={SVL.lbl}>Preview</div>
                  <div style={{ display:'flex', flexWrap:'wrap', gap:5 }}>
                    {textToOptions(editing.optionsText || '').slice(0, 20).map((opt, i) => (
                      <span key={i} style={{ padding:'3px 10px', background:'#fff',
                        border:'1px solid #e2e8f0', borderRadius:20, fontSize:12,
                        color:'#374151' }}>
                        {typeof opt === 'string'
                          ? opt
                          : <>{opt.label} <span style={{ color:'#94a3b8' }}>| {opt.value}</span></>
                        }
                      </span>
                    ))}
                    {optionCount > 20 && (
                      <span style={{ fontSize:12, color:'#94a3b8', padding:'3px 6px' }}>
                        +{optionCount - 20} more
                      </span>
                    )}
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* ── RIGHT: library ── */}
        <div style={{ display:'table-cell', width:240, verticalAlign:'top',
          borderLeft:'1px solid #e2e8f0', background:'#fafafa' }}>
          <div style={{ padding:'10px 12px', borderBottom:'1px solid #e2e8f0',
            display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <span style={{ fontSize:11, fontWeight:700, color:'#64748b',
              textTransform:'uppercase', letterSpacing:'0.06em' }}>📚 Library</span>
            {typeof KBIcon !== 'undefined' && <KBIcon kbKey="valuelists" />}
          </div>

          {libLoading ? (
            <div style={{ padding:16, textAlign:'center', color:'#94a3b8', fontSize:12 }}>
              Loading…
            </div>
          ) : (
            <div style={{ padding:10, overflowY:'auto', maxHeight:600 }}>

              {library.public.length > 0 && (
                <>
                  <div style={{ fontSize:10, fontWeight:700, color:'#94a3b8',
                    textTransform:'uppercase', letterSpacing:'0.06em',
                    marginBottom:6 }}>🌐 Public</div>
                  {library.public.map(item => (
                    <div key={item.id} style={SVL.libItem}>
                      <div style={SVL.libName}>{item.name}</div>
                      {item.desc && (
                        <div style={SVL.libDesc}>{item.desc}</div>
                      )}
                      <div style={{ fontSize:10, color:'#94a3b8', marginBottom:4 }}>
                        {(item.options||[]).length} options
                      </div>
                      <button onClick={() => addFromLibrary(item)}
                        style={SVL.libBtn}>+ Add to App</button>
                    </div>
                  ))}
                </>
              )}

              {library.private.length > 0 && (
                <>
                  <div style={{ fontSize:10, fontWeight:700, color:'#94a3b8',
                    textTransform:'uppercase', letterSpacing:'0.06em',
                    margin:'12px 0 6px' }}>🔒 Private</div>
                  {library.private.map(item => (
                    <div key={item.id} style={SVL.libItem}>
                      <div style={SVL.libName}>{item.name}</div>
                      <button onClick={() => addFromLibrary(item)}
                        style={SVL.libBtn}>+ Add to App</button>
                    </div>
                  ))}
                </>
              )}

              {library.public.length === 0 && library.private.length === 0 && (
                <div style={{ padding:'20px 0', textAlign:'center',
                  color:'#94a3b8', fontSize:12 }}>
                  No library items yet.
                </div>
              )}
            </div>
          )}
        </div>

      </div>

      {/* Icon browser overlay */}
      {vlIconBrowser && typeof IconBrowser !== 'undefined' && (
        <IconBrowser
          onSelect={val => { setEditing(p => ({...p, icon: val})); setVlIconBrowser(false); }}
          onClose={() => setVlIconBrowser(false)}
        />
      )}
    </div>
  );
}

// ─────────────────────────────────────────────
// Styles — prefix SVL
// ─────────────────────────────────────────────
const SVL = {
  lbl:      { fontSize:10, fontWeight:700, color:'#94a3b8', textTransform:'uppercase',
              letterSpacing:'0.06em', marginBottom:4, display:'block' },
  input:    { width:'100%', padding:'7px 10px', border:'1.5px solid #e2e8f0',
              borderRadius:6, fontSize:13, fontFamily:'DM Sans, sans-serif',
              outline:'none', marginBottom:12, boxSizing:'border-box', display:'block' },
  actionBtn:{ padding:'9px 12px', background:'#fff', color:'#374151',
              border:'1px solid #e2e8f0', borderRadius:6, fontSize:13,
              cursor:'pointer', fontFamily:'DM Sans, sans-serif' },
  libItem:  { background:'#fff', border:'1px solid #e2e8f0', borderRadius:7,
              padding:'10px', marginBottom:8 },
  libName:  { fontSize:12, fontWeight:600, color:'#1e293b', marginBottom:2 },
  libDesc:  { fontSize:11, color:'#94a3b8', marginBottom:4 },
  libBtn:   { width:'100%', padding:'5px', background:'#0f1923', color:'#fff',
              border:'none', borderRadius:5, fontSize:11, cursor:'pointer',
              fontFamily:'DM Sans, sans-serif' },
};
