/* global React, firebase */
/* ============================================
   EAReviewsEditor — Admin modal to edit customer reviews
   Stores on /eas/{eaId}:
     reviews : [{ name, stars, text, date }]
     rating  : number   (aggregate shown next to ★)
   ============================================ */
function EAReviewsEditor({ ea, onClose }) {
  const DEFAULT_REVIEWS = [
    { name: 'Ahmed M.', stars: 5, text: 'Running this on prop firm account. Passed phase 1 in 11 days. The full backtest report sold me — every trade documented.', date: '2 days ago' },
    { name: 'Linda B.', stars: 5, text: 'PF and DD match the marketplace claims exactly. I verified against my own MT5 logs.', date: '6 days ago' },
    { name: 'Yuki T.', stars: 4, text: 'Great EA but watch the news filter on JPY pairs. Minor issue, AI Agent helped me tune it.', date: '2 weeks ago' },
    { name: 'Faris A.', stars: 5, text: 'AWS VPS template installed in 4 minutes. EA was profitable on day 1.', date: '3 weeks ago' },
  ];

  const [reviews, setReviews] = React.useState(
    (Array.isArray(ea.reviews) && ea.reviews.length ? ea.reviews : DEFAULT_REVIEWS)
      .map(r => ({ name: r.name ?? '', stars: r.stars ?? 5, text: r.text ?? '', date: r.date ?? '' }))
  );
  const [rating, setRating] = React.useState(ea.rating ?? 4.8);
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);

  const setRev = (i, key, val) => setReviews(l => l.map((r, idx) => idx === i ? { ...r, [key]: val } : r));
  const addRev = () => setReviews(l => [...l, { name: 'New reviewer', stars: 5, text: '', date: 'just now' }]);
  const removeRev = i => setReviews(l => l.filter((_, idx) => idx !== i));
  const moveRev = (i, dir) => setReviews(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;
  });

  async function save() {
    setError(''); setSaving(true); setSuccess(false);
    try {
      const clean = reviews
        .map(r => ({
          name: String(r.name || '').trim(),
          stars: Math.max(1, Math.min(5, parseInt(r.stars, 10) || 5)),
          text: String(r.text || '').trim(),
          date: String(r.date || '').trim() || 'recently',
        }))
        .filter(r => r.name && r.text);
      const nr = parseFloat(rating);
      const payload = {
        reviews: clean,
        rating: isNaN(nr) ? 4.8 : Math.max(0, Math.min(5, nr)),
      };
      await window.EAReports.saveEAFields(ea.id, payload);
      setSuccess(true);
      setTimeout(onClose, 800);
    } catch (e) {
      setError(e.message || 'Save failed');
    } finally {
      setSaving(false);
    }
  }

  return (
    <Modal onClose={onClose}>
      <div style={{ width: '100%', maxWidth: 640 }}>
        <div className="flex-between mb-4">
          <div>
            <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · EDIT REVIEWS · v1</span>
            <h2 className="mt-2" style={{ fontSize: 22 }}>{ea.name} · Reviews</h2>
          </div>
          <button onClick={onClose} className="btn btn-ghost btn-sm">×</button>
        </div>

        {/* Aggregate rating */}
        <div className="field mb-4" style={{ maxWidth: 220 }}>
          <label>Aggregate rating (0–5)</label>
          <input className="input font-mono" type="number" min="0" max="5" step="0.1" value={rating} onChange={e => setRating(e.target.value)}/>
          <div className="text-xs text-muted mt-1">Count is taken from the list below.</div>
        </div>

        <div style={{ maxHeight: '52vh', overflowY: 'auto', paddingRight: 8 }}>
          <div className="flex-col gap-3">
            {reviews.map((rv, i) => (
              <div key={i} style={{ border: '1px solid var(--line)', borderRadius: 10, padding: 12, background: 'rgba(255,255,255,0.02)' }}>
                <div className="flex-between" style={{ marginBottom: 10 }}>
                  <span className="font-mono text-xs text-muted">REVIEW {i + 1}</span>
                  <div className="flex gap-1">
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveRev(i, -1)} disabled={i === 0}>↑</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => moveRev(i, 1)} disabled={i === reviews.length - 1}>↓</button>
                    <button type="button" className="btn btn-ghost btn-sm" onClick={() => removeRev(i)} style={{ color: 'var(--red)' }}>× Remove</button>
                  </div>
                </div>
                <div className="flex gap-2" style={{ flexWrap: 'wrap', marginBottom: 8 }}>
                  <div style={{ flex: '2 1 160px' }}>
                    <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Name</div>
                    <input className="input" style={{ width: '100%' }} value={rv.name} onChange={e => setRev(i, 'name', e.target.value)}/>
                  </div>
                  <div style={{ flex: '1 1 120px' }}>
                    <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Date</div>
                    <input className="input" style={{ width: '100%' }} placeholder="2 days ago" value={rv.date} onChange={e => setRev(i, 'date', e.target.value)}/>
                  </div>
                  <div style={{ flex: '1 1 120px' }}>
                    <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Stars</div>
                    <div className="flex gap-1" style={{ alignItems: 'center' }}>
                      {[1, 2, 3, 4, 5].map(n => (
                        <button key={n} type="button" onClick={() => setRev(i, 'stars', n)} style={{
                          background: 'transparent', border: 'none', cursor: 'pointer', padding: 2, fontSize: 20, lineHeight: 1,
                          color: n <= rv.stars ? 'var(--amber)' : 'var(--text-4)',
                        }}>★</button>
                      ))}
                    </div>
                  </div>
                </div>
                <div>
                  <div className="font-mono text-xs text-muted" style={{ marginBottom: 4 }}>Review text</div>
                  <textarea className="input" rows={3} style={{ width: '100%' }} value={rv.text} onChange={e => setRev(i, 'text', e.target.value)}/>
                </div>
              </div>
            ))}
            <button type="button" className="btn btn-secondary btn-sm" onClick={addRev} style={{ alignSelf: 'flex-start' }}>+ Add review</button>
          </div>
        </div>

        {error && <div className="strat-pdf-error" style={{ marginTop: 12 }}>⚠ {error}</div>}

        <div className="flex gap-2 mt-4">
          <button className="btn btn-primary btn-block" onClick={save} disabled={saving}>
            {success ? '✓ Saved' : saving ? 'Saving…' : 'Save & publish'}
          </button>
          <button className="btn btn-ghost" onClick={onClose} disabled={saving}>Cancel</button>
        </div>
      </div>
    </Modal>
  );
}

window.EAReviewsEditor = EAReviewsEditor;
