// fund-progress.jsx — Fundraising progress visualization

function FundProgress({ amount, goal = 300000, milestones = [], animate = false, compact = false }) {
  const { useState, useEffect, useRef } = React;

  const pct = Math.min(100, (amount / goal) * 100);
  const [displayAmount, setDisplayAmount] = useState(animate ? 0 : amount);
  const [displayPct, setDisplayPct]       = useState(animate ? 0 : pct);
  const [triggered, setTriggered]         = useState(false);
  const containerRef = useRef(null);

  // Trigger animation only when component enters the viewport
  useEffect(() => {
    if (!animate) return;
    const el = containerRef.current;
    if (!el) return;
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setTriggered(true);
          observer.disconnect();
        }
      },
      { threshold: 0.15 }
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, [animate]);

  // Count-up runs once, when triggered becomes true
  useEffect(() => {
    if (!animate || !triggered) return;
    let start = null;
    const duration = 1600;
    const step = (ts) => {
      if (!start) start = ts;
      const elapsed = Math.min(ts - start, duration);
      const eased   = 1 - Math.pow(1 - elapsed / duration, 3);
      setDisplayAmount(Math.round(amount * eased));
      setDisplayPct(pct * eased);
      if (elapsed < duration) requestAnimationFrame(step);
    };
    const r = requestAnimationFrame(step);
    return () => cancelAnimationFrame(r);
  }, [animate, triggered, amount, pct]);

  const fmt = (n) => new Intl.NumberFormat("sv-SE").format(n);
  const remaining     = Math.max(0, goal - amount);
  const nextMilestone = milestones.find((m) => m.amount > amount);

  return (
    <div ref={containerRef} className={"fund " + (compact ? "fund--compact" : "")}>
      {/* Top — big numbers */}
      <div className="fund__top">
        <div className="fund__main">
          <p className="eyebrow eyebrow--paper">Insamlat</p>
          <p className="fund__amount display">
            <span className="serif-num">{fmt(displayAmount)}</span>
            <span className="fund__amount-unit">kr</span>
          </p>
          <p className="fund__sub">
            av {fmt(goal)} kr · <span className="fund__pct serif-num">{displayPct.toFixed(1)}%</span>
          </p>
        </div>
        {nextMilestone && (
          <div className="fund__next">
            <p className="eyebrow eyebrow--paper">Nästa milstolpe</p>
            <p className="display display-s" style={{ color: "var(--gold)", marginTop: 6 }}>
              {nextMilestone.label}
            </p>
            <p className="fund__next-amount">
              <span className="serif-num">{fmt(nextMilestone.amount - amount)}</span> kr kvar
            </p>
          </div>
        )}
      </div>

      {/* Bar */}
      <div className="fund__bar-wrap">
        <div className="fund__bar">
          <div
            className="fund__bar-fill"
            style={{
              width: `${displayPct}%`,
              transition: animate && triggered ? "width 0.4s ease-out" : "none",
            }}
          />
          {milestones.map((m, i) => {
            const x       = (m.amount / goal) * 100;
            const reached = amount >= m.amount;
            return (
              <div
                key={i}
                className={"fund__marker " + (reached ? "fund__marker--reached" : "")}
                style={{ left: `${x}%` }}
                title={`${fmt(m.amount)} kr · ${m.label}`}
              />
            );
          })}
        </div>
      </div>

      {/* Milestones list */}
      <div className="fund__milestones">
        {milestones.map((m, i) => {
          const reached = amount >= m.amount;
          const isNext  = !reached && (i === 0 || amount >= milestones[i - 1].amount);
          return (
            <article
              key={i}
              className={
                "milestone " +
                (reached ? "milestone--reached " : "") +
                (isNext   ? "milestone--next"    : "")
              }
            >
              <div className="milestone__head">
                <span className="milestone__check" aria-hidden="true">
                  {reached ? "✓" : (i + 1).toString().padStart(2, "0")}
                </span>
                <span className="milestone__amount serif-num">
                  {fmt(m.amount)} kr
                </span>
              </div>
              <p className="milestone__label">{m.label}</p>
              <p className="milestone__desc">{m.desc}</p>
            </article>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { FundProgress });
