/* global React, ReactDOM, AnimatedBackground, CursorGlow, firebase */
const { useState, useEffect } = React;

const auth = firebase.auth();
const db = firebase.firestore();
const googleProvider = new firebase.auth.GoogleAuthProvider();

function ReviewsNav() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
      <div className="nav__inner">
        <a href="/" className="nav__brand">
          <span className="nav__logo-plate">
            <img src="/logos/logo dark.webp" alt="Orca Solutions" className="nav__logo" />
          </span>
          <span className="nav__wordmark">Orca</span>
          <span className="nav__sub">/ Solutions</span>
        </a>
        <nav className="nav__links">
          <a href="/">Home</a>
          <a href="/projects">Projects</a>
          <a href="#contact">Contact</a>
        </nav>
        <div className="nav__cta">
          <a href="#contact" className="btn btn--ghost nav__cta-btn">Start a project →</a>
        </div>
      </div>
    </header>
  );
}

function StarIcon({ filled, size = 18, onClick, hoverable }) {
  return (
    <svg
      width={size} height={size} viewBox="0 0 24 24"
      style={{ cursor: onClick ? 'pointer' : 'default' }}
      className={`review-form__star ${filled ? 'review-form__star--active' : ''}`}
      onClick={onClick}
    >
      <path fill="currentColor" d="M12 2l2.9 6.6 7.1.6-5.4 4.7 1.7 7L12 17.3 5.7 21l1.7-7L2 9.2l7.1-.6L12 2z"/>
    </svg>
  );
}

function ReviewsContact() {
  const [sent, setSent] = useState(false);
  const [form, setForm] = useState({ name: '', email: '', company: '', scope: 'Web platform', msg: '' });
  const upd = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const handleSubmit = (e) => {
    e.preventDefault();
    if (typeof firebase !== 'undefined' && firebase.firestore) {
      firebase.firestore().collection('contacts').add({
        name: form.name,
        email: form.email,
        company: form.company,
        scope: form.scope,
        message: form.msg,
        status: 'new',
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      }).catch(() => {});
    }
    setSent(true);
  };
  return (
    <section className="contact" id="contact">
      <div className="contact__inner">
        <div className="contact__left">
          <span className="eyebrow">Contact</span>
          <h2 className="contact__title">Have a project in mind?<br /><span className="contact__title-muted">Let's map it out.</span></h2>
          <p className="contact__lede">Tell us a little about what you're building. We reply within one business day, usually faster.</p>
          <div className="contact__cards">
            <a href="tel:+94711818119" className="contact__card contact__card--phone">
              <div className="contact__card-icon">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
              </div>
              <span className="contact__card-label">Prefer to talk?</span>
              <span className="contact__card-title">Call our Technical Consultant</span>
              <span className="contact__card-name">Charaka Janith</span>
              <span className="contact__card-value">+94 71 181 8119</span>
            </a>
            <a href="https://wa.me/94711818119" target="_blank" rel="noopener noreferrer" className="contact__card contact__card--whatsapp">
              <div className="contact__card-icon">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413z"/></svg>
              </div>
              <span className="contact__card-label">Quick chat?</span>
              <span className="contact__card-title">Message us on WhatsApp</span>
              <span className="contact__card-value">wa.me/94711818119</span>
            </a>
          </div>
          <div className="contact__office">
            <span className="contact__direct-label">Office</span>
            <span className="contact__direct-value">Colombo, Sri Lanka — Mon–Fri 8:00 AM–6:00 PM</span>
          </div>
        </div>
        <form className="contact__form" onSubmit={handleSubmit}>
          {sent ?
          <div className="contact__sent">
              <div className="contact__sent-mark">✓</div>
              <h4>Message received.</h4>
              <p>We'll be in touch shortly, {form.name || 'there'}.</p>
            </div> :
          <>
              <label className="field"><span>Name</span><input value={form.name} onChange={upd('name')} placeholder="Jane Perera" required /></label>
              <label className="field"><span>Email</span><input type="email" value={form.email} onChange={upd('email')} placeholder="jane@company.com" required /></label>
              <label className="field"><span>Company</span><input value={form.company} onChange={upd('company')} placeholder="Acme Ltd." /></label>
              <label className="field">
                <span>Scope</span>
                <select value={form.scope} onChange={upd('scope')}>
                  <option>Web platform</option>
                  <option>Mobile app</option>
                  <option>ERP / internal tools</option>
                  <option>Cloud / DevOps</option>
                  <option>AI / data</option>
                  <option>Other</option>
                </select>
              </label>
              <label className="field field--full"><span>What are you building?</span>
                <textarea value={form.msg} onChange={upd('msg')} rows="4" placeholder="A few sentences is plenty. Links welcome." required></textarea>
              </label>
              <button className="btn btn--primary btn--full" type="submit">Send message<span className="btn__arrow"> →</span></button>
            </>
          }
        </form>
      </div>
    </section>
  );
}

function ReviewsPage() {
  const [user, setUser] = useState(null);
  const [reviews, setReviews] = useState([]);
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [hoverRating, setHoverRating] = useState(0);

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((u) => setUser(u));
    fetchReviews();
    return () => unsubscribe();
  }, []);

  const fetchReviews = async () => {
    try {
      const snapshot = await db.collection('reviews').orderBy('createdAt', 'desc').get();
      const fetched = [];
      snapshot.forEach((doc) => {
        const data = doc.data();
        fetched.push({
          id: doc.id,
          userName: data.userName,
          userPhoto: data.userPhoto,
          rating: data.rating,
          comment: data.comment,
          createdAt: data.createdAt?.toDate() || new Date(),
        });
      });
      setReviews(fetched);
    } catch (err) {
      console.error('Error fetching reviews:', err);
    }
  };

  const handleSignIn = async () => {
    try {
      await auth.signInWithPopup(googleProvider);
    } catch (err) {
      console.error('Sign in error:', err);
    }
  };

  const handleSignOut = () => auth.signOut();

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!user || rating === 0 || !comment.trim()) return;
    setLoading(true);
    try {
      await db.collection('reviews').add({
        userId: user.uid,
        userName: user.displayName || 'Anonymous',
        userPhoto: user.photoURL || '',
        rating,
        comment: comment.trim(),
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
      });
      setRating(0);
      setComment('');
      setSuccess(true);
      fetchReviews();
      setTimeout(() => setSuccess(false), 5000);
    } catch (err) {
      console.error('Submit error:', err);
    } finally {
      setLoading(false);
    }
  };

  const avgRating = reviews.length > 0
    ? (reviews.reduce((sum, r) => sum + r.rating, 0) / reviews.length).toFixed(1)
    : '5.0';

  return (
    <>
      <CursorGlow />
      <AnimatedBackground enabled={true} />
      <ReviewsNav />
      <div className="reviews-page">
        <a href="/" className="reviews-page__back">&larr; Back to home</a>
        <h1 className="reviews-page__title">Client Reviews</h1>
        <p className="reviews-page__lede">
          <strong>{avgRating}</strong> average from <strong>{reviews.length}</strong> verified reviews.
          All clients recommended Orca Solutions with the maximum stars.
        </p>

        {/* Auth & Form */}
        {!user ? (
          <div className="reviews-auth">
            <div className="reviews-auth__info">
              <h4>Leave a review</h4>
              <p>Sign in with Google to share your experience working with us.</p>
            </div>
            <button className="btn btn--google" onClick={handleSignIn}>
              <svg width="16" height="16" viewBox="0 0 48 48"><path fill="#FFC107" d="M43.6 20.5H42V20H24v8h11.3C33.7 32.7 29.3 36 24 36c-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.1 6.5 29.3 4.5 24 4.5 13 4.5 4 13.5 4 24.5s9 20 20 20 20-9 20-20c0-1.4-.1-2.7-.4-4z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.7 15.1 19 12.5 24 12.5c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34.1 6.5 29.3 4.5 24 4.5 16.3 4.5 9.7 8.6 6.3 14.7z"/><path fill="#4CAF50" d="M24 44.5c5.2 0 9.9-2 13.5-5.2l-6.2-5.2c-2 1.5-4.6 2.4-7.3 2.4-5.3 0-9.7-3.3-11.3-7.9l-6.5 5C9.6 40.4 16.2 44.5 24 44.5z"/><path fill="#1976D2" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.2-2.1 4.1-3.9 5.5l6.2 5.2c4.4-4.1 7-10 7-17.7 0-1.4-.1-2.7-.4-4z"/></svg>
              Sign in with Google
            </button>
          </div>
        ) : (
          <>
            <div className="reviews-auth">
              <div className="reviews-auth__user">
                {user.photoURL && <img src={user.photoURL} alt="" className="reviews-auth__photo" referrerPolicy="no-referrer" />}
                <span>Signed in as <strong>{user.displayName}</strong></span>
              </div>
              <button className="btn btn--signout" onClick={handleSignOut}>Sign out</button>
            </div>

            {success ? (
              <div className="review-success">
                <h4>Thank you!</h4>
                <p>Your review has been submitted successfully.</p>
              </div>
            ) : (
              <form className="review-form" onSubmit={handleSubmit}>
                <h3>Write a review</h3>
                <div className="review-form__stars">
                  {[1,2,3,4,5].map(i => (
                    <StarIcon
                      key={i}
                      size={32}
                      filled={i <= (hoverRating || rating)}
                      onClick={() => setRating(i)}
                      onMouseEnter={() => setHoverRating(i)}
                      onMouseLeave={() => setHoverRating(0)}
                    />
                  ))}
                </div>
                <textarea
                  value={comment}
                  onChange={(e) => setComment(e.target.value)}
                  placeholder="Tell us about your experience working with Orca Solutions..."
                  required
                />
                <button className="btn btn--primary" type="submit" disabled={loading || rating === 0}>
                  {loading ? 'Submitting...' : 'Submit Review'}
                </button>
              </form>
            )}
          </>
        )}

        {/* Reviews list */}
        <div className="reviews__grid">
          {reviews.map((r) => (
            <article key={r.id} className="review">
              <div className="review__stars">
                {[1,2,3,4,5].map(i => (
                  <svg key={i} width="14" height="14" viewBox="0 0 24 24" style={{ color: i <= r.rating ? '#ffc94d' : 'var(--ink-4)' }}>
                    <path fill="currentColor" d="M12 2l2.9 6.6 7.1.6-5.4 4.7 1.7 7L12 17.3 5.7 21l1.7-7L2 9.2l7.1-.6L12 2z"/>
                  </svg>
                ))}
              </div>
              <p className="review__quote">&ldquo;{r.comment}&rdquo;</p>
              <div className="review__person">
                {r.userPhoto ? (
                  <img src={r.userPhoto} alt="" style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover' }} referrerPolicy="no-referrer" />
                ) : (
                  <span className="review__avatar">{(r.userName || 'A').charAt(0)}</span>
                )}
                <div>
                  <div className="review__name">{r.userName}</div>
                  <div className="review__role">{r.createdAt.toLocaleDateString()}</div>
                </div>
              </div>
            </article>
          ))}
        </div>
      </div>
      <ReviewsContact />
      <footer className="foot">
        <div className="foot__top">
          <div className="foot__brand-col">
            <div className="foot__brand">
              <span className="foot__logo-plate">
                <img src="/logos/logo dark.webp" alt="Orca Solutions" className="foot__logo" />
              </span>
              <span className="foot__word">Orca Solutions Limited</span>
            </div>
            <div className="foot__socials">
              <a href="https://www.linkedin.com/company/109359186/" target="_blank" rel="noopener noreferrer" className="foot__social" aria-label="LinkedIn">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
              </a>
              <a href="https://x.com/OrcaSolutionsLK" target="_blank" rel="noopener noreferrer" className="foot__social" aria-label="X / Twitter">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
              </a>
              <a href="https://github.com/AspireVX15" target="_blank" rel="noopener noreferrer" className="foot__social" aria-label="GitHub">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>
              </a>
              <a href="https://wa.me/94711818119" target="_blank" rel="noopener noreferrer" className="foot__social" aria-label="WhatsApp">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
              </a>
              <a href="mailto:orca.softwares.limited@gmail.com" className="foot__social" aria-label="Email">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
              </a>
            </div>
          </div>
          <div className="foot__cols">
            <div><h5>Services</h5><a href="/#services">Engineering</a><a href="/#services">Cloud</a><a href="/#services">Security</a><a href="/#services">Data</a></div>
            <div><h5>Company</h5><a href="/#about">About</a><a href="/#work">Work</a><a href="/projects">Projects</a><a href="/#contact">Contact</a></div>
            <div><h5>Connect</h5><a href="https://www.linkedin.com/company/109359186/" target="_blank" rel="noopener noreferrer">LinkedIn</a><a href="https://x.com/OrcaSolutionsLK" target="_blank" rel="noopener noreferrer">X / Twitter</a><a href="https://wa.me/94711818119" target="_blank" rel="noopener noreferrer">WhatsApp</a><a href="mailto:orca.softwares.limited@gmail.com">Email</a></div>
          </div>
        </div>
        <div className="foot__bot">
          <span>© 2026 Orca Solutions Limited</span>
          <span>Colombo · Sri Lanka</span>
          <span className="foot__pulse"><span className="foot__dot"></span>All systems operational</span>
        </div>
      </footer>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ReviewsPage />);
