// Shared UI primitives for Reale 2027 app.

// Tipo-escudo: renderiza el badge oficial si existe, si no, monograma de placeholder.
// El monograma también aparece como fallback si la imagen falla al cargar.
function Crest({ team, size = 52 }) {
  const t = (window.TEAMS || {})[team] || { mono: team, primary: '#333', accent: '#fff' };
  const [imgErr, setImgErr] = React.useState(false);
  const hasBadge = t.badge && !imgErr;

  if (hasBadge) {
    return (
      <div
        aria-label={t.name}
        style={{
          width: size, height: size * 1.08,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}
      >
        <img
          src={t.badge}
          alt={t.name}
          onError={() => setImgErr(true)}
          style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', display: 'block' }}
        />
      </div>
    );
  }

  const fs = size * 0.28;
  return (
    <div
      aria-label={t.name}
      style={{
        width: size,
        height: size * 1.08,
        borderRadius: '10px 10px 14px 14px',
        clipPath: 'polygon(0 0, 100% 0, 100% 70%, 50% 100%, 0 70%)',
        background: `linear-gradient(180deg, ${t.primary} 0%, ${t.primary} 70%, ${shade(t.primary, -8)} 100%)`,
        color: t.accent,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        fontFamily: '"Archivo Black", "Oswald", system-ui',
        fontSize: fs,
        fontWeight: 900,
        letterSpacing: -0.5,
        textAlign: 'center',
        position: 'relative',
        boxShadow: 'inset 0 0 0 2px rgba(255,255,255,0.18), inset 0 -6px 10px rgba(0,0,0,0.18)',
        lineHeight: 1,
        flexShrink: 0,
      }}
    >
      <span style={{ transform: 'translateY(-2px)' }}>{t.mono}</span>
    </div>
  );
}

function shade(hex, pct) {
  const n = parseInt(hex.slice(1), 16);
  let r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  r = Math.max(0, Math.min(255, Math.round(r + (r * pct) / 100)));
  g = Math.max(0, Math.min(255, Math.round(g + (g * pct) / 100)));
  b = Math.max(0, Math.min(255, Math.round(b + (b * pct) / 100)));
  return '#' + ((r << 16) | (g << 8) | b).toString(16).padStart(6, '0');
}

// Mini crest para tabla de posiciones — img si hay badge, si no monograma.
function MiniCrest({ team, size = 22 }) {
  const t = (window.TEAMS || {})[team] || { mono: team, primary: '#333', accent: '#fff' };
  const [imgErr, setImgErr] = React.useState(false);

  if (t.badge && !imgErr) {
    return (
      <div style={{
        width: size, height: size,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <img
          src={t.badge}
          alt={t.name}
          onError={() => setImgErr(true)}
          style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain', display: 'block' }}
        />
      </div>
    );
  }

  return (
    <div style={{
      width: size, height: size, borderRadius: 4,
      background: t.primary, color: t.accent,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: '"Archivo Black", system-ui', fontSize: size * 0.42,
      fontWeight: 900, letterSpacing: -0.3, flexShrink: 0,
      boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.12)',
    }}>
      {t.mono.slice(0, 3)}
    </div>
  );
}

// Footer con redes sociales
function SocialFooter() {
  const color = '#0A2B63';
  const items = [
    {
      name: 'Instagram',
      href: 'https://www.instagram.com/jorgeareale/',
      svg: (
        <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="18" height="18" rx="5" />
          <circle cx="12" cy="12" r="4" />
          <circle cx="17.5" cy="6.5" r="0.9" fill={color} stroke="none" />
        </svg>
      ),
    },
    {
      name: 'TikTok',
      href: 'https://www.tiktok.com/@jorgerealeoficial',
      svg: (
        <svg viewBox="0 0 24 24" width="22" height="22" fill={color}>
          <path d="M16.5 3.5c.5 1.7 1.7 3 3.4 3.4v3c-1.4 0-2.7-.4-3.8-1.1v6.4c0 3.7-3 6.7-6.7 6.7S2.7 18.9 2.7 15.2c0-3.7 3-6.7 6.7-6.7.4 0 .8 0 1.1.1v3.1a3.7 3.7 0 1 0 2.6 3.5V3.5h3.4z" />
        </svg>
      ),
    },
    {
      name: 'YouTube',
      href: 'https://www.youtube.com/@jorgereale2027',
      svg: (
        <svg viewBox="0 0 24 24" width="24" height="24" fill={color}>
          <path d="M23.5 7.1s-.2-1.6-.9-2.3c-.9-1-1.9-1-2.3-1C16.7 3.5 12 3.5 12 3.5h0s-4.7 0-8.3.3c-.5.1-1.4.1-2.3 1-.7.7-.9 2.3-.9 2.3S.3 9 .3 10.9v1.7c0 1.9.2 3.7.2 3.7s.2 1.6.9 2.3c.9 1 2.1.9 2.6 1 1.9.2 8 .3 8 .3s4.7 0 8.3-.3c.5-.1 1.4-.1 2.3-1 .7-.7.9-2.3.9-2.3s.2-1.9.2-3.7v-1.7c0-1.9-.2-3.7-.2-3.7zM9.5 14.6V8.4l6.1 3.1-6.1 3.1z" />
        </svg>
      ),
    },
  ];

  return (
    <div style={{
      marginTop: 8,
      padding: '20px 16px 24px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
      borderTop: '1px dashed rgba(0,0,0,0.18)',
    }}>
      <div style={{
        fontSize: 11, fontWeight: 700, color: color,
        letterSpacing: 1.4, textTransform: 'uppercase',
      }}>
        Seguinos
      </div>
      <div style={{ display: 'flex', gap: 18 }}>
        {items.map(s => (
          <a
            key={s.name}
            href={s.href}
            target="_blank"
            rel="noopener noreferrer"
            aria-label={s.name}
            style={{
              width: 40, height: 40, borderRadius: '50%',
              background: '#fff',
              border: `1.5px solid ${color}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              textDecoration: 'none',
              transition: 'transform 0.15s',
            }}
            onMouseEnter={e => (e.currentTarget.style.transform = 'translateY(-2px)')}
            onMouseLeave={e => (e.currentTarget.style.transform = 'none')}
          >
            {s.svg}
          </a>
        ))}
      </div>
      <div style={{ fontSize: 10.5, color: 'rgba(0,0,0,0.45)', marginTop: 2, fontWeight: 500 }}>
        Jorge Reale · #DaleBoca
      </div>
    </div>
  );
}


function TeamPhotoBanner() {
  // Foto real del plantel. Si el archivo no existe, cae al placeholder vectorial.
  const [failed, setFailed] = React.useState(false);
  const src = 'assets/boca-team.jpg';

  if (!failed) {
    return (
      <div style={{
        margin: '4px 16px 0',
        borderRadius: 10,
        overflow: 'hidden',
        aspectRatio: '16 / 7',
        background: '#0A2457',
      }}>
        <img
          src={src}
          alt="Plantel Boca Juniors"
          onError={() => setFailed(true)}
          style={{
            width: '100%', height: '100%', objectFit: 'cover',
            display: 'block',
          }}
        />
      </div>
    );
  }

  // Fallback: placeholder vectorial (si falta assets/boca-team.jpg)
  return (
    <div style={{
      margin: '4px 16px 0',
      height: 130,
      borderRadius: 10,
      position: 'relative',
      overflow: 'hidden',
      background:
        'linear-gradient(180deg, rgba(245,176,30,0.85) 0%, rgba(245,176,30,0.55) 25%, transparent 28%),' +
        'radial-gradient(ellipse at 20% 75%, #0A2457 0 8%, transparent 9%),' +
        'radial-gradient(ellipse at 35% 70%, #0A2457 0 8%, transparent 9%),' +
        'radial-gradient(ellipse at 50% 75%, #0A2457 0 8%, transparent 9%),' +
        'radial-gradient(ellipse at 65% 70%, #0A2457 0 8%, transparent 9%),' +
        'radial-gradient(ellipse at 80% 75%, #0A2457 0 8%, transparent 9%),' +
        'radial-gradient(ellipse at 15% 100%, #0A2457 0 9%, transparent 10%),' +
        'radial-gradient(ellipse at 32% 100%, #0A2457 0 9%, transparent 10%),' +
        'radial-gradient(ellipse at 50% 100%, #0A2457 0 9%, transparent 10%),' +
        'radial-gradient(ellipse at 68% 100%, #0A2457 0 9%, transparent 10%),' +
        'radial-gradient(ellipse at 85% 100%, #0A2457 0 9%, transparent 10%),' +
        'linear-gradient(180deg, #1B5A2D 30%, #2E7D3F 75%, #1B5A2D 100%)',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: '30%',
        backgroundImage: 'repeating-linear-gradient(90deg, rgba(10,36,87,0.6) 0 6px, transparent 6px 14px)',
        opacity: 0.7,
      }} />
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(255,255,255,0.06) 0%, transparent 40%)',
      }} />
    </div>
  );
}


function NextMatchCard({ match, onClick }) {
  const home = window.TEAMS[match.home];
  const away = window.TEAMS[match.away];
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: '100%',
        appearance: 'none',
        border: '1.5px solid #F5B01E',
        background: 'linear-gradient(180deg, #0D2E6B 0%, #0A2457 100%)',
        borderRadius: 14,
        padding: '16px 14px',
        color: '#fff',
        textAlign: 'left',
        cursor: 'pointer',
        fontFamily: 'inherit',
        boxShadow: '0 6px 18px rgba(10, 36, 87, 0.22)',
      }}
    >
      <div style={{ textAlign: 'center', marginBottom: 10 }}>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.2, color: '#F5B01E', textTransform: 'uppercase' }}>
          {match.comp}
        </div>
        <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.72)', marginTop: 2 }}>
          {match.phase}{match.fase ? ` · ${match.fase}` : ''}
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 8 }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <Crest team={match.home} size={54} />
          <div style={{ fontSize: 10, fontWeight: 700, textAlign: 'center', lineHeight: 1.2, letterSpacing: 0.3, textTransform: 'uppercase' }}>
            {home.name.split(' ').map((w, i) => <div key={i}>{w}</div>)}
          </div>
        </div>
        <div style={{
          fontFamily: '"Archivo Black", system-ui',
          fontSize: 28, fontWeight: 900, color: 'rgba(255,255,255,0.32)',
          letterSpacing: 2,
        }}>VS</div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
          <Crest team={match.away} size={54} />
          <div style={{ fontSize: 10, fontWeight: 700, textAlign: 'center', lineHeight: 1.2, letterSpacing: 0.3, textTransform: 'uppercase' }}>
            {away.name.split(' ').map((w, i) => <div key={i}>{w}</div>)}
          </div>
        </div>
      </div>
      <div style={{ marginTop: 12, textAlign: 'center' }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: '#fff' }}>
          {match.date} · {match.time} hs
        </div>
        <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.65)', marginTop: 2 }}>
          {match.venue}
        </div>
      </div>
    </button>
  );
}

// Row de partido para Fixture / Resultados — copia exacta de la referencia
function MatchRow({ match, score, onClick }) {
  const home = window.TEAMS[match.home];
  const away = window.TEAMS[match.away];
  // En la referencia, todos los partidos muestran el mismo header.
  // Lo replicamos textualmente.
  const compLine = 'COPA DE LA LIGA PROFESIONAL';
  const phaseLine = '1st Phase - Semi Final';
  const dateLine = match.dateLong || `${match.date}${match.time ? ` - ${match.time} HS` : ''}`;
  const venueLine = match.venue || 'Estadio Mario Alberto Kempes';

  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: '100%',
        appearance: 'none',
        border: 'none',
        background: '#E9E9EB',
        borderRadius: 12,
        padding: '14px 14px',
        cursor: 'pointer',
        fontFamily: 'inherit',
        color: '#111',
        textAlign: 'left',
      }}
    >
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'auto 1fr auto',
        alignItems: 'center',
        gap: 10,
      }}>
        {/* Escudo izq + nombre */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, width: 70 }}>
          <Crest team={match.home} size={48} />
          <div style={{
            fontSize: 9, fontWeight: 700, textAlign: 'center', lineHeight: 1.15,
            letterSpacing: 0.3, textTransform: 'uppercase', color: '#111',
          }}>
            {(home.name).split(' ').map((w, i) => <div key={i}>{w}</div>)}
          </div>
        </div>

        {/* Centro */}
        <div style={{ textAlign: 'center', minWidth: 0 }}>
          <div style={{
            fontSize: 10, fontWeight: 700, letterSpacing: 0.3,
            textTransform: 'uppercase', color: '#0A1F47', lineHeight: 1.2,
          }}>
            {compLine}
          </div>
          <div style={{ fontSize: 9.5, color: 'rgba(0,0,0,0.6)', marginTop: 1 }}>
            {phaseLine}
          </div>
          {score ? (
            <div style={{
              fontFamily: '"Inter", system-ui',
              fontSize: 26, fontWeight: 800, marginTop: 6,
              letterSpacing: 1, color: '#111',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              lineHeight: 1,
            }}>
              <span>{score.h}</span>
              <span style={{ color: 'rgba(0,0,0,0.32)', fontSize: 13, fontWeight: 700, letterSpacing: 1 }}>VS</span>
              <span>{score.a}</span>
            </div>
          ) : (
            <div style={{
              fontFamily: '"Inter", system-ui',
              fontSize: 22, fontWeight: 800, marginTop: 6, lineHeight: 1,
              letterSpacing: 2, color: 'rgba(0,0,0,0.32)',
            }}>VS</div>
          )}
          <div style={{ fontSize: 10, fontWeight: 600, marginTop: 7, color: '#111' }}>
            {dateLine}
          </div>
          <div style={{ fontSize: 9.5, color: 'rgba(0,0,0,0.55)', marginTop: 1 }}>
            {venueLine}
          </div>
        </div>

        {/* Escudo der + nombre */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5, width: 70 }}>
          <Crest team={match.away} size={48} />
          <div style={{
            fontSize: 9, fontWeight: 700, textAlign: 'center', lineHeight: 1.15,
            letterSpacing: 0.3, textTransform: 'uppercase', color: '#111',
          }}>
            {(away.name).split(' ').map((w, i) => <div key={i}>{w}</div>)}
          </div>
        </div>
      </div>
    </button>
  );
}

// Pequeño placeholder para fotos de jugador — avatar monograma azul/dorado
// Si recibe `photo` URL (de la API), la renderiza con fallback al monograma.
function PlayerAvatar({ name, size = 32, photo }) {
  const initials = (name || '').split(' ').map(w => w[0] || '').join('').slice(0, 2).toUpperCase();
  const [failed, setFailed] = React.useState(false);
  const shared = {
    width: size, height: size, borderRadius: '50%',
    flexShrink: 0,
    boxShadow: 'inset 0 -2px 4px rgba(0,0,0,0.25), 0 0 0 1.5px #F5B01E',
  };
  if (photo && !failed) {
    return (
      <img
        src={photo}
        alt={name}
        onError={() => setFailed(true)}
        style={{ ...shared, objectFit: 'cover', background: '#0A2457' }}
      />
    );
  }
  return (
    <div style={{
      ...shared,
      background: 'linear-gradient(180deg, #13357A 0%, #0A2457 100%)',
      color: '#F5B01E',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: '"Archivo Black", system-ui', fontSize: size * 0.36,
      fontWeight: 900, letterSpacing: -0.3,
    }}>
      {initials}
    </div>
  );
}

// Card genérica de noticia (list item)
function NewsCard({ item, onClick, compact = false }) {
  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        width: '100%', appearance: 'none', border: 'none',
        background: 'transparent', padding: 0, cursor: 'pointer',
        display: 'flex', gap: 10, textAlign: 'left',
        fontFamily: 'inherit', color: '#111',
      }}
    >
      <div style={{
        width: compact ? 88 : 108,
        height: compact ? 78 : 88,
        borderRadius: 8,
        flexShrink: 0,
        background: 'linear-gradient(135deg, #0D2E6B 0%, #13357A 60%, #0A2457 100%)',
        position: 'relative',
        overflow: 'hidden',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'repeating-linear-gradient(45deg, rgba(245,176,30,0.08) 0 6px, transparent 6px 12px)',
        }} />
        <div style={{
          fontFamily: '"Archivo Black", system-ui',
          fontSize: 9, fontWeight: 900, color: '#F5B01E',
          letterSpacing: 1.2, textTransform: 'uppercase',
          background: 'rgba(10,36,87,0.6)', padding: '3px 6px', borderRadius: 3,
          position: 'relative', zIndex: 1,
        }}>
          {item.tag}
        </div>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 13, fontWeight: 800, lineHeight: 1.25,
          color: '#0A1F47', marginBottom: 4, letterSpacing: -0.2,
        }}>
          {item.title}
        </div>
        <div style={{
          fontSize: 10.5, lineHeight: 1.35,
          color: 'rgba(0,0,0,0.6)',
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
          overflow: 'hidden',
        }}>
          {item.excerpt}
        </div>
        <div style={{ fontSize: 9.5, color: 'rgba(0,0,0,0.4)', marginTop: 4, fontWeight: 500 }}>
          {item.time}
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { Crest, MiniCrest, NextMatchCard, MatchRow, PlayerAvatar, NewsCard, TeamPhotoBanner, SocialFooter, shade });
