'use client';

import { useEffect } from 'react';
import { useParlay } from '@/contexts/ParlayContext';
import { useAuth } from '@/contexts/AuthContext';
import GradeBadge from '@/components/vyndr/GradeBadge';
import ArchetypeBadge from '@/components/vyndr/ArchetypeBadge';
// 4.4 — the ONE shared stat-label formatter (lib/gradeAdapter, unit-tested).
import { statLabel } from '@/lib/gradeAdapter';

/**
 * ParlayPanel (Session 50) — the Parlay Lab. A bottom slide-up that shows the
 * selected legs, the correlation-aware combined grade, the correlation warning,
 * and the estimated payout. Tier-gated: free 2 legs (payout blurred), Analyst 4,
 * Desk 6. A floating badge (bottom-right) opens it when legs are pending.
 * Mounted globally in the layout — visible across pages.
 */

const TIER_MAX = { free: 2, analyst: 4, desk: 6 } as const;
function tierMaxLegs(tier: string): number {
  return TIER_MAX[(tier as keyof typeof TIER_MAX)] ?? 2;
}

export default function ParlayPanel() {
  const { legs, isOpen, toggle, close, open, removeLeg, clear, combined, correlation, payout, grading, maxLegs, setMaxLegs } = useParlay();
  const { tier } = useAuth();
  const fullLab = tier === 'desk' || tier === 'analyst';

  // Sync the leg cap to the user's tier.
  useEffect(() => { setMaxLegs(tierMaxLegs(tier || 'free')); }, [tier, setMaxLegs]);

  // Session 60 (night2/E, 4.4) — a discoverable entry point: the Nav's
  // PARLAY LAB item opens the drawer even with zero legs.
  useEffect(() => {
    if (typeof window === 'undefined') return;
    (window as Window & { __openParlay?: () => void }).__openParlay = open;
    return () => { delete (window as Window & { __openParlay?: () => void }).__openParlay; };
  }, [open]);

  if (legs.length === 0 && !isOpen) return null;

  // Floating trigger when closed.
  if (!isOpen && legs.length > 0) {
    return (
      <button
        type="button"
        onClick={toggle}
        aria-label={`Open Parlay Lab (${legs.length} legs)`}
        style={{
          position: 'fixed', bottom: 84, right: 18, zIndex: 60, width: 56, height: 56, borderRadius: '50%',
          background: 'var(--g-a)', color: '#06060B', fontWeight: 800, fontSize: 18, border: 'none', cursor: 'pointer',
          boxShadow: '0 0 22px rgba(0,212,160,.45)', fontFamily: 'var(--mono)',
        }}
      >
        {legs.length}
      </button>
    );
  }

  return (
    <div
      role="dialog"
      aria-label="Parlay Lab"
      style={{
        position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 70,
        maxWidth: 520, margin: '0 auto', background: 'var(--bg-1)',
        borderTop: '1px solid var(--g-a)', borderLeft: '1px solid var(--border-hi)', borderRight: '1px solid var(--border-hi)',
        borderTopLeftRadius: 16, borderTopRightRadius: 16, boxShadow: '0 -12px 40px rgba(0,0,0,.6)',
        padding: '16px 16px 22px',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <span className="mono" style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', color: 'var(--g-a)' }}>
          PARLAY LAB ({legs.length})
        </span>
        <button type="button" onClick={close} aria-label="Close" className="mono" style={{ background: 'transparent', border: 'none', color: 'var(--text-1)', cursor: 'pointer', fontSize: 16 }}>✕</button>
      </div>

      {/* Legs */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 7, marginBottom: 12, maxHeight: 220, overflowY: 'auto' }}>
        {legs.map((l) => (
          <div key={l.id} style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '8px 10px', background: 'var(--bg-2)', borderRadius: 8, border: '1px solid var(--border)' }}>
            {l.archetype && <ArchetypeBadge archetype={l.archetype} size="sm" variant="full" />}
            <span style={{ fontSize: 13, fontWeight: 700, color: '#fff', whiteSpace: 'nowrap' }}>{l.player}</span>
            {/* 4.4 — humanized stat labels via the ONE shared formatter. */}
            <span className="mono" style={{ fontSize: 11, color: 'var(--text-1)' }}>{statLabel(l.stat)} {l.direction === 'under' ? 'U' : 'O'}{l.line}</span>
            <GradeBadge grade={l.grade} size="sm" />
            <button type="button" onClick={() => removeLeg(l.id)} aria-label="Remove leg" className="mono" style={{ marginLeft: 'auto', background: 'transparent', border: 'none', color: 'var(--miss)', cursor: 'pointer', fontSize: 14 }}>✕</button>
          </div>
        ))}
      </div>

      {legs.length >= maxLegs && (
        <div className="mono" style={{ fontSize: 11, color: 'var(--amber)', marginBottom: 10 }}>
          {fullLab ? `Max ${maxLegs} legs on your plan.` : 'Free tier caps at 2 legs — upgrade to Desk for 6.'}
        </div>
      )}

      {/* Correlation warning */}
      {correlation?.warning && (
        <div className="mono" style={{ fontSize: 12, color: 'var(--amber)', marginBottom: 10 }}>{correlation.warning}</div>
      )}

      {/* Metrics */}
      {legs.length >= 2 ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
          <div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-2)', letterSpacing: '0.08em', marginBottom: 4 }}>COMBINED GRADE</div>
            {combined ? <GradeBadge grade={combined.grade} size="md" glow /> : <span className="mono" style={{ color: 'var(--text-2)' }}>{grading ? '…' : '—'}</span>}
          </div>
          <div>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-2)', letterSpacing: '0.08em', marginBottom: 4 }}>CORRELATION</div>
            <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: (correlation?.avg ?? 0) > 0.3 ? 'var(--amber)' : 'var(--g-a)' }}>
              {correlation ? `${correlation.avg > 0.5 ? 'High' : correlation.avg > 0.2 ? 'Medium' : 'Low'} (${correlation.avg.toFixed(2)})` : '—'}
            </div>
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--text-2)', letterSpacing: '0.08em', marginBottom: 4 }}>EST. PAYOUT · $10</div>
            {fullLab ? (
              <div className="mono" style={{ fontSize: 15, fontWeight: 700, color: 'var(--g-a)' }}>
                {payout ? `$${payout.amount.toFixed(2)} (${payout.multiplier.toFixed(2)}x)` : (grading ? '…' : '—')}
              </div>
            ) : (
              <div style={{ position: 'relative' }}>
                <div className="mono" style={{ fontSize: 15, fontWeight: 700, color: 'var(--g-a)', filter: 'blur(6px)', userSelect: 'none' }}>$38.50 (3.85x)</div>
                <button type="button" onClick={() => typeof window !== 'undefined' && window.__goPaywall && window.__goPaywall()} className="mono"
                  style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'transparent', border: 'none', color: 'var(--g-a)', cursor: 'pointer', fontSize: 11, fontWeight: 700 }}>
                  Upgrade to Desk for the full Parlay Lab →
                </button>
              </div>
            )}
          </div>
        </div>
      ) : legs.length === 1 ? (
        // 4.4 — the 1-leg provisional read instead of a dead panel.
        <div className="mono" style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 12, color: 'var(--text-1)', marginBottom: 14 }}>
          <span>Leg grade:</span>
          <GradeBadge grade={legs[0].grade} size="sm" />
          <span>— add a leg for the combined read.</span>
        </div>
      ) : (
        <div className="mono" style={{ fontSize: 12, color: 'var(--text-1)', marginBottom: 14 }}>
          No legs yet — tap <span style={{ color: 'var(--g-a)', fontWeight: 700 }}>+</span> on any graded prop to start building.
        </div>
      )}

      <button type="button" onClick={clear} className="mono"
        style={{ width: '100%', padding: '11px', borderRadius: 9, fontWeight: 700, letterSpacing: '0.06em', fontSize: 12, cursor: 'pointer', background: 'transparent', border: '1px solid var(--border-hi)', color: 'var(--miss)' }}>
        CLEAR ALL
      </button>
    </div>
  );
}
