// TitanReviews.jsx - Google reviews with social proof header and infinite carousel

const REVIEWS = [
  { name: 'Luke White',       text: "Matthew has taken over, cleaned up and made sense of our books. He is focused, immaculate in his work, and attentive not only to your financials, but your core ethos and operations.", url: 'https://maps.app.goo.gl/ovpzEAxvuXv3FMFaA' },
  { name: 'Kacy Wren',        text: "Titan Ledgers is an excellent resource for understanding your company's financial health. Matthew is incredibly knowledgeable, fast and reliable. He follows through on everything with meticulous attention to detail.", url: 'https://maps.app.goo.gl/QcbRN98LgHhinL8a8' },
  { name: 'Nick Walker',      text: "Working with Matt has been absolutely incredible. From what felt like a messy and unorganized situation to all of the ducks in a row in less than two weeks. He has been timely and professional.", url: 'https://maps.app.goo.gl/7M3xJ3Vhm3RDCBvz5' },
  { name: 'Karie Lee',        text: "Our business has been through a couple bookkeepers and Titan is hands down the best! If you don't have time to look after every little transaction then this is your solution! Your CPA will appreciate the organization of it all!", url: 'https://maps.app.goo.gl/U4mT6noRJc76p8yH7' },
  { name: 'Foothill Billing', text: "Matt saved the day! Our books have been such a hassle for years (3 separate companies). Matt came in so organized. My CPA was so impressed he's now starting to send him clients!", url: 'https://maps.app.goo.gl/LrzcwobhDrbw2QvN7' },
  { name: 'Well Women PT',    text: "If I could go back in time and give myself one piece of advice when starting my business, it would have been to hire a good bookkeeper from the very start! Matthew has saved me months of headache. Now my books are clean and tidy!", url: 'https://maps.app.goo.gl/s6AzveLVijha833v9' },
  { name: 'Vanessa Sierra',   text: "Matt has been such a great asset to our company. When we first started with him, we were over a year in business and our books were a mess. He came up with a great plan to get everything cleaned up and organized and our numbers have been accounted for in the best way since he has started managing our accounts. Matt is very trustworthy and is always available for questions or concerns. Highly recommend him to any business, small or large, that is looking to work with a credible accountant!", url: 'https://maps.app.goo.gl/FSn34uEdzYPbyxsh6' },
  { name: 'Jimmy Delao',      text: "Working with Titan Ledgers has been a game changer for Texas United Futbol Club. Our books are consistently accurate and reconciled on time. Matt is incredibly responsive and always provides clear, helpful explanations.", url: 'https://maps.app.goo.gl/FKLWRzgGtDcAbxi36' },
  { name: 'King Soocer',      text: "We are new business owners and reached out to Matthew to help us organize our finances. He is very thorough and diligent. We meet monthly to go over the ins and outs of our finances. We HIGHLY recommend Matthew to all business owners!", url: 'https://maps.app.goo.gl/Fc7VmKcVNVWMrHgt9' },
  { name: 'Chas Hoppe',       text: "Titan Ledgers does a fantastic job of improving my visibility into my small business finances, showing me a variety of ways to look at my business, my cash flow, and my overall financial health. Highly recommended!", url: 'https://maps.app.goo.gl/qDo5Yzr9tSGmNcuKA' },
  { name: 'DocuSwift Pro',    text: "Titan Ledgers has been an absolute game-changer. Matt's attention to detail and depth of knowledge are unmatched. He tailored his approach perfectly. I can't recommend Titan Ledgers enough!", url: 'https://maps.app.goo.gl/XFjewmBxL7xztM5m6' },
  { name: 'Mark Gudaitis',    text: "Working with Matthew has been a god send for our small company. He is incredibly thorough, patient, and set us up for success. His reports show extreme clarity to the standing of the business.", url: 'https://maps.app.goo.gl/eiCVgw51DBiiypZ28' },
  { name: 'Christine Nieh',   text: "I hired Matt a couple of years ago and it's been an absolute pleasure. He took the time to understand my needs and the operational intricacies of my business. Hiring Matt was truly the best decision I made.", url: 'https://maps.app.goo.gl/8uDZXvK3PvfRMXr47' },
  { name: 'Alex Deng',        text: "Matt at Titan Ledgers is the bookkeeper you need! He is very punctual and takes his time explaining key components. If you want to focus on what you're good at and have someone handle the numbers, contact Matt!", url: 'https://maps.app.goo.gl/7XMhqCrKFCyAwfTk7' },
  { name: 'Angelica Baez',    text: "Before engaging Matt's services, I consulted with several bookkeepers, and Matt clearly distinguished himself as the top choice. His rates are reasonable and his expertise has been indispensable.", url: 'https://maps.app.goo.gl/gQ74H3sB8JL8i9sJ9' },
];

// Avatar palette: brand navy + gold tints, plus neutrals
const AVATAR_COLORS = ['#0F1A2E','#967844','#16263D','#7E6638','#273951','#BD9748','#0F1A2E','#967844'];

const GOOGLE_PROFILE_URL = 'https://maps.app.goo.gl/4HhpcWp62Jr28zfF8';

const useGoogleReviewData = () => {
  const [data, setData] = React.useState({ rating: '5.0', count: null });
  React.useEffect(() => {
    fetch('/api/reviews')
      .then(r => r.json())
      .then(d => { if (d.count) setData({ rating: d.rating, count: d.count }); })
      .catch(() => {});
  }, []);
  return data;
};

const useReviewVisibleCount = () => {
  const getCount = () => {
    if (window.innerWidth <= 640) return 1;
    if (window.innerWidth <= 900) return 2;
    return 4;
  };
  const [visible, setVisible] = React.useState(getCount);
  React.useEffect(() => {
    const onResize = () => setVisible(getCount());
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return visible;
};

const StarRow = ({ size = 12 }) => (
  <div style={{ display: 'flex', gap: 2 }}>
    {[...Array(5)].map((_, i) => (
      <svg key={i} width={size} height={size} viewBox="0 0 24 24" fill="#BD9748" stroke="none">
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
      </svg>
    ))}
  </div>
);

const GoogleG = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 48 48">
    <path fill="#4285F4" d="M43.6 20.5H42V20H24v8h11.3c-1.6 4.7-6.1 8-11.3 8-6.6 0-12-5.4-12-12s5.4-12 12-12c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34 5.3 29.3 3.5 24 3.5 12.7 3.5 3.5 12.7 3.5 24S12.7 44.5 24 44.5c11.6 0 20-8.4 20-20 0-1.4-.2-2.7-.4-4z"/>
    <path fill="#34A853" d="M6.3 14.7l6.6 4.8C14.6 16 19 13 24 13c3.1 0 5.9 1.2 8 3.1l5.7-5.7C34 7 29.3 5 24 5 16.3 5 9.7 9.3 6.3 14.7z"/>
    <path fill="#FBBC05" d="M24 44.5c5.2 0 9.9-2 13.5-5.2l-6.2-5.2c-2 1.4-4.5 2.2-7.3 2.2-5.2 0-9.6-3.3-11.2-8l-6.5 5C9.7 39.1 16.3 44.5 24 44.5z"/>
    <path fill="#EA4335" d="M43.6 20.5H42V20H24v8h11.3c-.8 2.3-2.3 4.3-4.1 5.6l6.2 5.2c-.4.4 6.6-4.8 6.6-14.8 0-1.4-.2-2.7-.4-4z"/>
  </svg>
);

const GoogleReviewPill = () => {
  const { rating, count } = useGoogleReviewData();
  const countLabel = count ? `${count} Google reviews` : '30 Google reviews';
  return (
    <a
      href={GOOGLE_PROFILE_URL}
      target="_blank"
      rel="noopener noreferrer"
      style={{ textDecoration: 'none', display: 'inline-flex', flexShrink: 0 }}
    >
      <div
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 10,
          background: '#fff', border: '1px solid #e5edf5',
          borderRadius: 10, padding: '9px 14px',
          boxShadow: 'rgba(15,26,46,0.06) 0px 2px 8px 0px',
          cursor: 'pointer', transition: 'box-shadow 150ms, border-color 150ms',
        }}
        onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 16px rgba(15,26,46,0.12)'; e.currentTarget.style.borderColor = '#E2C887'; }}
        onMouseLeave={e => { e.currentTarget.style.boxShadow = 'rgba(15,26,46,0.06) 0px 2px 8px 0px'; e.currentTarget.style.borderColor = '#e5edf5'; }}
      >
        <GoogleG size={22} />
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 2 }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: '#0F1A2E' }}>{rating}</span>
            <StarRow size={11} />
          </div>
          <div style={{ fontSize: 11, fontWeight: 300, color: '#94a3b8' }}>{countLabel}</div>
        </div>
      </div>
    </a>
  );
};

const ArrowBtn = ({ onClick, dir }) => {
  const [hov, setHov] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      aria-label={dir === 'left' ? 'Previous reviews' : 'Next reviews'}
      style={{
        width: 38, height: 38, borderRadius: '50%', flexShrink: 0,
        border: '1px solid ' + (hov ? '#BD9748' : '#E2C887'),
        background: hov ? '#0F1A2E' : '#fff',
        color: hov ? '#BD9748' : '#967844',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        cursor: 'pointer', transition: 'all 150ms',
      }}
    >
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        {dir === 'left' ? <polyline points="15 18 9 12 15 6"/> : <polyline points="9 18 15 12 9 6"/>}
      </svg>
    </button>
  );
};

const MiniCard = ({ review, colorIdx }) => {
  const initials = review.name.split(' ').map(n => n[0]).slice(0, 2).join('').toUpperCase();
  const color = AVATAR_COLORS[colorIdx % AVATAR_COLORS.length];
  const short = review.text.length > 170 ? review.text.slice(0, 167) + '...' : review.text;
  const [hov, setHov] = React.useState(false);
  return (
    <a
      href={review.url || GOOGLE_PROFILE_URL}
      target="_blank"
      rel="noopener noreferrer"
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        textDecoration: 'none',
        background: '#fff', border: '1px solid ' + (hov ? '#E2C887' : '#e5edf5'), borderRadius: 10,
        padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 12,
        minHeight: 178, boxShadow: hov ? 'rgba(15,26,46,0.12) 0px 4px 16px 0px' : 'rgba(15,26,46,0.06) 0px 2px 6px 0px',
        cursor: 'pointer', transition: 'box-shadow 150ms, border-color 150ms',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 500, color: '#fff' }}>{initials}</div>
          <div style={{ position: 'absolute', bottom: -2, right: -2, background: '#fff', borderRadius: '50%', padding: 1, boxShadow: '0 1px 2px rgba(0,0,0,0.1)' }}><GoogleG size={11} /></div>
        </div>
        <div>
          <div style={{ fontSize: 13, fontWeight: 400, color: '#0F1A2E', lineHeight: 1.2 }}>{review.name}</div>
          <StarRow size={10} />
        </div>
      </div>
      <p style={{ fontSize: 12.5, fontWeight: 300, color: '#273951', lineHeight: 1.6, margin: 0, flex: 1 }}>"{short}"</p>
    </a>
  );
};

const TitanReviews = () => {
  const visible = useReviewVisibleCount();
  const [idx, setIdx] = React.useState(0);
  const total = REVIEWS.length;
  const max = Math.max(0, total - visible);

  React.useEffect(() => {
    setIdx(i => Math.min(i, max));
  }, [max]);

  const prev = () => setIdx(i => (i <= 0 ? max : i - 1));
  const next = () => setIdx(i => (i >= max ? 0 : i + 1));

  return (
    <section id="reviews" style={{ background: '#f8fafc', borderTop: '1px solid #e5edf5', padding: '24px 0 16px', fontFamily: "'DM Sans', sans-serif" }}>
      <div style={{ maxWidth: 1080, margin: '0 auto', padding: '0 24px' }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <h2 style={{ fontSize: 'clamp(20px,2.4vw,26px)', fontWeight: 400, color: '#0F1A2E', letterSpacing: '-0.4px', lineHeight: 1.2, margin: 0, textWrap: 'pretty' }}>
            What our clients say about Titan Ledgers
          </h2>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <ArrowBtn onClick={prev} dir="left" />
          <div style={{ flex: 1, display: 'grid', gridTemplateColumns: `repeat(${visible}, minmax(0, 1fr))`, gap: 14, overflow: 'hidden', minWidth: 0 }}>
            {REVIEWS.slice(idx, idx + visible).map((r, i) => (
              <MiniCard key={idx + i} review={r} colorIdx={idx + i} />
            ))}
          </div>
          <ArrowBtn onClick={next} dir="right" />
        </div>

        {max > 0 && (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6, paddingTop: 24 }}>
            {Array.from({ length: max + 1 }, (_, i) => (
              <button
                key={i}
                onClick={() => setIdx(i)}
                aria-label={`Reviews page ${i + 1}`}
                style={{
                  width: i === idx ? 24 : 8,
                  height: 8,
                  borderRadius: 4,
                  background: i === idx ? '#BD9748' : '#d1dde6',
                  border: 'none',
                  cursor: 'pointer',
                  padding: 0,
                  transition: 'width 200ms ease, background 200ms ease',
                  flexShrink: 0,
                }}
              />
            ))}
          </div>
        )}
      </div>

      <style>{`
        @media (max-width: 600px) {
          .reviews-header-row { flex-direction: column !important; align-items: flex-start !important; }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { TitanReviews, StarRow, GoogleG, ArrowBtn, MiniCard, GoogleReviewPill });
