/* Shared UI components for PaddleReviewHub */

const { useState, useEffect, useRef } = React;

// ====== ROUTER ======
function useHashRoute() {
  const [route, setRoute] = useState(window.location.hash.slice(1) || "/");
  useEffect(() => {
    const onChange = () => {
      setRoute(window.location.hash.slice(1) || "/");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onChange);
    return () => window.removeEventListener("hashchange", onChange);
  }, []);
  return route;
}

function navigate(path) {
  window.location.hash = path;
}

function Link({ to, className, children, ...rest }) {
  const active = (window.location.hash.slice(1) || "/") === to;
  return (
    <a
      href={"#" + to}
      className={(className || "") + (active ? " active" : "")}
      {...rest}
    >
      {children}
    </a>
  );
}

// ====== SCORE BADGE ======
function ScoreBadge({ score, size = "md" }) {
  const tier = score >= 9.0 ? "" : score >= 8.0 ? "tier-green" : "tier-yellow";
  const cls = `score-badge ${size === "lg" ? "score-badge-lg" : size === "sm" ? "score-badge-sm" : ""} ${tier}`;
  return (
    <div className={cls}>
      <div className="score-num">{score.toFixed(1)}</div>
      <div className="score-of">OUT OF 10</div>
    </div>
  );
}

// ====== PADDLE CARD ======
function PaddleCard({ paddle, rank }) {
  return (
    <a href={`#/reviews/${paddle.slug}`} className="paddle-card">
      <div className="paddle-card-imgbox">
        {rank && (
          <div className={`rank-pill ${rank === 1 ? "gold" : rank === 2 ? "silver" : "bronze"}`}>
            #{rank}
          </div>
        )}
        <img src={paddle.image} alt={`${paddle.name} pickleball paddle`} />
        <ScoreBadge score={paddle.score} size="sm" />
      </div>
      <div className="paddle-card-brand">{paddle.brand}</div>
      <div className="paddle-card-name">{paddle.name}</div>
      <div className="paddle-card-tag">{paddle.tagline}</div>
      <div className="paddle-card-foot">
        <div className="paddle-card-price">
          {paddle.stockPrice !== paddle.salePrice && <s>${paddle.stockPrice}</s>}
          ${paddle.salePrice}
        </div>
        <div className="paddle-card-link">Read Review →</div>
      </div>
    </a>
  );
}

// ====== HEADER ======
function Header() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const route = useHashRoute();
  useEffect(() => { setMobileOpen(false); }, [route]);

  return (
    <header className="prh-header">
      <div className="prh-header-inner">
        <a href="#/" className="prh-logo">
          <img src="assets/logo.png" alt="PaddleReviewHub" />
          <div className="prh-logo-text">
            <b>PaddleReviewHub</b>
            <span>Tested. Ranked. Real.</span>
          </div>
        </a>

        <nav className="prh-nav">
          <Link to="/reviews">Reviews</Link>
          <Link to="/articles">Articles</Link>
          <Link to="/community">Community</Link>
          <Link to="/deals">Deals</Link>
          <Link to="/about">About</Link>
        </nav>

        <a href="#/deals" className="prh-header-cta">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M20.59 13.41 13.42 20.58a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"/>
            <line x1="7" y1="7" x2="7.01" y2="7"/>
          </svg>
          Promo Codes
        </a>

        <button className="prh-hamburger" onClick={() => setMobileOpen(v => !v)} aria-label="Menu">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
            {mobileOpen ? <><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></>
              : <><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/></>}
          </svg>
        </button>
      </div>

      {mobileOpen && (
        <div className="prh-mobile-menu">
          <a href="#/reviews" onClick={() => setMobileOpen(false)}>Reviews</a>
          <a href="#/articles" onClick={() => setMobileOpen(false)}>Articles</a>
          <a href="#/community" onClick={() => setMobileOpen(false)}>Community</a>
          <a href="#/deals" onClick={() => setMobileOpen(false)}>Deals</a>
          <a href="#/about" onClick={() => setMobileOpen(false)}>About</a>
        </div>
      )}
    </header>
  );
}

// ====== FOOTER ======
function Footer() {
  return (
    <footer className="prh-footer">
      <div className="container">
        <div className="prh-footer-top">
          <div>
            <div className="prh-footer-brand">
              <img src="assets/logo.png" alt="PaddleReviewHub" />
              <div className="prh-footer-brand-text">
                <b>PaddleReviewHub</b>
                <span>Tested. Ranked. Real.</span>
              </div>
            </div>
            <p className="prh-footer-about">
              Independent pickleball paddle reviews from real players.
              We test every paddle on-court before we write a word.
            </p>
            <div className="prh-social">
              <a href="https://www.instagram.com/paddlereviewhub/" target="_blank" rel="noopener noreferrer" aria-label="Instagram"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="2" width="20" height="20" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r=".5" fill="currentColor"/></svg></a>
              <a href="https://www.youtube.com/@PaddleReviewHub" target="_blank" rel="noopener noreferrer" aria-label="YouTube"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z"/><polygon points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02" fill="currentColor"/></svg></a>
              <a href="https://www.tiktok.com/@paddle.review.hub" target="_blank" rel="noopener noreferrer" aria-label="TikTok"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 12a4 4 0 1 0 4 4V4a5 5 0 0 0 5 5"/></svg></a>
              <a href="https://www.facebook.com/people/Paddle-Review-Hub/61572100277064/" target="_blank" rel="noopener noreferrer" aria-label="Facebook"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/></svg></a>
            </div>
          </div>
          <div>
            <h5>Reviews</h5>
            <a href="#/reviews/honolulu-j2cr">Honolulu J2CR</a>
            <a href="#/reviews/vatic-v-sol-pro-flash">Vatic V-SOL Pro</a>
            <a href="#/reviews/joola-perseus-pro-v">JOOLA Pro V</a>
            <a href="#/reviews/selkirk-boomstik">Selkirk Boomstik</a>
            <a href="#/reviews">All Reviews →</a>
          </div>
          <div>
            <h5>Guides</h5>
            <a href="#/articles/best-pickleball-paddles-2026">Best of 2026</a>
            <a href="#/articles/best-pickleball-paddle-under-100">Under $100</a>
            <a href="#/articles/best-foam-core-paddles-2026">Best Foam Core</a>
            <a href="#/articles/joola-pro-iv-vs-pro-v">Pro IV vs Pro V</a>
          </div>
          <div>
            <h5>Site</h5>
            <a href="#/community">Community</a>
            <a href="#/deals">Promo Codes</a>
            <a href="#/about">About Us</a>
            <a href="#/about">Contact</a>
          </div>
        </div>

        <div className="prh-footer-disclosure">
          <b style={{color: "white"}}>Affiliate disclosure:</b> We may earn a commission through links on this site at no extra cost to you.
          We only recommend gear we've personally tested on-court. Questions? <a href="mailto:info@paddlereviewhub.com" style={{color:"var(--teal)"}}>info@paddlereviewhub.com</a>.
        </div>

        <div className="prh-footer-bottom">
          <div>© 2026 PaddleReviewHub. All rights reserved.</div>
          <div style={{display:"flex", gap: 18}}>
            <a href="#/about">Privacy</a>
            <a href="#/about">Terms</a>
            <a href="#/about">Disclosure</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ====== QUICK ANSWER ======
function QuickAnswer({ children }) {
  return (
    <div className="quick-answer">
      <div className="quick-answer-label">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
        QUICK ANSWER
      </div>
      <p>{children}</p>
    </div>
  );
}

// ====== PROMO BOX ======
function PromoBox({ code, discount }) {
  const [copied, setCopied] = useState(false);
  const onCopy = () => {
    navigator.clipboard?.writeText(code);
    setCopied(true);
    showToast(`Code ${code} copied`);
    setTimeout(() => setCopied(false), 1800);
  };
  if (!code) return null;
  return (
    <div className="promo-box">
      <div>
        <div className="promo-label">Promo Code</div>
        <div className="promo-code">{code}</div>
        <div className="promo-discount">{discount}</div>
      </div>
      <button onClick={onCopy}>{copied ? "✓ Copied" : "Copy code"}</button>
    </div>
  );
}

// ====== CTA ======
function AffiliateCTA({ paddle, size = "lg", block = true }) {
  const priceText = paddle.code
    ? `Get it for $${paddle.salePrice} with code ${paddle.code}`
    : `Shop at ${paddle.brand} — $${paddle.salePrice}`;
  const onClick = (e) => {
    e.preventDefault();
    showToast("Demo — affiliate link placeholder");
  };
  return (
    <div>
      <a
        href="#"
        onClick={onClick}
        className={`btn btn-primary ${size === "lg" ? "btn-lg" : ""} ${block ? "btn-block" : ""}`}
      >
        {priceText}
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
      </a>
      <div className="disclosure-small">Affiliate link — we may earn a commission.</div>
    </div>
  );
}

// ====== PERF TABLE ======
function PerfTable({ scores }) {
  const order = [
    ["Power", scores.power],
    ["Control", scores.control],
    ["Spin", scores.spin],
    ["Feel", scores.feel],
    ["Sweet Spot", scores.sweetspot],
    ["Forgiveness", scores.forgiveness],
  ];
  return (
    <div>
      {order.map(([label, v]) => (
        <div key={label} className="perf-row">
          <div className="perf-name">{label}</div>
          <div className="perf-bar"><div className="perf-fill" style={{ width: `${v * 10}%` }} /></div>
          <div className="perf-num">{v.toFixed(1)}</div>
        </div>
      ))}
    </div>
  );
}

// ====== TOAST ======
function showToast(msg) {
  let el = document.getElementById("__toast");
  if (!el) {
    el = document.createElement("div");
    el.id = "__toast";
    el.className = "toast";
    document.body.appendChild(el);
  }
  el.textContent = msg;
  el.classList.add("show");
  clearTimeout(el._t);
  el._t = setTimeout(() => el.classList.remove("show"), 2000);
}

// ====== NEWSLETTER ======
const EMAIL_CAPTURE_URL = "https://docs.google.com/forms/d/e/1FAIpQLSc6O00N1ZZAGBeaMBJ85A7i0jL24pBkTt7xgjY2dCylQESTyw/viewform?usp=publish-editor";

function Newsletter() {
  return (
    <div className="newsletter">
      <div>
        <h2>New reviews in your inbox.</h2>
        <p>One email per month. New paddle reviews, active promo codes, and community giveaway updates.
          No spam, no sponsored nonsense. More reviews coming soon.</p>
      </div>
      <div>
        <a
          href={EMAIL_CAPTURE_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="btn btn-primary btn-lg btn-block"
          style={{justifyContent:"center"}}
        >
          Subscribe to the newsletter
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
        </a>
        <small style={{marginTop:14}}>Opens our signup form in a new tab. Unsubscribe any time.</small>
      </div>
    </div>
  );
}

// ====== EXPORT ======
Object.assign(window, {
  useHashRoute, navigate, Link,
  ScoreBadge, PaddleCard, Header, Footer,
  QuickAnswer, PromoBox, AffiliateCTA, PerfTable,
  Newsletter, showToast,
});
