import type { ExitPlan } from '../../lib/exitPlan';
import { formatPrice } from '../../lib/format';

/**
 * The exit rules that will actually close this trade.
 *
 * Deliberately sits *above* the levels ladder: the levels are context, this is
 * the plan. Before this existed the card showed a "Target" with the same visual
 * weight as the entry, implying a take-profit that the live exit never fires.
 *
 * Laid out as a vertical timeline (not label↔value rows) so the sequence —
 * stop protects → trail arms → trail rides → time stop — reads top to bottom.
 */
export function ExitPlanPanel({ plan, direction }: { plan: ExitPlan; direction: string }) {
  const isLong = direction === 'long';
  const steps = buildSteps(plan, isLong);

  return (
    <div className="mt-8 rounded-xl border border-white/[0.07] bg-white/[0.02] p-4">
      <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
        <span className="num text-[10px] uppercase tracking-[0.16em] text-gray-500">how this exits</span>
        <span className="text-[11.5px] font-medium text-gray-300">{plan.headline}</span>
      </div>

      <ol className="relative mt-3">
        {steps.map((step, i) => {
          const isLast = i === steps.length - 1;
          return (
            <li key={step.title} className="relative flex gap-2.5">
              {/* Spine column: continuous connector from this node into the next */}
              <div className="relative flex w-5 shrink-0 flex-col items-center self-stretch">
                <span
                  className="num relative z-10 mt-0.5 flex h-5 w-5 items-center justify-center rounded-full border border-blue-400/35 bg-blue-400/10 text-[10px] font-semibold text-blue-200"
                  aria-hidden
                >
                  {i + 1}
                </span>
                {!isLast && (
                  <span
                    className="absolute left-1/2 top-5 bottom-0 w-px -translate-x-1/2 bg-blue-400/25"
                    aria-hidden
                  />
                )}
              </div>

              <div className={`min-w-0 flex-1 pt-0.5 ${isLast ? 'pb-0' : 'pb-2.5'}`}>
                <p className="text-[12px] font-medium leading-tight text-gray-200">{step.title}</p>
                {step.primary && (
                  <p className="num mt-0.5 text-[13px] font-semibold leading-tight tracking-tight text-gray-100">
                    {step.primary}
                  </p>
                )}
                {step.detail && (
                  <p className="mt-0.5 text-[11px] leading-snug text-gray-500">{step.detail}</p>
                )}
              </div>
            </li>
          );
        })}
      </ol>

      {!plan.honorsTarget && (
        <p className="mt-1 border-t border-white/[0.05] pt-3 text-[11px] leading-relaxed text-gray-500">
          Levels on the chart are screening context, not sell targets.
        </p>
      )}
    </div>
  );
}

interface ExitStep {
  title: string;
  primary?: string;
  detail?: string;
}

function buildSteps(plan: ExitPlan, isLong: boolean): ExitStep[] {
  const steps: ExitStep[] = [
    {
      title: 'Protected by stop',
      primary: formatPrice(plan.initialStop),
      detail: `Risk 1R = ${formatPrice(plan.riskPerShare)} per share until the trail is live.`,
    },
  ];

  if (plan.mode === 'atr_trailing' && plan.trailTakesOverAt != null && plan.trailWidthR != null) {
    steps.push({
      title: 'Trail arms',
      primary: `${isLong ? 'above' : 'below'} ${formatPrice(plan.trailTakesOverAt)}`,
      detail: 'When the trail would sit beyond the initial stop, it takes over as the floor.',
    });
    steps.push({
      title: 'Then rides the trail',
      primary: `${formatPrice(plan.trailWidth ?? 0)}  ·  ${plan.trailWidthR.toFixed(1)}R give-back`,
      detail: isLong
        ? 'Stop = highest close minus trail width. Winners run — no take-profit.'
        : 'Stop = lowest close plus trail width. Winners run — no take-profit.',
    });
  } else if (plan.mode === 'trailing' && plan.trailWidth != null && plan.trailWidthR != null) {
    steps.push({
      title: 'Trailing stop',
      primary: `${formatPrice(plan.trailWidth)}  ·  ${plan.trailWidthR.toFixed(1)}R give-back`,
      detail: 'Follows price; no fixed take-profit.',
    });
  } else if (plan.mode === 'target') {
    steps.push({
      title: 'Take profit',
      primary: 'At the selected level',
      detail: 'Or exit at the stop if price reverses first.',
    });
  }

  // Same visual weight as the other steps — time stop is a real exit rule,
  // not a footnote.
  steps.push({
    title: 'Time stop',
    primary: `${plan.maxHoldDays} trading days`,
    detail: 'Flat if still open after the max hold.',
  });

  return steps;
}
