"use client";

import { useState } from "react";
import { CALCULATOR } from "@/lib/platform-content";

const fmt = (n: number) =>
  n.toLocaleString("en-KE", { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// "Run the Numbers" — organizer types a ticket price, we show the split.
// feeRate/flatFee/currency come live from site settings; constants are the fallback.
export default function EarningsCalculator({
  feeRate = CALCULATOR.feeRate,
  flatFee = CALCULATOR.flatFee,
  currency = CALCULATOR.currency,
}: {
  feeRate?: number;
  flatFee?: number;
  currency?: string;
}) {
  const [amount, setAmount] = useState<number>(CALCULATOR.defaultAmount);

  const safeAmount = Number.isNaN(amount) ? 0 : amount;
  const fee = safeAmount > 0 ? Math.round((safeAmount * feeRate + flatFee) * 100) / 100 : 0;
  const receive = Math.max(0, safeAmount - fee);
  const c = currency;

  return (
    <div className="rounded-3xl border border-line bg-panel p-6 sm:p-8">
      <label className="block text-xs font-bold uppercase tracking-[0.2em] text-muted">
        If your ticket costs
      </label>
      <div className="mt-3 flex items-center gap-3 rounded-2xl border border-line bg-panel-soft px-5 py-4 focus-within:border-brand-green">
        <span className="text-2xl font-black text-muted">{c}</span>
        <input
          type="number"
          min={0}
          inputMode="numeric"
          value={Number.isNaN(amount) ? "" : amount}
          onChange={(e) => setAmount(parseFloat(e.target.value))}
          className="w-full bg-transparent text-3xl font-black text-white outline-none placeholder:text-muted"
          placeholder="2000"
          aria-label="Ticket price"
        />
      </div>

      <div className="mt-8 grid grid-cols-2 gap-6">
        <div>
          <p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-green-h">
            You receive
          </p>
          <p className="mt-2 text-2xl sm:text-3xl font-black text-white">
            {c} {fmt(receive)}
          </p>
        </div>
        <div>
          <p className="text-xs font-bold uppercase tracking-[0.2em] text-muted">We make</p>
          <p className="mt-2 text-2xl sm:text-3xl font-black text-muted">
            {c} {fmt(fee)}
          </p>
        </div>
      </div>

      <p className="mt-6 text-xs text-muted">
        Based on {(feeRate * 100).toFixed(2)}%
        {flatFee ? ` + ${c} ${flatFee}` : ""} per ticket sold — or pass the fee to buyers and
        keep it all. We only earn when you do.
      </p>
    </div>
  );
}
