/* global React, window */
/* ============================================
   VpsEditor — Admin modal to edit ALL VPS data:
   name, colour, price, specs, locations, perks,
   signup links, intro, ordering, add/remove.
   Saves to Firestore → live for every visitor.
   ============================================ */

const VPS_FIELDS = [
  { key: 'tagline',   label: 'Tagline',            ph: 'Short selling point', wide: true },
  { key: 'price',     label: 'Price',              ph: 'From $29/mo' },
  { key: 'latency',   label: 'Latency',            ph: '< 1 ms to brokers' },
  { key: 'uptime',    label: 'Uptime',             ph: '99.99% uptime' },
  { key: 'locations', label: 'Server locations (· separated)', ph: 'NY · London · Frankfurt', wide: true },
  { key: 'perks',     label: 'Key advantages (· separated)',   ph: 'Free setup · 24/7 support · DDoS protection', wide: true },
  { key: 'signupUrl', label: 'Sign-up link (your affiliate URL)', ph: 'https://...', wide: true },
  { key: 'logoUrl',   label: 'Logo image URL (optional)', ph: 'https://...', wide: true },
];

const VPS_COLORS = ['#1FA2FF', '#7C5CFF', '#00B97A', '#FF7A00', '#00E5FF', '#FF2DAA', '#F3D000', '#E4002B'];

function newVpsId() { return 'vps_' + Math.random().toString(36).slice(2, 8); }

function VpsEditor({ onClose }) {
  const [list, setList] = React.useState(() => (window.VpsStore?.getVps?.() || []).map(v => ({ ...v })));
  const [intro, setIntro] = React.useState(() => window.VpsStore?.getIntro?.() || '');
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);
  const [openId, setOpenId] = React.useState(list[0]?.id || null);

  function setField(id, key, value) { setList(l => l.map(v => v.id === id ? { ...v, [key]: value } : v)); }
  function move(i, dir) {
    setList(l => {
      const j = i + dir;
      if (j < 0 || j >= l.length) return l;
      const copy = [...l];
      [copy[i], copy[j]] = [copy[j], copy[i]];
      return copy;
    });
  }
  function removeVps(id) { if (confirm('Remove this VPS provider?')) setList(l => l.filter(v => v.id !== id)); }
  function addVps() {
    const v = { id: newVpsId(), name: 'New VPS', color: '#00E5FF', tagline: '', price: '', latency: '', uptime: '', locations: '', perks: '', signupUrl: '', logoUrl: '', featured: false };
    setList(l => [...l, v]);
    setOpenId(v.id);
  }

  async function save() {
    setError(''); setSaving(true); setSuccess(false);
    try {
      const clean = list.map(v => ({
        id: v.id || newVpsId(),
        name: (v.name || '').trim() || 'Untitled',
        color: v.color || '#00E5FF',
        tagline: v.tagline || '',
        price: v.price || '',
        latency: v.latency || '',
        uptime: v.uptime || '',
        locations: v.locations || '',
        perks: v.perks || '',
        signupUrl: (v.signupUrl || '').trim(),
        logoUrl: (v.logoUrl || '').trim(),
        featured: !!v.featured,
      }));
      await window.VpsStore.saveVps(clean, intro);
      setSuccess(true);
      setTimeout(onClose, 800);
    } catch (e) {
      setError(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 860 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · VPS</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>Edit recommended VPS</h2>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        <div style={{ maxHeight: '78vh', overflowY: 'auto', paddingRight: 8 }}>
          <div className="field mb-4">
            <label>Intro / recommendation text</label>
            <textarea className="input" rows="3" value={intro} onChange={e => setIntro(e.target.value)}
              placeholder="Why you recommend these VPS providers"/>
          </div>

          <div className="divider" style={{ margin: '8px 0 16px' }}/>

          <div className="flex-col gap-3">
            {list.map((v, i) => {
              const open = openId === v.id;
              return (
                <div key={v.id} style={{ border: '1px solid var(--line)', borderRadius: 12, background: 'rgba(255,255,255,0.02)', overflow: 'hidden' }}>
                  <div className="flex gap-2" style={{ alignItems: 'center', padding: '10px 12px' }}>
                    <span style={{ width: 22, height: 22, borderRadius: 6, background: v.color, flexShrink: 0, boxShadow: `0 0 10px ${v.color}66` }}/>
                    <div style={{ flex: 1, minWidth: 0, cursor: 'pointer' }} onClick={() => setOpenId(open ? null : v.id)}>
                      <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v.name}{v.featured ? '  ★' : ''}</div>
                    </div>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => move(i, -1)} disabled={i === 0} style={{ padding: '4px 8px' }}>↑</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => move(i, 1)} disabled={i === list.length - 1} style={{ padding: '4px 8px' }}>↓</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpenId(open ? null : v.id)} style={{ padding: '4px 8px' }}>{open ? '▲' : '▼'}</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeVps(v.id)} style={{ padding: '4px 8px', color: 'var(--red)' }}>×</button>
                  </div>

                  {open && (
                    <div style={{ padding: '4px 12px 14px' }}>
                      <div className="field mb-3">
                        <label>Provider name</label>
                        <input className="input" value={v.name} onChange={e => setField(v.id, 'name', e.target.value)} placeholder="Provider name"/>
                      </div>

                      <div className="field mb-3">
                        <label>Brand colour</label>
                        <div className="flex gap-2" style={{ flexWrap: 'wrap', alignItems: 'center' }}>
                          {VPS_COLORS.map(c => (
                            <button key={c} type="button" onClick={() => setField(v.id, 'color', c)}
                              style={{ width: 26, height: 26, borderRadius: 7, background: c, cursor: 'pointer',
                                border: v.color === c ? '2px solid #fff' : '2px solid transparent', boxShadow: `0 0 8px ${c}66` }}/>
                          ))}
                          <input type="color" value={v.color} onChange={e => setField(v.id, 'color', e.target.value)}
                            style={{ width: 34, height: 28, border: 'none', background: 'none', cursor: 'pointer' }}/>
                        </div>
                      </div>

                      <div className="field mb-3">
                        <label className="flex gap-2" style={{ alignItems: 'center', cursor: 'pointer' }}>
                          <input type="checkbox" checked={!!v.featured} onChange={e => setField(v.id, 'featured', e.target.checked)}/>
                          <span>Mark as “Top pick” (highlighted badge)</span>
                        </label>
                      </div>

                      <div className="grid grid-2" style={{ gap: 12 }}>
                        {VPS_FIELDS.map(f => (
                          <div className="field" key={f.key} style={f.wide ? { gridColumn: '1 / -1' } : null}>
                            <label>{f.label}</label>
                            <input className="input" value={v[f.key] || ''} onChange={e => setField(v.id, f.key, e.target.value)} placeholder={f.ph}/>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          <button type="button" className="btn btn-secondary mt-4" onClick={addVps}>+ Add VPS provider</button>
        </div>

        {error && <div className="panel mt-3" style={{ padding: 10, background: 'rgba(255,59,92,0.08)', borderColor: 'rgba(255,59,92,0.3)' }}><span className="text-red font-mono text-xs">⚠ {error}</span></div>}
        {success && <div className="panel mt-3" style={{ padding: 10, background: 'rgba(0,255,148,0.08)', borderColor: 'rgba(0,255,148,0.3)' }}><span className="text-green font-mono text-xs">✓ Saved · changes are live</span></div>}

        <div className="flex gap-2 mt-4">
          <div style={{ flex: 1 }}/>
          <button className="btn btn-ghost" onClick={onClose} disabled={saving}>Cancel</button>
          <button className="btn btn-primary btn-sheen" onClick={save} disabled={saving}>
            {saving ? <span className="typing"><span/><span/><span/></span> : 'Save & publish'}
          </button>
        </div>
      </div>
    </Modal>
  );
}

window.VpsEditor = VpsEditor;
