import { useMemo } from 'react'
import type { BreakEvenPoint } from './model'
import { money } from './format'

// This chart answers one question: own (CD Baby) vs rent-flat (DistroKid).
// Stack tracks CD Baby exactly on cost, so it's folded into that line. RouteNote
// Premium is deliberately omitted — its cost runs 5–10× higher and would crush
// the crossover's resolution; its story is told in its card instead.
interface Line {
  id: string
  label: string
  color: string
  dash?: boolean
}
const LINES: Line[] = [
  { id: 'distrokid', label: 'DistroKid (flat)', color: 'var(--color-melodic)' },
  { id: 'cdbaby', label: 'CD Baby (per release)', color: 'var(--color-tops)' },
  { id: 'routenote-free', label: 'RouteNote Free', color: 'var(--color-ink-faint)', dash: true },
]

interface Props {
  sweep: BreakEvenPoint[]
  currentCadence: number
  crossover: number | null
}

const W = 640
const H = 280
const PAD = { t: 16, r: 16, b: 36, l: 56 }

export function BreakEvenChart({ sweep, currentCadence, crossover }: Props) {
  const { paths, maxX, xOf, yOf, ticksY } = useMemo(() => {
    const maxX = sweep.length - 1
    const maxCost = Math.max(
      1,
      ...sweep.flatMap((p) => LINES.map((l) => p.costs[l.id] ?? 0)),
    )
    // round the axis up to a clean ceiling
    const mag = Math.pow(10, Math.floor(Math.log10(maxCost)))
    const maxY = Math.ceil(maxCost / mag) * mag
    const xOf = (cad: number) => PAD.l + (cad / maxX) * (W - PAD.l - PAD.r)
    const yOf = (cost: number) => H - PAD.b - (cost / maxY) * (H - PAD.t - PAD.b)
    const paths = LINES.map((l) => ({
      ...l,
      d: sweep
        .map((p, i) => `${i === 0 ? 'M' : 'L'}${xOf(p.cadence).toFixed(1)},${yOf(p.costs[l.id] ?? 0).toFixed(1)}`)
        .join(' '),
    }))
    const ticksY = [0, 0.25, 0.5, 0.75, 1].map((f) => f * maxY)
    return { paths, maxX, xOf, yOf, ticksY }
  }, [sweep])

  return (
    <figure className="m-0">
      <svg
        viewBox={`0 0 ${W} ${H}`}
        className="h-auto w-full"
        role="img"
        aria-label="Lifetime distributor cost as a function of releases per year"
      >
        {/* y grid + labels */}
        {ticksY.map((t) => (
          <g key={t}>
            <line x1={PAD.l} x2={W - PAD.r} y1={yOf(t)} y2={yOf(t)} stroke="var(--color-hairline)" />
            <text x={PAD.l - 8} y={yOf(t) + 4} textAnchor="end" className="fill-[var(--color-ink-faint)] text-[10px]">
              {money(t)}
            </text>
          </g>
        ))}
        {/* x labels */}
        {sweep
          .filter((_, i) => i % 4 === 0)
          .map((p) => (
            <text
              key={p.cadence}
              x={xOf(p.cadence)}
              y={H - PAD.b + 18}
              textAnchor="middle"
              className="fill-[var(--color-ink-faint)] text-[10px]"
            >
              {p.cadence}
            </text>
          ))}
        <text
          x={(PAD.l + W - PAD.r) / 2}
          y={H - 4}
          textAnchor="middle"
          className="fill-[var(--color-ink-muted)] text-[10px]"
        >
          releases per year →
        </text>

        {/* crossover marker: where DistroKid overtakes CD Baby on cost */}
        {crossover != null && crossover > 0 && crossover <= maxX ? (
          <g>
            <line
              x1={xOf(crossover)}
              x2={xOf(crossover)}
              y1={PAD.t}
              y2={H - PAD.b}
              stroke="var(--color-ink-muted)"
              strokeDasharray="3 3"
            />
            <text x={xOf(crossover) + 6} y={PAD.t + 12} className="fill-[var(--color-ink-muted)] text-[10px]">
              break-even ≈ {crossover}/yr
            </text>
          </g>
        ) : (
          <text x={PAD.l + 8} y={PAD.t + 12} className="fill-[var(--color-ink-muted)] text-[10px]">
            {crossover === 0 ? 'DistroKid cheaper at every cadence' : 'CD Baby cheaper at every cadence'}
          </text>
        )}

        {/* current cadence: you are here */}
        <g>
          <line
            x1={xOf(currentCadence)}
            x2={xOf(currentCadence)}
            y1={PAD.t}
            y2={H - PAD.b}
            stroke="var(--color-magenta)"
            strokeWidth={1.5}
          />
          <circle cx={xOf(currentCadence)} cy={PAD.t} r={3} fill="var(--color-magenta)" />
        </g>

        {/* lines */}
        {paths.map((p) => (
          <path
            key={p.id}
            d={p.d}
            fill="none"
            stroke={p.color}
            strokeWidth={2}
            strokeDasharray={p.dash ? '4 4' : undefined}
            strokeLinejoin="round"
          />
        ))}
      </svg>

      <figcaption className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-[11px] text-ink-muted">
        {LINES.map((l) => (
          <span key={l.id} className="inline-flex items-center gap-1.5">
            <span
              aria-hidden
              className="inline-block h-0.5 w-4"
              style={{ background: l.color, opacity: l.dash ? 0.7 : 1 }}
            />
            {l.label}
          </span>
        ))}
        <span className="inline-flex items-center gap-1.5">
          <span aria-hidden className="inline-block h-3 w-0.5 bg-magenta" />
          your cadence
        </span>
      </figcaption>
    </figure>
  )
}
