/* Color tool — modal palette explorer.
   Opens from any swatch click on the brand page or from the header palette
   button. Shows every ramp, lets users copy hex/rgb/hsl, and checks
   WCAG contrast against the foreground/background combos that matter. */

const COLOR_TOOL_RAMPS = [
  {
    key: 'brand', label: 'Brand · Penn Blue', anchor: 600, prefix: 'brand',
    steps: [
      { step: 25,  hex: '#F8F9FC' }, { step: 50,  hex: '#F1F2F9' },
      { step: 100, hex: '#DDDFE9' }, { step: 200, hex: '#B4B7D4' },
      { step: 300, hex: '#8488B6' }, { step: 400, hex: '#5558A0' },
      { step: 500, hex: '#2A2D78' }, { step: 600, hex: '#121541' },
      { step: 700, hex: '#0E1034' }, { step: 800, hex: '#0A0C28' },
      { step: 900, hex: '#06081C' }, { step: 950, hex: '#03040E' },
    ],
  },
  {
    key: 'accent', label: 'Accent · Aureolin', anchor: 400, prefix: 'accent',
    steps: [
      { step: 25,  hex: '#FFFDE8' }, { step: 50,  hex: '#FEF8B8' },
      { step: 100, hex: '#FDF17D' }, { step: 200, hex: '#FCEB55' },
      { step: 300, hex: '#FDE033' }, { step: 400, hex: '#F7EC33' },
      { step: 500, hex: '#E0D420' }, { step: 600, hex: '#B8AC10' },
      { step: 700, hex: '#8A7F0A' }, { step: 800, hex: '#5A5405' },
      { step: 900, hex: '#2E2B02' },
    ],
  },
  {
    key: 'neutral', label: 'Neutral', prefix: 'neutral',
    steps: [
      { step: 25,  hex: '#FCFCFD' }, { step: 50,  hex: '#F9FAFB' },
      { step: 100, hex: '#F2F4F7' }, { step: 200, hex: '#EAECF0' },
      { step: 300, hex: '#D0D5DD' }, { step: 400, hex: '#98A2B3' },
      { step: 500, hex: '#667085' }, { step: 600, hex: '#475467' },
      { step: 700, hex: '#344054' }, { step: 800, hex: '#1D2939' },
      { step: 900, hex: '#101828' }, { step: 950, hex: '#0C111D' },
    ],
  },
];

const COLOR_TOOL_SINGLES = [
  { name: 'Dodger Blue',  hex: '#1E96FC', group: 'Supporting', cssVar: '--dodger-blue' },
  { name: 'Signal Red',   hex: '#FF331F', group: 'Supporting', cssVar: '--signal-red' },
  { name: 'Pine Green',   hex: '#17301C', group: 'Supporting', cssVar: '--pine-green' },
  { name: 'Humus',        hex: '#484538', group: 'Supporting', cssVar: '--humus' },
  { name: 'Success',      hex: '#17B26A', group: 'Semantic',   cssVar: '--success-500' },
  { name: 'Warning',      hex: '#F79009', group: 'Semantic',   cssVar: '--warning-500' },
  { name: 'Error',        hex: '#F04438', group: 'Semantic',   cssVar: '--error-500'   },
  { name: 'Paper',        hex: '#FFFFFF', group: 'Canvas',     cssVar: null            },
];

/* ---------- Color math ---------- */
function ctHexToRgb(hex) {
  const h = hex.replace('#', '').trim();
  const n = h.length === 3 ? h.split('').map(c => c + c).join('') : h;
  if (n.length !== 6) return null;
  const v = parseInt(n, 16);
  return { r: (v >> 16) & 255, g: (v >> 8) & 255, b: v & 255 };
}

function ctRgbToHsl({ r, g, b }) {
  r /= 255; g /= 255; b /= 255;
  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  let h = 0, s = 0, l = (max + min) / 2;
  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break;
      case g: h = (b - r) / d + 2; break;
      case b: h = (r - g) / d + 4; break;
    }
    h *= 60;
  }
  return { h: Math.round(h), s: Math.round(s * 100), l: Math.round(l * 100) };
}

function ctRelLum({ r, g, b }) {
  const f = (c) => {
    const x = c / 255;
    return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
  };
  return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
}

function ctContrast(hexA, hexB) {
  const a = ctHexToRgb(hexA), b = ctHexToRgb(hexB);
  if (!a || !b) return 1;
  const la = ctRelLum(a), lb = ctRelLum(b);
  const ratio = (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
  return Math.round(ratio * 100) / 100;
}

function ctWcagBadge(ratio) {
  if (ratio >= 7)   return { label: 'AAA', tone: 'pass' };
  if (ratio >= 4.5) return { label: 'AA',  tone: 'pass' };
  if (ratio >= 3)   return { label: 'AA Large', tone: 'warn' };
  return { label: 'Fail', tone: 'fail' };
}

/* ---------- Lookup: which ramp+step is a given hex? ---------- */
function ctIdentifyHex(hex) {
  const norm = hex.toUpperCase();
  for (const ramp of COLOR_TOOL_RAMPS) {
    for (const s of ramp.steps) {
      if (s.hex.toUpperCase() === norm) {
        return {
          name: `${ramp.label.split('·')[0].trim()} ${s.step}`,
          cssVar: `--${ramp.prefix}-${s.step}`,
          group: ramp.label,
        };
      }
    }
  }
  for (const s of COLOR_TOOL_SINGLES) {
    if (s.hex.toUpperCase() === norm) {
      return { name: s.name, cssVar: s.cssVar, group: s.group };
    }
  }
  return { name: 'Custom', cssVar: null, group: '—' };
}

/* ---------- Provider + hook ---------- */
const ColorToolContext = createContext({ open: () => {}, close: () => {} });
function useColorTool() { return useContext(ColorToolContext); }

function ColorToolProvider({ children }) {
  const [openHex, setOpenHex] = useState(null);
  const open = (hex = '#121541') => setOpenHex(hex);
  const close = () => setOpenHex(null);
  return (
    <ColorToolContext.Provider value={{ open, close }}>
      {children}
      {openHex && <ColorToolModal initialHex={openHex} onClose={close} />}
    </ColorToolContext.Provider>
  );
}

/* ---------- Header button — palette glyph ---------- */
function ColorToolButton() {
  const { open } = useColorTool();
  return (
    <button
      onClick={() => open('#121541')}
      title="Open colour tool"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '6px 10px',
        borderRadius: 8,
        background: 'var(--bg-secondary)',
        border: '1px solid var(--border-secondary)',
        color: 'var(--text-secondary)',
        fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
        cursor: 'pointer',
      }}
    >
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M12 22a10 10 0 1 1 10-10c0 2.5-2 4-4 4h-2a2 2 0 0 0 0 4c0 1.1-.9 2-2 2h-2z"
          stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" />
        <circle cx="7.5"  cy="11"  r="1.2" fill="#1E96FC" />
        <circle cx="10"   cy="7"   r="1.2" fill="#F04438" />
        <circle cx="14"   cy="7"   r="1.2" fill="#F7EC33" />
        <circle cx="16.5" cy="11"  r="1.2" fill="#17B26A" />
      </svg>
      Colours
    </button>
  );
}

/* ---------- Copy chip ---------- */
function CtCopyRow({ label, value }) {
  const [copied, setCopied] = useState(false);
  const onCopy = () => {
    copy(value);
    setCopied(true);
    setTimeout(() => setCopied(false), 1100);
  };
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '88px 1fr auto',
      alignItems: 'center', gap: 12,
      padding: '8px 10px',
      borderRadius: 8,
      background: 'var(--bg-secondary)',
      border: '1px solid var(--border-tertiary)',
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em',
        textTransform: 'uppercase', color: 'var(--text-quaternary)' }}>{label}</div>
      <code style={{ fontFamily: 'var(--font-mono)', fontSize: 12,
        color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis',
        whiteSpace: 'nowrap' }}>{value}</code>
      <button
        onClick={onCopy}
        style={{
          border: '1px solid var(--border-secondary)',
          background: copied ? 'var(--brand-600)' : 'var(--bg-primary)',
          color: copied ? '#fff' : 'var(--text-secondary)',
          fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 6,
          cursor: 'pointer', fontFamily: 'inherit', minWidth: 56,
        }}
      >{copied ? '✓' : 'Copy'}</button>
    </div>
  );
}

/* ---------- Mini ramp inside the modal ---------- */
function CtRamp({ ramp, selected, onPick, query }) {
  const visible = ramp.steps.filter(s => {
    if (!query) return true;
    const q = query.toLowerCase();
    return ramp.label.toLowerCase().includes(q)
      || ramp.prefix.includes(q)
      || s.hex.toLowerCase().includes(q)
      || String(s.step).includes(q);
  });
  if (!visible.length) return null;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 8 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)' }}>
          {ramp.label}
        </div>
        <code style={{ fontFamily: 'var(--font-mono)', fontSize: 11,
          color: 'var(--text-quaternary)' }}>--{ramp.prefix}-*</code>
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: `repeat(${visible.length}, 1fr)`,
        gap: 2, borderRadius: 8, overflow: 'hidden',
        border: '1px solid var(--border-secondary)',
      }}>
        {visible.map(s => {
          const dark = s.step >= 400;
          const isSel = selected === s.hex.toUpperCase();
          const isAnc = ramp.anchor === s.step;
          return (
            <button
              key={s.step}
              onClick={() => onPick(s.hex)}
              title={`${ramp.prefix}-${s.step} · ${s.hex.toUpperCase()}`}
              style={{
                background: s.hex,
                height: 64,
                position: 'relative',
                padding: 6,
                cursor: 'pointer',
                border: 'none',
                outline: isSel ? '3px solid var(--accent-400)' : 'none',
                outlineOffset: -3,
                display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                color: dark ? 'rgba(255,255,255,.92)' : 'var(--brand-700)',
                fontFamily: 'var(--font-mono)', fontSize: 10,
              }}
            >
              <span>{s.step}</span>
              <span style={{ opacity: .8 }}>{s.hex.replace('#', '').toUpperCase()}</span>
              {isAnc && (
                <span style={{
                  position: 'absolute', top: 6, right: 6,
                  fontSize: 8, fontWeight: 700, letterSpacing: '.06em',
                  background: 'var(--accent-400)', color: 'var(--brand-700)',
                  padding: '1px 4px', borderRadius: 3,
                }}>ANCHOR</span>
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Modal ---------- */
function ColorToolModal({ initialHex, onClose }) {
  const [selected, setSelected] = useState((initialHex || '#121541').toUpperCase());
  const [query, setQuery] = useState('');
  const overlayRef = useRef(null);

  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  const id = useMemo(() => ctIdentifyHex(selected), [selected]);
  const rgb = useMemo(() => ctHexToRgb(selected), [selected]);
  const hsl = useMemo(() => rgb ? ctRgbToHsl(rgb) : null, [rgb]);

  const formats = rgb && hsl ? [
    { label: 'Hex',    value: selected },
    { label: 'RGB',    value: `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})` },
    { label: 'HSL',    value: `hsl(${hsl.h} ${hsl.s}% ${hsl.l}%)` },
    ...(id.cssVar ? [{ label: 'CSS var', value: `var(${id.cssVar})` }] : []),
  ] : [];

  // Contrast checks against the four most useful targets
  const contrastTargets = [
    { name: 'White',     hex: '#FFFFFF' },
    { name: 'Black',     hex: '#000000' },
    { name: 'Penn Blue', hex: '#121541' },
    { name: 'Aureolin',  hex: '#F7EC33' },
  ];

  const visibleSingles = COLOR_TOOL_SINGLES.filter(s => {
    if (!query) return true;
    const q = query.toLowerCase();
    return s.name.toLowerCase().includes(q)
      || s.hex.toLowerCase().includes(q)
      || (s.cssVar || '').includes(q)
      || s.group.toLowerCase().includes(q);
  });

  return (
    <div
      ref={overlayRef}
      onClick={(e) => { if (e.target === overlayRef.current) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(8, 10, 28, 0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
      }}
    >
      <div style={{
        width: 'min(1100px, 100%)', maxHeight: '92vh', display: 'flex', flexDirection: 'column',
        background: 'var(--bg-primary)',
        border: '1px solid var(--border-secondary)',
        borderRadius: 16,
        boxShadow: '0 32px 64px -12px rgba(16,24,40,.28)',
        overflow: 'hidden',
      }}>
        {/* Header */}
        <div style={{
          padding: '16px 20px', borderBottom: '1px solid var(--border-tertiary)',
          display: 'flex', alignItems: 'center', gap: 16, flexShrink: 0,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--accent-400)' }} />
            <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.01em' }}>
              Colour tool
            </div>
            <div style={{ fontSize: 12, color: 'var(--text-quaternary)' }}>
              Click any swatch · ⌘C copies selection · Esc to close
            </div>
          </div>
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Filter by name, hex, step…"
            style={{
              marginLeft: 'auto', width: 240,
              padding: '7px 10px',
              border: '1px solid var(--border-primary)',
              borderRadius: 8, fontSize: 13,
              background: 'var(--bg-primary)', color: 'var(--text-primary)',
              fontFamily: 'inherit', outline: 'none',
            }}
          />
          <button onClick={onClose} aria-label="Close" style={{
            border: '1px solid var(--border-secondary)',
            background: 'var(--bg-primary)',
            color: 'var(--text-secondary)',
            width: 30, height: 30, borderRadius: 8,
            cursor: 'pointer', fontSize: 16, lineHeight: 1,
          }}>×</button>
        </div>

        {/* Body — two column layout */}
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 360px',
          gap: 0, flex: 1, minHeight: 0,
        }}>
          {/* Left: ramps + singles, scrollable */}
          <div style={{
            padding: 20,
            overflowY: 'auto',
            display: 'flex', flexDirection: 'column', gap: 18,
            borderRight: '1px solid var(--border-tertiary)',
          }}>
            {COLOR_TOOL_RAMPS.map(r => (
              <CtRamp
                key={r.key}
                ramp={r}
                selected={selected.toUpperCase()}
                onPick={(hex) => setSelected(hex.toUpperCase())}
                query={query}
              />
            ))}

            {visibleSingles.length > 0 && (
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-primary)',
                  marginBottom: 8 }}>Supporting & semantic</div>
                <div style={{
                  display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(120px, 1fr))', gap: 8,
                }}>
                  {visibleSingles.map(s => {
                    const isSel = selected.toUpperCase() === s.hex.toUpperCase();
                    const dark = ctRelLum(ctHexToRgb(s.hex) || { r: 0, g: 0, b: 0 }) < 0.5;
                    return (
                      <button
                        key={s.hex}
                        onClick={() => setSelected(s.hex.toUpperCase())}
                        title={`${s.name} · ${s.hex}`}
                        style={{
                          padding: 10, height: 72,
                          background: s.hex,
                          border: 'none',
                          borderRadius: 8,
                          textAlign: 'left',
                          cursor: 'pointer',
                          color: dark ? '#fff' : 'var(--brand-700)',
                          outline: isSel ? '3px solid var(--accent-400)' : '1px solid var(--border-secondary)',
                          outlineOffset: -1,
                          display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                        }}
                      >
                        <span style={{ fontSize: 12, fontWeight: 600 }}>{s.name}</span>
                        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, opacity: .85 }}>
                          {s.hex.toUpperCase().replace('#', '')}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}
          </div>

          {/* Right: detail panel */}
          <div style={{
            padding: 20, background: 'var(--bg-secondary)',
            overflowY: 'auto',
            display: 'flex', flexDirection: 'column', gap: 16,
          }}>
            {/* Selected swatch hero */}
            <div style={{
              background: selected,
              height: 132, borderRadius: 12,
              border: '1px solid var(--border-secondary)',
              display: 'flex', alignItems: 'flex-end', padding: 16,
              color: ctRelLum(rgb || { r: 0, g: 0, b: 0 }) < 0.5 ? '#fff' : 'var(--brand-700)',
            }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: '-0.01em' }}>{id.name}</div>
                <div style={{ fontSize: 11, opacity: .75, marginTop: 2 }}>{id.group}</div>
              </div>
            </div>

            {/* Custom hex input */}
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em',
                textTransform: 'uppercase', color: 'var(--text-quaternary)', marginBottom: 6 }}>
                Custom hex
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <input
                  type="color"
                  value={selected}
                  onChange={(e) => setSelected(e.target.value.toUpperCase())}
                  style={{
                    width: 38, height: 36, padding: 0,
                    border: '1px solid var(--border-secondary)', borderRadius: 6,
                    cursor: 'pointer', background: 'var(--bg-primary)',
                  }}
                />
                <input
                  value={selected}
                  onChange={(e) => {
                    let v = e.target.value.toUpperCase().replace(/[^#0-9A-F]/g, '');
                    if (v && v[0] !== '#') v = '#' + v;
                    setSelected(v.slice(0, 7));
                  }}
                  style={{
                    flex: 1, padding: '8px 10px',
                    border: '1px solid var(--border-primary)', borderRadius: 6,
                    fontFamily: 'var(--font-mono)', fontSize: 13,
                    background: 'var(--bg-primary)', color: 'var(--text-primary)',
                    outline: 'none',
                  }}
                />
              </div>
            </div>

            {/* Format copy chips */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {formats.map(f => (
                <CtCopyRow key={f.label} label={f.label} value={f.value} />
              ))}
            </div>

            {/* Contrast */}
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em',
                textTransform: 'uppercase', color: 'var(--text-quaternary)', marginBottom: 8 }}>
                Contrast
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {contrastTargets.map(t => {
                  const r = ctContrast(selected, t.hex);
                  const w = ctWcagBadge(r);
                  const tone = w.tone === 'pass' ? 'var(--success-500)'
                    : w.tone === 'warn' ? 'var(--warning-500)'
                    : 'var(--error-500)';
                  return (
                    <div key={t.hex} style={{
                      display: 'grid', gridTemplateColumns: '32px 1fr auto auto',
                      alignItems: 'center', gap: 10,
                      padding: '6px 10px', borderRadius: 8,
                      background: 'var(--bg-primary)',
                      border: '1px solid var(--border-tertiary)',
                    }}>
                      <div style={{ width: 22, height: 22, borderRadius: 4,
                        background: t.hex, border: '1px solid var(--border-secondary)' }} />
                      <div style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{t.name}</div>
                      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12,
                        fontVariantNumeric: 'tabular-nums', color: 'var(--text-tertiary)' }}>
                        {r.toFixed(2)}:1
                      </div>
                      <div style={{
                        background: tone, color: '#fff',
                        fontSize: 10, fontWeight: 700,
                        padding: '2px 6px', borderRadius: 999,
                        letterSpacing: '.04em',
                      }}>{w.label}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Live previews */}
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.08em',
                textTransform: 'uppercase', color: 'var(--text-quaternary)', marginBottom: 8 }}>
                Preview
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <div style={{
                  background: selected, color: '#fff',
                  padding: 14, borderRadius: 8,
                  border: '1px solid var(--border-secondary)',
                  fontSize: 14, fontWeight: 600, lineHeight: 1.3,
                }}>
                  Aa <span style={{ opacity: .7, fontWeight: 400, fontSize: 12 }}>on white text</span>
                </div>
                <div style={{
                  background: '#fff', color: selected,
                  padding: 14, borderRadius: 8,
                  border: '1px solid var(--border-secondary)',
                  fontSize: 14, fontWeight: 600, lineHeight: 1.3,
                }}>
                  Aa <span style={{ opacity: .7, fontWeight: 400, fontSize: 12 }}>on canvas</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.ColorToolProvider = ColorToolProvider;
window.ColorToolButton = ColorToolButton;
window.useColorTool = useColorTool;
