// Shared / reusable components

const { useEffect, useState, useRef } = React;

// Simple hash router helpers
function navigate(path) {
  window.location.hash = path;
}

function useRoute() {
  const [route, setRoute] = useState(() => window.location.hash.replace(/^#/, "") || "/");
  useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.replace(/^#/, "") || "/");
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return route;
}

// IntersectionObserver reveal — with immediate-fire fallback for above-the-fold content
function Reveal({ children, delay = 0, className = "", as: Tag = "div", ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let observer;
    let timeoutId;
    // Immediately reveal if already in viewport
    const rect = el.getBoundingClientRect();
    const vh = window.innerHeight || 800;
    if (rect.top < vh) {
      timeoutId = setTimeout(() => setShown(true), delay);
    } else {
      observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) {
              timeoutId = setTimeout(() => setShown(true), delay);
              observer.unobserve(el);
            }
          });
        },
        { threshold: 0.12, rootMargin: "0px 0px -10% 0px" }
      );
      observer.observe(el);
    }
    // Safety net — always show after 1500ms regardless
    const safety = setTimeout(() => setShown(true), 1500);
    return () => {
      if (observer) observer.disconnect();
      if (timeoutId) clearTimeout(timeoutId);
      clearTimeout(safety);
    };
  }, [delay]);
  return (
    <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`} {...rest}>
      {children}
    </Tag>
  );
}

// Editorial label
function EditorialLabel({ children, className = "" }) {
  return <span className={`editorial-label ${className}`}>{children}</span>;
}

// Section title block
function SectionTitle({ eyebrow, number, title, description, align = "left", invert = false }) {
  return (
    <div style={{ 
      maxWidth: align === "center" ? 760 : 880, 
      margin: align === "center" ? "0 auto" : "0", 
      textAlign: align,
      width: "100%"
    }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 18, marginBottom: 20, justifyContent: align === "center" ? "center" : "flex-start" }}>
        {number && <span className="mono" style={{ fontSize: 12, letterSpacing: "0.22em", color: invert ? "var(--teal-deep)" : "var(--teal)" }}>{number}</span>}
        {eyebrow && <EditorialLabel>{eyebrow}</EditorialLabel>}
      </div>
      <h2 className="h1" style={{ margin: 0, color: invert ? "var(--ink)" : "var(--fg)" }}>{title}</h2>
      {description && (
        <p style={{ marginTop: 22, fontSize: 17, lineHeight: 1.6, color: invert ? "var(--fg-muted)" : "var(--fg-muted)", maxWidth: 680, marginLeft: align === "center" ? "auto" : 0, marginRight: align === "center" ? "auto" : 0 }}>
          {description}
        </p>
      )}
    </div>
  );
}

// Button (link / button)
function Button({ children, variant = "primary", to, href, type = "button", onClick, target }) {
  const cls = `btn btn-${variant}`;
  const content = (
    <>
      <span>{children}</span>
      <span className="arrow" aria-hidden="true">→</span>
    </>
  );
  if (to) {
    return (
      <a className={cls} href={`#${to}`} onClick={(e) => { onClick && onClick(e); }}>
        {content}
      </a>
    );
  }
  if (href) {
    return (
      <a className={cls} href={href} target={target} rel={target === "_blank" ? "noreferrer noopener" : undefined}>
        {content}
      </a>
    );
  }
  return (
    <button className={cls} type={type} onClick={onClick}>
      {content}
    </button>
  );
}

// Coach portrait placeholder
function CoachPortrait({ name, number, head, imageUrl }) {
  // Initials
  const initials = (name || "").replace("Coach ", "").split(" ").map((s) => s[0]).slice(0, 2).join("");
  return (
    <div className="coach-portrait" style={{ aspectRatio: head ? "4 / 5" : "3 / 4", color: "var(--fg)" }}>
      <span className="badge" style={{ display: "flex", alignItems: "center", gap: 6, zIndex: 10 }}>
        <img src="src/assets/logomerah.png" alt="" style={{ width: 14, height: 14, objectFit: "contain" }} />
        COACH · {number || "00"}
      </span>
      
      {imageUrl ? (
        <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "flex-end", justifyContent: "center" }}>
          <img 
            src={imageUrl} 
            alt={name} 
            style={{ 
              width: "100%", 
              height: "100%", 
              objectFit: "cover", 
              objectPosition: "top center",
              filter: "contrast(1.05) brightness(0.95)"
            }} 
          />
          {/* Subtle gradient overlay to blend with card bottom */}
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(26,26,26,0.2) 0%, transparent 40%)" }}></div>
        </div>
      ) : (
        <>
          <div className="silhouette">
            <svg viewBox="0 0 200 240" fill="none" xmlns="http://www.w3.org/2000/svg">
              <circle cx="100" cy="78" r="44" stroke="currentColor" strokeOpacity="0.4" strokeWidth="1.4" fill="none" />
              <path d="M28 240 C28 170 60 134 100 134 C140 134 172 170 172 240" stroke="currentColor" strokeOpacity="0.4" strokeWidth="1.4" fill="none" />
            </svg>
          </div>
          <div style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none" }}>
            <img src="src/assets/logomerah.png" alt="" style={{ width: head ? 110 : 80, opacity: 0.08, filter: "grayscale(1)" }} />
          </div>
        </>
      )}

      <span className="number" style={{ zIndex: 5 }}>{number || "00"}</span>
      {head && (
        <span style={{ position: "absolute", top: 14, right: 14, fontSize: 9, letterSpacing: "0.16em", color: "var(--teal-deep)", textTransform: "uppercase", fontWeight: 700, lineHeight: 1.2, textAlign: "right", maxWidth: 180, zIndex: 10 }}>
          KETUA PROGRAM<br />GH GAMBIT SCHOOL DEVELOPMENT
        </span>
      )}
    </div>
  );
}

// Coach card
function CoachCard({ coach, large = false }) {
  return (
    <a
      href={`#/coaches/${coach.slug}`}
      className="card"
      style={{
        padding: 0,
        display: "flex",
        flexDirection: large ? "row" : "column",
        gap: 0,
        background: "var(--bg-card)",
        textDecoration: "none",
        gridColumn: large ? "span 2" : "auto",
        color: "var(--fg)",
      }}
    >
      <div style={{ flex: large ? "0 0 46%" : "auto" }}>
        <CoachPortrait name={coach.name} number={coach.number} head={large} imageUrl={coach.imageUrl} />
      </div>
      <div style={{ padding: large ? "40px 40px 36px" : "24px 26px 28px", flex: 1, display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: "0.22em", color: "var(--teal-deep)", fontWeight: 700 }}>
            {large ? "KETUA PROGRAM" : "STAFF / " + coach.number}
          </span>
          <span className="mono" style={{ fontSize: 10, letterSpacing: "0.22em", color: "var(--fg-muted)" }}>VIEW →</span>
        </div>
        <div>
          <h3 className={large ? "h1" : "h2"} style={{ margin: "0 0 8px 0" }}>{coach.name}</h3>
          <p style={{ margin: 0, fontSize: large ? 15 : 13, letterSpacing: "0.04em", color: "var(--fg-muted)", textTransform: "uppercase", fontWeight: 600 }}>
            {coach.role}
          </p>
        </div>
        {large && (
          <p style={{ margin: 0, color: "var(--fg-muted)", fontSize: 15, lineHeight: 1.65 }}>{coach.shortBio}</p>
        )}
        <div style={{ marginTop: large ? 8 : 4, display: "flex", flexWrap: "wrap", gap: 8 }}>
          {coach.specialization.map((s, i) => (
            <span key={i} style={{ fontSize: 11, letterSpacing: "0.08em", padding: "5px 10px", border: "1px solid var(--line)", color: "var(--fg-muted)", borderRadius: 999, fontWeight: 500 }}>
              {s}
            </span>
          ))}
        </div>
      </div>
    </a>
  );
}

// Program / pillar card
function ProgramCard({ num, title, description, accent = false }) {
  return (
    <div className="card" style={{ display: "flex", flexDirection: "column", gap: 18, minHeight: 280 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <span className="mono" style={{ fontSize: 11, letterSpacing: "0.22em", color: "var(--teal-deep)", fontWeight: 600 }}>{num}</span>
        <span style={{ width: 28, height: 2, background: "var(--teal-deep)", marginTop: 10, borderRadius: 2 }}></span>
      </div>
      <h3 className="h2" style={{ margin: 0 }}>{title}</h3>
      <p style={{ margin: 0, color: "var(--fg-muted)", fontSize: 15, lineHeight: 1.65 }}>{description}</p>
    </div>
  );
}

// Benefit card (compact)
function BenefitCard({ num, label }) {
  return (
    <div className="card" style={{ padding: 24, display: "flex", flexDirection: "column", gap: 22, minHeight: 160 }}>
      <span className="mono" style={{ fontSize: 11, letterSpacing: "0.22em", color: "var(--teal-deep)", fontWeight: 600 }}>{num}</span>
      <p style={{ margin: 0, fontSize: 16, lineHeight: 1.5, fontWeight: 500, color: "var(--fg)" }}>{label}</p>
    </div>
  );
}

// Stat card
function StatCard({ k, l }) {
  return (
    <div className="stat-cell">
      <span className="tick"></span>
      <span className="k">{k}</span>
      <span className="l">{l}</span>
    </div>
  );
}

// Page header (shared across inner pages)
function PageHeader({ number, eyebrow, title, subtitle }) {
  return (
    <header style={{ 
      position: "relative", 
      padding: "clamp(120px, 15vw, 180px) 0 clamp(60px, 8vw, 80px)", 
      overflow: "hidden", 
      background: "var(--bg)",
      width: "100%"
    }}>
      <div className="court-lines" aria-hidden="true"></div>
      <img 
        src="src/assets/logoputih.png" 
        alt="" 
        style={{ 
          position: "absolute", 
          left: "-10%", 
          top: "-10%", 
          width: "600px", 
          opacity: 0.15, 
          pointerEvents: "none", 
          zIndex: 0 
        }} 
      />
      <div className="watermark" style={{ fontSize: "clamp(180px, 32vw, 460px)", right: "-40px", top: "60px", color: "var(--burgundy)", zIndex: 1 }}>{number}</div>
      <div className="container" style={{ position: "relative" }}>
        <Reveal>
          <div style={{ display: "flex", gap: 16, alignItems: "baseline", marginBottom: 22 }}>
            <span className="mono" style={{ fontSize: 12, letterSpacing: "0.22em", color: "var(--teal)" }}>{number}</span>
            <EditorialLabel>{eyebrow}</EditorialLabel>
          </div>
        </Reveal>
        <Reveal delay={80}>
          <h1 className="hero-display" style={{ margin: 0, maxWidth: 1000 }}>{title}</h1>
        </Reveal>
        {subtitle && (
          <Reveal delay={160}>
            <p style={{ marginTop: 24, fontSize: 18, lineHeight: 1.55, color: "var(--fg-muted)", maxWidth: 720 }}>{subtitle}</p>
          </Reveal>
        )}
      </div>
    </header>
  );
}

// Trophy card
function TrophyCard({ trophy, idx }) {
  return (
    <div className="card-cream" style={{ padding: 0, display: "flex", flexDirection: "column", minHeight: 300, position: "relative", overflow: "hidden" }}>
      {/* Background Image if exists */}
      {trophy.imageUrl ? (
        <div style={{ position: "absolute", inset: 0, zIndex: 0 }}>
          <img src={trophy.imageUrl} alt={trophy.eventName} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.2) 60%, transparent 100%)" }}></div>
        </div>
      ) : (
        <div style={{ position: "absolute", inset: 0, background: "var(--bg-card)", opacity: 0.05 }}></div>
      )}

      <div style={{ padding: 24, position: "relative", zIndex: 1, display: "flex", flexDirection: "column", height: "100%", justifyContent: "space-between", flex: 1 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <span className="mono" style={{ fontSize: 11, letterSpacing: "0.22em", color: trophy.imageUrl ? "var(--teal)" : "var(--teal-deep)" }}>TRP / {String(idx + 1).padStart(2, "0")}</span>
          {!trophy.imageUrl && (
            <svg width="24" height="28" viewBox="0 0 24 28" fill="none" stroke="currentColor" strokeWidth="1.4" style={{ color: "var(--burgundy)" }}>
              <path d="M5 3h14v6a7 7 0 0 1-14 0V3z" />
              <path d="M5 5H2v3a3 3 0 0 0 3 3" />
              <path d="M19 5h3v3a3 3 0 0 1-3 3" />
              <path d="M10 16h4v4h-4z" />
              <path d="M7 25h10" />
              <path d="M9 25l1-5M15 25l-1-5" />
            </svg>
          )}
        </div>
        
        <div style={{ marginTop: "auto" }}>
          <p style={{ margin: 0, fontSize: 10, letterSpacing: "0.20em", textTransform: "uppercase", color: trophy.imageUrl ? "rgba(255,255,255,0.7)" : "var(--fg-muted)", marginBottom: 6 }}>
            {trophy.achievement} · {trophy.year}
          </p>
          <h3 className="h3" style={{ margin: "0 0 4px 0", color: trophy.imageUrl ? "var(--cream)" : "var(--burgundy)", fontSize: 20 }}>{trophy.eventName}</h3>
          <p style={{ margin: 0, fontSize: 13, color: trophy.imageUrl ? "rgba(255,255,255,0.6)" : "var(--ink)", fontWeight: 500 }}>{trophy.category}</p>
        </div>
      </div>
    </div>
  );
}

// Partnership card
function PartnershipCard({ partnership, highlight }) {
  return (
    <div
      className={`card ${highlight ? "surface-burgundy" : ""}`}
      style={{
        padding: 36,
        display: "flex",
        flexDirection: "column",
        gap: 22,
        background: highlight ? "var(--burgundy)" : "var(--bg-card)",
        borderColor: highlight ? "var(--burgundy)" : "var(--line)",
        color: highlight ? "var(--cream)" : "var(--fg)",
        minHeight: 540,
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span className="mono" style={{ fontSize: 11, letterSpacing: "0.22em", color: highlight ? "var(--teal-soft)" : "var(--teal-deep)" }}>
          PROGRAM KERJA SAMA
        </span>
      </div>
      <div>
        <p style={{ margin: 0, fontSize: 18, lineHeight: 1.6, color: highlight ? "var(--cream)" : "var(--fg)", fontWeight: 500 }}>
          {partnership.bestFor}
        </p>
      </div>
      <div style={{ height: 1, background: highlight ? "rgba(244,240,229,0.20)" : "var(--line)" }}></div>
      <p style={{ margin: 0, fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase", color: highlight ? "rgba(244,240,229,0.72)" : "var(--fg-muted)", fontWeight: 600 }}>Includes</p>
      <ul className="bullets" style={{ marginTop: -4 }}>
        {partnership.includes.map((it, i) => (
          <li key={i} style={{ borderColor: highlight ? "rgba(244,240,229,0.14)" : "var(--line)", color: highlight ? "var(--cream)" : "var(--fg)" }}>
            <span>{it}</span>
          </li>
        ))}
      </ul>
      <div style={{ marginTop: "auto", paddingTop: 18 }}>
        <Button variant={highlight ? "cream" : "primary"} to="/contact">Diskusikan</Button>
      </div>
    </div>
  );
}

// Expose globals
Object.assign(window, {
  navigate, useRoute, Reveal, EditorialLabel, SectionTitle, Button,
  CoachPortrait, CoachCard, ProgramCard, BenefitCard, StatCard,
  PageHeader, TrophyCard, PartnershipCard,
});
