/* Public review form */

const Review = () => {
  const { lang } = useLang();
  const params = React.useMemo(() => {
    const query = (window.location.hash.split('?')[1] || '');
    return new URLSearchParams(query);
  }, []);
  const [form, setForm] = React.useState({
    orderNumber: params.get('order') || '',
    email: '',
    rating: 5,
    review: '',
    photo: '',
    photoFile: null,
    _hp: ''
  });
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const set = (patch) => setForm((cur) => ({ ...cur, ...patch }));
  const copy = lang === 'en'
    ? {
      eyebrow: 'Review',
      title: 'Review your Titan Case',
      sub: 'Use the same email from your order so we can verify it.',
      order: 'Order number',
      email: 'Order email',
      rating: 'Stars',
      body: 'Review (max 500 characters)',
      photo: 'Photo (optional)',
      photoPlaceholder: 'Add a photo of your case',
      button: 'Send review',
      sent: 'Review saved. It will appear after approval.',
      thanksTitle: 'Thanks for your review!',
      thanksSub: 'Your review has been saved and will appear on the site after verification. Thanks for taking the time to share your experience.',
      thanksBack: 'Back to home'
    }
    : {
      eyebrow: 'Recensione',
      title: 'Recensisci la tua Titan Case',
      sub: 'Usa la stessa email dell ordine per verificarla.',
      order: 'Numero ordine',
      email: 'Email ordine',
      rating: 'Stelle',
      body: 'Recensione (max 500 caratteri)',
      photo: 'Foto (opzionale)',
      photoPlaceholder: 'Aggiungi una foto della tua cover',
      button: 'Invia recensione',
      sent: 'Recensione salvata. Apparira dopo approvazione.',
      thanksTitle: 'Grazie per la recensione!',
      thanksSub: 'La tua recensione e stata salvata e apparira sul sito dopo la verifica. Grazie per aver dedicato del tempo a condividere la tua esperienza.',
      thanksBack: 'Torna alla home'
    };

  const submit = async (event) => {
    event.preventDefault();
    if (loading) return;
    setLoading(true);
    setError('');
    setSent(false);

    let photoUrl = '';
    if (form.photoFile) {
      setUploading(true);
      const uploadResult = await uploadFile(form.photoFile);
      setUploading(false);
      if (!uploadResult.ok) {
        setError(uploadResult.error || 'Photo upload failed.');
        setLoading(false);
        return;
      }
      photoUrl = uploadResult.url;
    }

    const result = await submitRecord('/api/reviews', {
      orderNumber: form.orderNumber,
      email: form.email,
      rating: Number(form.rating),
      review: form.review,
      photoUrl: photoUrl || null,
      language: lang
    });
    setLoading(false);
    if (result.ok) {
      setSent(true);
      setForm({ orderNumber: '', email: '', rating: 5, review: '', photo: '', photoFile: null, _hp: '' });
    } else {
      setError(result.error || 'Request failed.');
    }
  };

  if (sent) {
    return (
      <section className="section">
        <div className="container stack" style={{ gap: 20, maxWidth: 560, margin: '0 auto', textAlign: 'center', alignItems: 'center' }}>
          <div className="eyebrow">{copy.eyebrow}</div>
          <h1 className="h-1">{copy.thanksTitle}</h1>
          <p className="lead">{copy.thanksSub}</p>
          <div className="row wrap" style={{ justifyContent: 'center' }}>
            <button className="btn btn-primary btn-lg" onClick={() => { setSent(false); setForm({ orderNumber: '', email: '', rating: 5, review: '', photo: '', photoFile: null, _hp: '' }); }}>
              {lang === 'en' ? 'Write another review' : 'Scrivi un\'altra recensione'}
            </button>
            <Link to="/" className="btn btn-secondary btn-lg">{copy.thanksBack}</Link>
          </div>
        </div>
      </section>
    );
  }

  return (
    <>
      <PageHero eyebrow={copy.eyebrow} title={copy.title} sub={copy.sub} />
      <section className="section-tight">
        <div className="container">
          <form className="surface stack" style={{ padding: 22, maxWidth: 680, margin: '0 auto' }} onSubmit={submit} autoComplete="off">
            {error && <p className="notice notice-danger" role="alert">{error}</p>}
            <div className="grid cols-2">
              <Field label={copy.order}>
                <input className="input" required value={form.orderNumber} onChange={(event) => set({ orderNumber: event.target.value })} autoComplete="off" />
              </Field>
              <Field label={copy.email}>
                <input className="input" type="email" required autoComplete="email" value={form.email} onChange={(event) => set({ email: event.target.value })} />
              </Field>
            </div>
            <Field label={copy.rating}>
              <select className="input" value={form.rating} onChange={(event) => set({ rating: event.target.value })}>
                {[5, 4, 3, 2, 1].map((rating) => <option key={rating} value={rating}>{rating} {'★'.repeat(rating)}</option>)}
              </select>
            </Field>
            <Field label={copy.body}>
              <textarea className="textarea" required minLength="1" maxLength="500" value={form.review} onChange={(event) => set({ review: event.target.value })} autoComplete="off"></textarea>
            </Field>
            <Field label={copy.photo}>
              <label className="choice photo-choice">
                <input
                  type="file"
                  hidden
                  accept="image/png,image/jpeg,image/webp"
                  onChange={(event) => {
                    const file = event.target.files && event.target.files[0];
                    if (!file) {
                      set({ photo: '', photoFile: null });
                      return;
                    }
                    if (!/^image\/(png|jpeg|webp)$/.test(file.type) || file.size > 5 * 1024 * 1024) {
                      setError(lang === 'en' ? 'Use a PNG, JPG, or WebP image under 5 MB.' : 'Usa un file PNG, JPG o WebP sotto 5 MB.');
                      event.target.value = '';
                      return;
                    }
                    setError('');
                    set({ photo: file.name, photoFile: file });
                  }}
                />
                <span>{form.photo || copy.photoPlaceholder}</span>
              </label>
            </Field>
            <input type="text" value={form._hp} onChange={(event) => set({ _hp: event.target.value })} tabIndex="-1" autoComplete="off" className="hp-field" aria-hidden="true" />
            <button className="btn btn-primary btn-block" type="submit" disabled={loading}>
              {loading ? <span className="dot-loader"><span></span><span></span><span></span></span> : uploading ? (lang === 'en' ? 'Uploading photo...' : 'Caricamento foto...') : copy.button}
            </button>
          </form>
        </div>
      </section>
    </>
  );
};

window.Review = Review;
