/* global React */
/* ============================================
   SiteSettings — Admin modal
   • Featured ordering for "Top-performing this month"
   • Category management (marketplace filters + EA strategy options)
   ============================================ */
function SiteSettings({ onClose }) {
  const allEAs = window.EAReports?.effectiveList?.() || window.EA_LIST || [];
  const cfg = window.EAReports?.getSiteConfig?.() || { featured: [], categories: [] };

  // Featured: ordered list of EA ids. Default to first 3 if unset.
  const [featured, setFeatured] = React.useState(() =>
    (cfg.featured && cfg.featured.length ? cfg.featured : allEAs.slice(0, 3).map(e => e.id))
      .filter(id => allEAs.some(e => e.id === id))
  );
  const [categories, setCategories] = React.useState(() => [...(cfg.categories || [])]);
  const [newCat, setNewCat] = React.useState('');
  // ── Marketplace ordering ──
  const [marketOrder, setMarketOrder] = React.useState(cfg.marketOrder || 'default');
  const [marketIds, setMarketIds] = React.useState(() => {
    const saved = (cfg.marketOrderIds || []).filter(id => allEAs.some(e => e.id === id));
    const missing = allEAs.map(e => e.id).filter(id => !saved.includes(id));
    return [...saved, ...missing];
  });
  function moveMarket(i, dir) {
    setMarketIds(list => {
      const j = i + dir;
      if (j < 0 || j >= list.length) return list;
      const copy = [...list];
      [copy[i], copy[j]] = [copy[j], copy[i]];
      return copy;
    });
  }
  // ── Promo codes ──
  const [promos, setPromos] = React.useState(() => (cfg.promoCodes || []).map(p => ({
    code: p.code || '', type: p.type === 'fixed' ? 'fixed' : 'percent',
    value: p.value ?? '', active: p.active !== false,
    expires: p.expires || '', minAmount: p.minAmount ?? '', maxUses: p.maxUses ?? '', uses: p.uses || 0,
  })));
  function setPromo(i, key, val) { setPromos(list => list.map((p, k) => k === i ? { ...p, [key]: val } : p)); }
  function addPromo() { setPromos(list => [...list, { code: '', type: 'percent', value: 10, active: true, expires: '', minAmount: '', maxUses: '', uses: 0 }]); }
  function removePromo(i) { setPromos(list => list.filter((_, k) => k !== i)); }
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);

  const byId = {};
  allEAs.forEach(e => { byId[e.id] = e; });
  const available = allEAs.filter(e => !featured.includes(e.id));

  // ── Featured ops ──
  function addFeatured(id) { setFeatured(f => [...f, id]); }
  function removeFeatured(id) { setFeatured(f => f.filter(x => x !== id)); }
  function moveFeatured(i, dir) {
    setFeatured(f => {
      const j = i + dir;
      if (j < 0 || j >= f.length) return f;
      const copy = [...f];
      [copy[i], copy[j]] = [copy[j], copy[i]];
      return copy;
    });
  }

  // ── Category ops ──
  function addCategory() {
    const v = newCat.trim();
    if (!v) return;
    if (categories.some(c => c.toLowerCase() === v.toLowerCase())) { setNewCat(''); return; }
    setCategories(c => [...c, v]);
    setNewCat('');
  }
  function removeCategory(i) { setCategories(c => c.filter((_, idx) => idx !== i)); }
  function renameCategory(i, v) { setCategories(c => c.map((x, idx) => idx === i ? v : x)); }
  function moveCategory(i, dir) {
    setCategories(c => {
      const j = i + dir;
      if (j < 0 || j >= c.length) return c;
      const copy = [...c];
      [copy[i], copy[j]] = [copy[j], copy[i]];
      return copy;
    });
  }

  async function save() {
    setError(''); setSaving(true); setSuccess(false);
    try {
      const cleanCats = categories.map(c => String(c).trim()).filter(Boolean);
      const cleanPromos = promos
        .map(p => ({
          code: String(p.code || '').trim().toUpperCase(),
          type: p.type === 'fixed' ? 'fixed' : 'percent',
          value: Math.max(0, parseFloat(p.value) || 0),
          active: p.active !== false,
          expires: String(p.expires || '').trim(),
          minAmount: p.minAmount === '' ? 0 : Math.max(0, parseFloat(p.minAmount) || 0),
          maxUses: p.maxUses === '' ? 0 : Math.max(0, parseInt(p.maxUses, 10) || 0),
          uses: p.uses || 0,
        }))
        .filter(p => p.code);
      await window.EAReports.saveSiteConfig({ featured, categories: cleanCats, marketOrder, marketOrderIds: marketIds, promoCodes: cleanPromos });
      setSuccess(true);
      setTimeout(onClose, 800);
    } catch (e) {
      setError(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  const thumb = (ea) => (
    <span style={{
      width: 34, height: 34, borderRadius: 8, flexShrink: 0, overflow: 'hidden',
      background: ea.imageUrl ? `center/cover url(${ea.imageUrl})` : 'var(--grad-1)',
      display: 'grid', placeItems: 'center', color: '#000', fontWeight: 700, fontSize: 13,
      fontFamily: 'var(--font-mono)',
    }}>{ea.imageUrl ? '' : (ea.name || '?').slice(0, 1)}</span>
  );

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

        <div style={{ maxHeight: '62vh', overflowY: 'auto', paddingRight: 8 }}>

          {/* ── Featured / Top-performing ── */}
          <div className="field mb-3">
            <label>Top-performing this month · home page order</label>
            <div className="text-xs text-muted mb-3">Pick which EAs appear in the home “Top-performing” section and drag them into order.</div>

            <div className="flex-col gap-2">
              {featured.length === 0 && (
                <div className="font-mono text-xs text-muted" style={{ padding: '8px 2px' }}>// none selected — add EAs below</div>
              )}
              {featured.map((id, i) => {
                const ea = byId[id];
                if (!ea) return null;
                return (
                  <div key={id} className="flex gap-3" style={{ alignItems: 'center', border: '1px solid var(--line)', borderRadius: 10, padding: '8px 10px', background: 'rgba(255,255,255,0.02)' }}>
                    <span className="font-mono text-xs" style={{ color: 'var(--cyan)', width: 18 }}>{i + 1}</span>
                    {thumb(ea)}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ea.name}</div>
                      <div className="font-mono text-xs text-muted">{ea.strategy}</div>
                    </div>
                    <div className="flex gap-1">
                      <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveFeatured(i, -1)} disabled={i === 0} title="Move up" style={{ padding: '4px 8px' }}>↑</button>
                      <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveFeatured(i, 1)} disabled={i === featured.length - 1} title="Move down" style={{ padding: '4px 8px' }}>↓</button>
                      <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeFeatured(id)} title="Remove" style={{ padding: '4px 8px', color: 'var(--red)' }}>×</button>
                    </div>
                  </div>
                );
              })}
            </div>

            {available.length > 0 && (
              <>
                <div className="font-mono text-xs text-muted mt-4 mb-2" style={{ letterSpacing: '0.12em' }}>+ ADD TO FEATURED</div>
                <div className="flex gap-2" style={{ flexWrap: 'wrap' }}>
                  {available.map(ea => (
                    <button key={ea.id} type="button" className="btn btn-ghost btn-sm" onClick={() => addFeatured(ea.id)}>
                      + {ea.name}
                    </button>
                  ))}
                </div>
              </>
            )}
          </div>

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

          {/* ── Marketplace ordering ── */}
          <div className="field mb-3">
            <label>Marketplace order · default card order</label>
            <div className="text-xs text-muted mb-3">Choose how Expert Advisors are ordered by default in the marketplace. Visitors can still re-sort with the dropdown.</div>

            <div className="flex gap-2" style={{ flexWrap: 'wrap', marginBottom: 12 }}>
              {[
                { id: 'default', label: 'Default' },
                { id: 'newest', label: 'Newest first' },
                { id: 'manual', label: 'Manual (free order)' },
              ].map(opt => (
                <button key={opt.id} type="button"
                  className={`btn btn-sm ${marketOrder === opt.id ? 'btn-primary' : 'btn-ghost'}`}
                  onClick={() => setMarketOrder(opt.id)}>{opt.label}</button>
              ))}
            </div>

            {marketOrder === 'newest' && (
              <div className="font-mono text-xs text-muted" style={{ padding: '2px 2px' }}>// Newest EAs (most recently added) appear first.</div>
            )}
            {marketOrder === 'default' && (
              <div className="font-mono text-xs text-muted" style={{ padding: '2px 2px' }}>// Uses the catalog's built-in order.</div>
            )}

            {marketOrder === 'manual' && (
              <div className="flex-col gap-2">
                <div className="font-mono text-xs text-muted mb-1" style={{ letterSpacing: '0.1em' }}>DRAG INTO ORDER · top shows first</div>
                {marketIds.map((id, i) => {
                  const ea = byId[id];
                  if (!ea) return null;
                  return (
                    <div key={id} className="flex gap-3" style={{ alignItems: 'center', border: '1px solid var(--line)', borderRadius: 10, padding: '8px 10px', background: 'rgba(255,255,255,0.02)' }}>
                      <span className="font-mono text-xs" style={{ color: 'var(--cyan)', width: 18 }}>{i + 1}</span>
                      {thumb(ea)}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ea.name}</div>
                        <div className="font-mono text-xs text-muted">{ea.strategy}</div>
                      </div>
                      <div className="flex gap-1">
                        <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveMarket(i, -1)} disabled={i === 0} title="Move up" style={{ padding: '4px 8px' }}>↑</button>
                        <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveMarket(i, 1)} disabled={i === marketIds.length - 1} title="Move down" style={{ padding: '4px 8px' }}>↓</button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

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

          {/* ── Categories ── */}
          <div className="field mb-3">
            <label>Categories · marketplace filters & EA strategy options</label>
            <div className="text-xs text-muted mb-3">These appear as filter buttons in the marketplace and as strategy options when editing an EA.</div>

            <div className="flex-col gap-2">
              {categories.length === 0 && (
                <div className="font-mono text-xs text-muted" style={{ padding: '8px 2px' }}>// no categories yet — the marketplace uses default filters until you add some</div>
              )}
              {categories.map((c, i) => (
                <div key={i} className="flex gap-2" style={{ alignItems: 'center' }}>
                  <input className="input" style={{ flex: 1 }} value={c} onChange={e => renameCategory(i, e.target.value)} placeholder="Category name"/>
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveCategory(i, -1)} disabled={i === 0} style={{ padding: '4px 8px' }}>↑</button>
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveCategory(i, 1)} disabled={i === categories.length - 1} style={{ padding: '4px 8px' }}>↓</button>
                  <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeCategory(i)} style={{ padding: '4px 8px', color: 'var(--red)' }}>×</button>
                </div>
              ))}
            </div>

            <div className="flex gap-2 mt-3">
              <input className="input" style={{ flex: 1 }} value={newCat} onChange={e => setNewCat(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addCategory(); } }} placeholder="New category, e.g. Scalping"/>
              <button type="button" className="btn btn-secondary" onClick={addCategory}>+ Add</button>
            </div>
          </div>

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

          {/* ── Promo codes ── */}
          <div className="field mb-3">
            <label>Promo codes · discounts at checkout</label>
            <div className="text-xs text-muted mb-3">Create discount codes buyers enter on the checkout page. Percentage or fixed amount, with optional expiry, minimum order, and usage limit.</div>

            <div className="flex-col gap-3">
              {promos.length === 0 && (
                <div className="font-mono text-xs text-muted" style={{ padding: '8px 2px' }}>// no promo codes yet — add one below</div>
              )}
              {promos.map((p, i) => {
                const limitReached = p.maxUses && p.maxUses > 0 && (p.uses || 0) >= p.maxUses;
                return (
                  <div key={i} style={{ border: '1px solid var(--line)', borderRadius: 10, padding: 12, background: p.active === false ? 'rgba(255,255,255,0.015)' : 'rgba(0,229,255,0.03)', opacity: p.active === false ? 0.6 : 1 }}>
                    <div className="flex gap-2" style={{ flexWrap: 'wrap', alignItems: 'flex-end' }}>
                      <div style={{ flex: '1 1 140px' }}>
                        <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Code</div>
                        <input className="input font-mono" style={{ width: '100%', textTransform: 'uppercase' }} value={p.code} placeholder="WELCOME10" onChange={e => setPromo(i, 'code', e.target.value.toUpperCase().replace(/\s+/g, ''))}/>
                      </div>
                      <div style={{ flex: '0 0 auto' }}>
                        <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Type</div>
                        <div className="flex gap-1">
                          <button type="button" className={`btn btn-sm ${p.type === 'percent' ? 'btn-primary' : 'btn-ghost'}`} onClick={() => setPromo(i, 'type', 'percent')} style={{ padding: '6px 10px' }}>%</button>
                          <button type="button" className={`btn btn-sm ${p.type === 'fixed' ? 'btn-primary' : 'btn-ghost'}`} onClick={() => setPromo(i, 'type', 'fixed')} style={{ padding: '6px 10px' }}>$</button>
                        </div>
                      </div>
                      <div style={{ flex: '1 1 90px' }}>
                        <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>{p.type === 'percent' ? 'Percent off' : 'Amount off ($)'}</div>
                        <input className="input font-mono" style={{ width: '100%' }} type="number" min="0" value={p.value} onChange={e => setPromo(i, 'value', e.target.value)}/>
                      </div>
                    </div>
                    <div className="flex gap-2 mt-2" style={{ flexWrap: 'wrap', alignItems: 'flex-end' }}>
                      <div style={{ flex: '1 1 130px' }}>
                        <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Expires (optional)</div>
                        <input className="input" style={{ width: '100%' }} type="date" value={p.expires} onChange={e => setPromo(i, 'expires', e.target.value)}/>
                      </div>
                      <div style={{ flex: '1 1 100px' }}>
                        <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Min order $</div>
                        <input className="input font-mono" style={{ width: '100%' }} type="number" min="0" placeholder="0" value={p.minAmount} onChange={e => setPromo(i, 'minAmount', e.target.value)}/>
                      </div>
                      <div style={{ flex: '1 1 100px' }}>
                        <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Max uses</div>
                        <input className="input font-mono" style={{ width: '100%' }} type="number" min="0" placeholder="∞" value={p.maxUses} onChange={e => setPromo(i, 'maxUses', e.target.value)}/>
                      </div>
                    </div>
                    <div className="flex-between mt-3" style={{ alignItems: 'center' }}>
                      <div className="flex gap-3" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
                        <button type="button" className={`btn btn-sm ${p.active === false ? 'btn-ghost' : 'btn-secondary'}`} onClick={() => setPromo(i, 'active', !(p.active !== false))} style={{ padding: '4px 12px' }}>
                          {p.active === false ? 'Inactive' : 'Active'}
                        </button>
                        <span className="font-mono text-xs text-muted">used {p.uses || 0}{p.maxUses ? ` / ${p.maxUses}` : ''}{limitReached ? ' · limit reached' : ''}</span>
                      </div>
                      <button type="button" className="btn btn-ghost btn-sm" onClick={() => removePromo(i)} style={{ padding: '4px 8px', color: 'var(--red)' }}>× Remove</button>
                    </div>
                  </div>
                );
              })}
            </div>
            <button type="button" className="btn btn-secondary mt-3" onClick={addPromo}>+ Add promo code</button>
          </div>
        </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.SiteSettings = SiteSettings;
