/* ============================================================
   HOCHZEITSPLANER — Hilfsfunktionen + kleine Komponenten
   ============================================================ */

const fmtEUR = (v, opts = {}) => {
  if (v == null || isNaN(v)) return "—";
  const formatter = new Intl.NumberFormat("de-DE", {
    style: "currency",
    currency: "EUR",
    minimumFractionDigits: opts.decimals ?? 0,
    maximumFractionDigits: opts.decimals ?? 0,
  });
  return formatter.format(v);
};

const fmtEURcents = (v) => fmtEUR(v, { decimals: 2 });

const fmtDate = (iso, opts = { day: "numeric", month: "long", year: "numeric" }) => {
  return new Date(iso + "T12:00:00").toLocaleDateString("de-DE", opts);
};

const fmtDateShort = (iso) =>
  new Date(iso + "T12:00:00").toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit" });

const daysBetween = (a, b) => {
  const da = new Date(a + "T12:00:00").getTime();
  const db = new Date(b + "T12:00:00").getTime();
  return Math.round((db - da) / (1000 * 60 * 60 * 24));
};

const todayISO = () => new Date().toISOString().slice(0, 10);

const sum = (arr, key) => arr.reduce((a, b) => a + (key ? b[key] : b), 0);

// Donut color palette (will be used in order)
const DONUT_COLORS = [
  "#7a2929", // wine
  "#b8924d", // gold
  "#5f7a64", // sage
  "#c87454", // terra
  "#a85656", // wine soft
  "#8c6b30", // gold deep
  "#c5d2c4", // sage soft
  "#e6cfca", // rose
  "#1c1612", // ink
  "#8a7c6d", // mute
  "#5a1d1d", // wine deep
  "#e8d9b6", // gold soft
];

// =============================================================
//  Countdown chip
// =============================================================
function Countdown({ targetISO }) {
  const [now, setNow] = React.useState(new Date());
  React.useEffect(() => {
    const t = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(t);
  }, []);
  const target = new Date(targetISO + "T11:00:00");
  const diff = target - now;
  if (diff <= 0) {
    return (
      <div className="countdown-chip">
        <span>Heute! </span>
        <strong>❤</strong>
      </div>
    );
  }
  const d = Math.floor(diff / (1000 * 60 * 60 * 24));
  const h = Math.floor((diff / (1000 * 60 * 60)) % 24);
  const m = Math.floor((diff / (1000 * 60)) % 60);
  return (
    <div className="countdown-chip">
      <span>{fmtDate(targetISO, { day: "numeric", month: "long", year: "numeric" })}</span>
      <span>·</span>
      <strong>T-{d} Tage</strong>
    </div>
  );
}

// =============================================================
//  Donut chart (SVG)
//  data: [{label, value, color}]
// =============================================================
function Donut({ data, size = 340, thickness = 36, center }) {
  const total = sum(data, "value") || 1;
  const r = size / 2 - thickness / 2 - 6;
  const cx = size / 2;
  const cy = size / 2;

  let acc = 0;
  const arcs = data.map((d, i) => {
    const start = (acc / total) * Math.PI * 2;
    acc += d.value;
    const end = (acc / total) * Math.PI * 2;
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + r * Math.sin(start);
    const y1 = cy - r * Math.cos(start);
    const x2 = cx + r * Math.sin(end);
    const y2 = cy - r * Math.cos(end);
    if (d.value === 0) return null;
    return (
      <path
        key={i}
        d={`M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`}
        fill="none"
        stroke={d.color}
        strokeWidth={thickness}
        strokeLinecap="butt"
      />
    );
  });

  return (
    <div className="donut-wrap">
      <svg className="donut-svg" width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#ece2ce" strokeWidth={thickness} />
        {arcs}
      </svg>
      {center && <div className="donut-center">{center}</div>}
      <div className="donut-legend">
        {data.map((d, i) => (
          <div className="donut-legend-row" key={i}>
            <span className="sw" style={{ background: d.color }} />
            <span className="nm" title={d.label}>{d.label}</span>
            <span>{Math.round((d.value / total) * 100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// =============================================================
//  Budget bar row
// =============================================================
function BudgetBar({ name, budget, paid, color = "var(--wine)" }) {
  const maxBudget = Math.max(budget, paid);
  const paidPct = budget > 0 ? Math.min(100, (paid / budget) * 100) : 0;
  const over = paid > budget;
  const done = !over && paid >= budget && budget > 0;
  return (
    <div className="cat-row">
      <div className="cat-name">{name}</div>
      <div className={`cat-bar ${over ? "over" : ""} ${done ? "done" : ""}`}>
        <div className="fill-budget" style={{ width: "100%" }} />
        <div className="fill-paid" style={{ width: `${paidPct}%`, background: done ? "var(--sage)" : (over ? "var(--terra)" : `linear-gradient(90deg, ${color}, var(--wine-soft))`) }} />
        <span className="cat-bar-label">{Math.round(paidPct)}%</span>
      </div>
      <div className="cat-amounts">
        <span className="num">{fmtEUR(paid)}</span>
        <span className="sep">/</span>
        <span>{fmtEUR(budget)}</span>
      </div>
    </div>
  );
}

// =============================================================
//  Section header
// =============================================================
function SectionHead({ eyebrow, title, sub, right }) {
  return (
    <div className="section-head">
      <div>
        {eyebrow && <div className="eyebrow" style={{ marginBottom: 8 }}>{eyebrow}</div>}
        <h2 className="section-title" dangerouslySetInnerHTML={{ __html: title }} />
      </div>
      {sub && <div className="section-sub">{sub}</div>}
      {right}
    </div>
  );
}

// Expose to global scope so other Babel scripts can use these
Object.assign(window, {
  fmtEUR, fmtEURcents, fmtDate, fmtDateShort, daysBetween, todayISO,
  sum, DONUT_COLORS,
  Countdown, Donut, BudgetBar, SectionHead,
});
