/* global React */
// Reviews
const { useState } = React;
const NS_R = window.GamekeepersCottageDesignSystem_070bc7;
const { Eyebrow, Button, Card, Rating } = NS_R;
const useShell = window.GKuseShell;
const useReviews = window.GKuseReviews;
const reviewMonth = window.GKreviewMonth;
const reviewStats = window.GKreviewStats;

const REVIEWS = [
  ['A winter woodland paradise', 'One of the loveliest places we have ever stayed — cosy and characterful, with a stunning garden and an abundance of woodland wildlife. We had the entire place to ourselves, apart from the many birds at the feeders. We will definitely be back.', 'JP', 'January 2026'],
  ['Idyllic', 'Such a beautiful, secluded location. A week of sunny weather made it ideal for sitting out and listening to nature, a BBQ and the occasional glass of wine. We all loved it — just how life should be.', 'Mark Rawlinson', 'September 2025'],
  ['Perfect setting for Easter week in Suffolk', 'We saw deer, buzzard and woodpeckers in the wood, with plenty of birds on the feeders. Just stopping to listen to the sounds of nature was wonderful. I couldn’t recommend it more.', 'William Ripper', 'April 2025'],
  ['A real home from home', 'You can tell the owners care. Everything you need is here and the welcome was warm. The log burner made our evenings, and the woodland walks were magical with the children.', 'The Hendersons', 'February 2025'],
  ['Birdsong and total peace', 'We came to switch off and that is exactly what we got. No traffic, no light pollution — just birdsong and the wood. The cottage is spotless and full of character.', 'Sue & David', 'October 2024'],
  ['Wonderful wildlife', 'The feeders right outside the window kept us entertained for hours. Nuthatches, woodpeckers, even a muntjac one morning. A nature-lover’s dream and beautifully kept.', 'Rachel M.', 'August 2024'],
];

function StarPicker({ value, onChange }) {
  const [hover, setHover] = useState(0);
  return (
    <div role="radiogroup" aria-label="Your overall rating" style={{ display: 'inline-flex', gap: 2 }}>
      {[1, 2, 3, 4, 5].map((n) => (
        <button key={n} type="button" onClick={() => onChange(n)} onMouseEnter={() => setHover(n)} onMouseLeave={() => setHover(0)}
          aria-label={n + (n === 1 ? ' star' : ' stars')} aria-pressed={value === n}
          style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '0 2px', fontSize: 32, lineHeight: 1, color: (hover || value) >= n ? '#d8a23a' : '#d8cfc0' }}>
          {(hover || value) >= n ? '★' : '☆'}
        </button>
      ))}
    </div>
  );
}

function ReviewForm() {
  const [form, setForm] = useState({ rating: 0, title: '', body: '', name: '', email: '', consent: false, website: '' });
  const [state, setState] = useState('idle');   // idle | sending | done
  const [errors, setErrors] = useState([]);
  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.type === 'checkbox' ? e.target.checked : e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    setErrors([]);
    if (!form.rating) { setErrors(['Please choose a star rating.']); return; }
    setState('sending');
    try {
      const fd = new FormData();
      fd.append('rating', form.rating);
      fd.append('title', form.title);
      fd.append('body', form.body);
      fd.append('name', form.name);
      fd.append('email', form.email);
      fd.append('consent', form.consent ? '1' : '');
      fd.append('website', form.website);   // honeypot
      const res = await fetch('api/reviews.php', { method: 'POST', body: fd });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) { setState('done'); }
      else { setErrors(data.errors || ['Something went wrong — please try again.']); setState('idle'); }
    } catch (err) {
      setErrors(['Could not send your review. Please try again, or email us.']);
      setState('idle');
    }
  };

  if (state === 'done') {
    return (
      <Card padding="md" style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 30, color: '#d8a23a' }}>★★★★★</div>
        <h3 className="h3" style={{ margin: '10px 0 8px' }}>Thank you{form.name ? ', ' + form.name : ''}!</h3>
        <p className="muted" style={{ margin: 0 }}>Your review has been sent to Nick and will appear on the site once it’s approved.</p>
      </Card>
    );
  }

  const labelStyle = { display: 'block', fontWeight: 600, color: 'var(--text-strong)', fontSize: 14.5, margin: '0 0 6px' };
  return (
    <Card padding="md">
      <form onSubmit={submit} style={{ display: 'grid', gap: 16 }}>
        <div>
          <span style={labelStyle}>Your overall rating</span>
          <StarPicker value={form.rating} onChange={(n) => setForm((f) => ({ ...f, rating: n }))} />
        </div>
        <label><span style={labelStyle}>Title of your review</span>
          <input className="gk-input" value={form.title} onChange={set('title')} placeholder="What’s your headline?" maxLength={120} /></label>
        <label><span style={labelStyle}>Your review</span>
          <textarea className="gk-input" value={form.body} onChange={set('body')} placeholder="Tell us about your stay with us." rows={5} maxLength={2500} required style={{ resize: 'vertical', minHeight: 110 }} /></label>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="gk-stack">
          <label><span style={labelStyle}>Your name</span>
            <input className="gk-input" value={form.name} onChange={set('name')} required /></label>
          <label><span style={labelStyle}>Your email</span>
            <input className="gk-input" type="email" value={form.email} onChange={set('email')} required /></label>
        </div>
        {/* honeypot — hidden from people, catches bots */}
        <input type="text" tabIndex={-1} autoComplete="off" value={form.website} onChange={set('website')}
          style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }} aria-hidden="true" />
        <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 14.5, color: 'var(--text-body)', cursor: 'pointer' }}>
          <input type="checkbox" checked={form.consent} onChange={set('consent')} style={{ marginTop: 3, width: 18, height: 18, flex: '0 0 auto', accentColor: 'var(--color-primary)' }} />
          <span>This review is based on my own experience and is my genuine opinion.</span>
        </label>
        {errors.length > 0 && (
          <div style={{ background: '#fbeae6', color: '#9f3d2e', borderRadius: 'var(--radius-sm)', padding: '10px 14px', fontSize: 14 }}>
            {errors.map((er, i) => <div key={i}>{er}</div>)}
          </div>
        )}
        <div>
          <Button variant="primary" size="lg" type="submit" disabled={state === 'sending'}>
            {state === 'sending' ? 'Sending…' : 'Submit review'}
          </Button>
        </div>
        <p className="muted" style={{ fontSize: 12.5, margin: 0 }}>Reviews are checked by the owner before they appear on the site. Your email is never published.</p>
      </form>
    </Card>
  );
}

function ReviewsContent() {
  const { openBooking } = useShell();
  const live = useReviews();
  const liveCards = (live || []).map((r) => [r.title || 'A lovely stay', r.body, r.name, reviewMonth(r.date), r.rating || 5]);
  const seedCards = REVIEWS.map(([title, body, who, when]) => [title, body, who, when, 5]);
  // Live (Decap-managed) reviews are the source of truth; the in-code examples are
  // only a fallback for when the data file can't be read (e.g. local file:// preview).
  const allCards = liveCards.length ? liveCards : seedCards;
  const stats = reviewStats(live);
  const statCount = stats.count || seedCards.length;
  const statAvg = stats.averageText !== '—' ? stats.averageText : '5.0';
  return (
    <React.Fragment>
      <section className="section--tight" style={{ paddingTop: 56 }}>
        <div className="container">
          <Eyebrow>Guest reviews</Eyebrow>
          <h1 className="h1" style={{ margin: '14px 0 18px' }}>What our guests say</h1>
          <Card padding="md" style={{ display: 'flex', alignItems: 'center', gap: 28, flexWrap: 'wrap' }}>
            <div style={{ textAlign: 'center', paddingRight: 28, borderRight: '1px solid var(--border-soft)' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 52, fontWeight: 600, color: 'var(--text-strong)', lineHeight: 1 }}>{statAvg}</div>
              <Rating value={stats.average || 5} showValue={false} />
              <div className="muted" style={{ fontSize: 14, marginTop: 6 }}>{statCount} {statCount === 1 ? 'review' : 'reviews'}</div>
            </div>
            <div style={{ flex: '1 1 320px', display: 'grid', gap: 8 }}>
              {[['Cleanliness', 5.0], ['Location', 5.0], ['Welcome', 5.0], ['Value', 4.9], ['Accuracy', 5.0]].map(([k, v]) => (
                <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 14.5 }}>
                  <span style={{ width: 100, color: 'var(--text-body)' }}>{k}</span>
                  <span style={{ flex: 1, height: 7, borderRadius: 999, background: 'var(--surface-strong)', overflow: 'hidden' }}><span style={{ display: 'block', height: '100%', width: (v / 5 * 100) + '%', background: 'var(--color-primary)' }}></span></span>
                  <b style={{ width: 32, textAlign: 'right', color: 'var(--text-strong)' }}>{v.toFixed(1)}</b>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </section>

      <section className="section" style={{ paddingTop: 36 }}>
        <div className="container">
          <div style={{ columnCount: 2, columnGap: 24 }} className="rev-masonry">
            {allCards.map(([title, body, who, when, rating], i) => (
              <div key={i + who + title} style={{ breakInside: 'avoid', marginBottom: 24 }}>
                <Card padding="md">
                  <Rating value={rating} showValue={false} />
                  <h3 className="h3" style={{ fontSize: 'var(--fs-h4)', margin: '12px 0 10px' }}>{title}</h3>
                  <p style={{ fontFamily: 'var(--font-display)', fontSize: 17.5, lineHeight: 1.6, color: 'var(--text-strong)', margin: '0 0 16px' }}>“{body}”</p>
                  <div style={{ fontSize: 14, color: 'var(--text-muted)' }}><b style={{ color: 'var(--text-strong)' }}>{who}</b>{when ? ' · ' + when : ''}</div>
                </Card>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section section--soft">
        <div className="container container--narrow">
          <Eyebrow>Stayed with us?</Eyebrow>
          <h2 className="h2" style={{ margin: '14px 0 8px' }}>Leave a review</h2>
          <p className="muted" style={{ margin: '0 0 22px' }}>We love to hear what you thought of your stay. Share a few words — it’ll appear here once the owner has approved it.</p>
          <ReviewForm />
        </div>
      </section>

      <section className="section" style={{ textAlign: 'center' }}>
        <div className="container container--narrow">
          <h2 className="h2" style={{ marginBottom: 12 }}>Come and see for yourself</h2>
          <p className="lead muted" style={{ marginBottom: 26 }}>Join the guests who keep coming back to the wood. Check your dates and we'll hold them for you.</p>
          <Button variant="primary" size="lg" onClick={openBooking}>Check rates &amp; reserve</Button>
        </div>
      </section>
      <style>{`@media(max-width:720px){.rev-masonry{column-count:1 !important}}`}</style>
    </React.Fragment>
  );
}

window.GKmount('reviews', ReviewsContent);
