// Countdown — static display of days remaining until the wedding date.
// Pinned to the bottom-left of the viewport like a footer signature.
// Date parsing is intentionally forgiving: accepts things like
// "Saturday · 29 August 2026" or "29 August 2026".

function Countdown({ targetDate }) {
  const target = React.useMemo(() => parseWeddingDate(targetDate), [targetDate]);
  if (!target) return null;

  const now = new Date();
  const msPerDay = 24 * 60 * 60 * 1000;
  const daysRaw = Math.ceil((target.getTime() - now.getTime()) / msPerDay);

  // If the date has passed, show elapsed or a celebratory label.
  const past = daysRaw < 0;
  const days = Math.abs(daysRaw);

  return (
    <div className="countdown" aria-label="countdown to the wedding">
      <span className="cd-value">
        {days}
        <span className="cd-unit"> {days === 1 ? 'day' : 'days'}{past ? ' ago' : ' to go'}</span>
      </span>
    </div>
  );
}

function parseWeddingDate(str) {
  if (!str) return null;
  // Strip leading weekday + separator if present: "Saturday · 29 August 2026"
  const cleaned = String(str).replace(/^[^0-9]*?(?=\d)/, '').trim();
  const d = new Date(cleaned);
  if (!isNaN(d.getTime())) return d;
  // Fallback: try original string
  const d2 = new Date(str);
  return isNaN(d2.getTime()) ? null : d2;
}

window.Countdown = Countdown;
