// ds.jsx — Mountaineer design system. Tenant-aware: the `WVU` export reflects
// the currently active tenant. Screens can keep using the name `WVU` — it's
// a live object whose color/identity values are synced when the tenant changes.

// The shape every screen consumes. We MUTATE these existing object references
// when the tenant switches, so no component needs to re-import anything.
const WVU = {
  id: 'wvu',
  name: 'West Virginia',
  full: 'West Virginia University',
  nick: 'Mountaineers',
  city: 'Morgantown, WV',
  conf: 'Big 12',

  // Primary palette — filled in by applyTenant()
  gold:     '#EAAA00',
  goldDim:  '#B88600',
  goldLite: '#F6C95C',
  blue:     '#002855',
  blueDim:  '#001A38',
  blueLite: '#1B4C89',

  // Warm surfaces — stay constant
  ink:      '#14110C',
  ink2:     '#1E1A13',
  ink3:     '#2A241A',
  cream:    '#F5ECD9',
  creamDim: '#C9BFA8',
  paper:    '#FAF5E8',

  // Lines
  line:      'rgba(245,236,217,0.08)',
  lineWarm:  'rgba(234,170,0,0.14)',
  lineBold:  'rgba(245,236,217,0.18)',

  // Shadows
  sh1: '0 1px 2px rgba(0,0,0,0.4), 0 4px 14px rgba(0,0,0,0.25)',
  sh2: '0 6px 18px rgba(0,0,0,0.38), 0 18px 48px rgba(0,0,0,0.32)',
  shGlow: '0 0 0 1px rgba(234,170,0,0.3), 0 10px 36px rgba(234,170,0,0.22)',
};

const DS = {
  sans:    '"Geist", -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif',
  display: '"Geist", -apple-system, BlinkMacSystemFont, "SF Pro Display", system-ui, sans-serif',
  mono:    '"Geist Mono", "SF Mono", ui-monospace, monospace',
  r: { xs: 6, sm: 10, md: 14, lg: 20, xl: 28, pill: 9999 },
};

// Convert a hex to an rgba() string with alpha
function hexA(hex, a) {
  const h = hex.replace('#', '');
  const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16);
  const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
  return `rgba(${r},${g},${b},${a})`;
}

// Apply a tenant's palette + identity to the live WVU object. All existing
// screens read from WVU.gold, WVU.blue etc — so mutating in place is enough
// to re-skin the whole app on next render.
function applyTenantToDS(tenant) {
  const c = tenant.colors;
  WVU.id = tenant.id;
  WVU.name = tenant.name;
  WVU.full = tenant.full;
  WVU.nick = tenant.nick;
  WVU.city = tenant.city;
  WVU.conf = tenant.conf;

  WVU.gold     = c.primary;
  WVU.goldDim  = c.primaryDim;
  WVU.goldLite = c.primaryLite;
  WVU.blue     = c.secondary;
  WVU.blueDim  = c.secondaryDim;
  WVU.blueLite = c.secondaryLite;

  WVU.lineWarm = hexA(c.primary, 0.14);
  WVU.shGlow   = `0 0 0 1px ${hexA(c.primary, 0.3)}, 0 10px 36px ${hexA(c.primary, 0.22)}`;
}

// Flying mark — tenant-agnostic geometric
function FlyingWV({ size = 28, color, bg }) {
  const s = size;
  const stroke = color || WVU.gold;
  return (
    <div style={{
      width: s, height: s, borderRadius: s * 0.2,
      background: bg || 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flexShrink: 0,
    }}>
      <svg width={s * 0.78} height={s * 0.58} viewBox="0 0 32 22">
        <path d="M2 2 L7 20 L13 6 L16 20 L19 6 L25 20 L30 2" fill="none"
              stroke={stroke} strokeWidth="2.6" strokeLinecap="square" strokeLinejoin="miter"/>
      </svg>
    </div>
  );
}

// Wordmark — reads current tenant's wordmark + product name
function WVUMark({ size = 15, color = WVU.cream }) {
  const tenant = (window.TENANTS && window.TENANTS[WVU.id]) || null;
  const wordmark = tenant?.wordmark || 'MOUNTAINEER';
  const product  = tenant?.productName || 'Mountaineer 360°';
  // product label strips the wordmark prefix if it starts with one
  const productSuffix = product.replace(new RegExp(`^${wordmark}\\s*`, 'i'), '').trim() || '360°';
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 7,
      fontFamily: DS.sans, fontWeight: 700, fontSize: size,
      letterSpacing: '0.18em', color,
    }}>
      <FlyingWV size={size + 4} color={WVU.gold} />
      <span>{wordmark}</span>
      <span style={{ opacity: 0.5, fontWeight: 400, letterSpacing: '0.08em' }}>{productSuffix}</span>
    </div>
  );
}

// Tenant-aware Unsplash imagery library — keyed by tenant id + variant.
// Each value is a curated Unsplash photo URL that fits the brand tone.
// Pulling from Unsplash means real photos with no licensing risk.
// Photo IDs verified American football / sport context (Unsplash)
// FB stadium = sYY1FlMHOV4 (Anders K-J · FedEx Field), GBPTdjRhK9s (DiMatteo · Cleveland), Xy-F5GptgR8 (Burden · Michigan field)
const TENANT_IMAGES = {
  wvu: {
    stadium:  'https://images.unsplash.com/photo-1566577739112-5180d4bf9390?auto=format&fit=crop&w=900&q=70', // football stadium night
    court:    'https://images.unsplash.com/photo-1546519638-68e109498ffc?auto=format&fit=crop&w=900&q=70',   // basketball arena
    dusk:     'https://images.unsplash.com/photo-1495555687398-3f50d6e79e1e?auto=format&fit=crop&w=900&q=70', // football stadium dusk
    dawn:     'https://images.unsplash.com/photo-1574629810360-7efbbe195018?auto=format&fit=crop&w=900&q=70',
    crowd:    'https://images.unsplash.com/photo-1577223625816-7546f13df25d?auto=format&fit=crop&w=900&q=70', // stadium crowd
    field:    'https://images.unsplash.com/photo-1508098682722-e99c43a406b2?auto=format&fit=crop&w=900&q=70', // football field
    portrait: 'https://images.unsplash.com/photo-1622547748225-3fc4abd2cca0?auto=format&fit=crop&w=600&q=70', // football player
    locker:   'https://images.unsplash.com/photo-1543326727-cf6c39e8f84c?auto=format&fit=crop&w=900&q=70',
  },
  utah: {
    stadium:  'https://images.unsplash.com/photo-1518091043644-c1d4457512c6?auto=format&fit=crop&w=900&q=70', // stadium
    court:    'https://images.unsplash.com/photo-1505666287802-931dc83948e9?auto=format&fit=crop&w=900&q=70',
    dusk:     'https://images.unsplash.com/photo-1495555687398-3f50d6e79e1e?auto=format&fit=crop&w=900&q=70',
    dawn:     'https://images.unsplash.com/photo-1577223625816-7546f13df25d?auto=format&fit=crop&w=900&q=70',
    crowd:    'https://images.unsplash.com/photo-1566577739112-5180d4bf9390?auto=format&fit=crop&w=900&q=70',
    field:    'https://images.unsplash.com/photo-1508098682722-e99c43a406b2?auto=format&fit=crop&w=900&q=70',
    portrait: 'https://images.unsplash.com/photo-1551958219-acbc608c6377?auto=format&fit=crop&w=600&q=70', // football player
    locker:   'https://images.unsplash.com/photo-1543326727-cf6c39e8f84c?auto=format&fit=crop&w=900&q=70',
  },
  osu: {
    stadium:  'https://images.unsplash.com/photo-1495555687398-3f50d6e79e1e?auto=format&fit=crop&w=900&q=70',
    court:    'https://images.unsplash.com/photo-1518611012118-696072aa579a?auto=format&fit=crop&w=900&q=70',
    dusk:     'https://images.unsplash.com/photo-1577223625816-7546f13df25d?auto=format&fit=crop&w=900&q=70',
    dawn:     'https://images.unsplash.com/photo-1518091043644-c1d4457512c6?auto=format&fit=crop&w=900&q=70',
    crowd:    'https://images.unsplash.com/photo-1566577739112-5180d4bf9390?auto=format&fit=crop&w=900&q=70',
    field:    'https://images.unsplash.com/photo-1508098682722-e99c43a406b2?auto=format&fit=crop&w=900&q=70',
    portrait: 'https://images.unsplash.com/photo-1599566150163-29194dcaad36?auto=format&fit=crop&w=600&q=70', // football helmet
    locker:   'https://images.unsplash.com/photo-1543326727-cf6c39e8f84c?auto=format&fit=crop&w=900&q=70',
  },
};

function tenantPhoto(variant) {
  const lib = TENANT_IMAGES[WVU.id] || TENANT_IMAGES.wvu;
  return lib[variant] || lib.stadium;
}

function WarmHero({ caption, h = 220, variant = 'stadium', photo, dim = 0.55 }) {
  const photoUrl = photo || tenantPhoto(variant);
  const scenes = {
    stadium: `linear-gradient(180deg, transparent 30%, rgba(0,0,0,${dim}))`,
    court:   `linear-gradient(180deg, transparent 30%, rgba(0,0,0,${dim}))`,
    dusk:    `linear-gradient(180deg, transparent 30%, rgba(0,0,0,${dim}))`,
    dawn:    `linear-gradient(180deg, transparent 30%, rgba(0,0,0,${dim}))`,
  };
  // Tenant-tinted overlay so photo always feels "in the brand"
  const tint = `linear-gradient(160deg, ${hexA(WVU.blue, 0.35)}, transparent 55%, ${hexA(WVU.gold, 0.15)})`;
  return (
    <div style={{
      width: '100%', height: h,
      backgroundColor: WVU.ink,
      backgroundImage: `${scenes[variant] || scenes.stadium}, ${tint}, url("${photoUrl}")`,
      backgroundSize: 'cover, cover, cover',
      backgroundPosition: 'center, center, center',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `repeating-linear-gradient(-20deg, rgba(245,236,217,0.015) 0 1px, transparent 1px 8px)`,
        mixBlendMode: 'overlay', opacity: 0.6,
      }} />
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: '55%',
        background: 'linear-gradient(180deg, transparent, rgba(0,0,0,0.65))',
      }} />
      {caption && (
        <div style={{
          position: 'absolute', bottom: 12, left: 14,
          fontFamily: DS.sans, fontSize: 10, fontWeight: 600, color: 'rgba(245,236,217,0.95)',
          letterSpacing: '0.12em', textTransform: 'uppercase',
          padding: '3px 8px', borderRadius: 3,
          background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(6px)',
        }}>{caption}</div>
      )}
    </div>
  );
}

function WarmTile({ label, h = 120, w = '100%', variant = 'gold', photo, style = {} }) {
  // Map variants to tenant photos (variant is treated as a hint, not strict)
  const variantMap = { gold: 'field', blue: 'court', ember: 'dusk' };
  const photoUrl = photo || tenantPhoto(variantMap[variant] || 'field');
  // Tenant-tinted overlay
  const tints = {
    gold:  `linear-gradient(160deg, ${hexA(WVU.gold, 0.35)}, ${hexA(WVU.blue, 0.45)} 90%)`,
    blue:  `linear-gradient(160deg, ${hexA(WVU.blue, 0.55)}, ${hexA(WVU.gold, 0.18)} 90%)`,
    ember: `linear-gradient(160deg, ${hexA(WVU.gold, 0.18)}, rgba(0,0,0,0.55) 90%)`,
  };
  return (
    <div style={{
      width: w, height: h,
      backgroundColor: WVU.ink,
      backgroundImage: `${tints[variant] || tints.gold}, url("${photoUrl}")`,
      backgroundSize: 'cover, cover',
      backgroundPosition: 'center, center',
      position: 'relative', overflow: 'hidden',
      ...style,
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        background: `repeating-linear-gradient(-28deg, rgba(245,236,217,0.02) 0 1px, transparent 1px 9px)`,
      }} />
      {label && (
        <div style={{
          position: 'absolute', bottom: 8, left: 10,
          fontFamily: DS.sans, fontSize: 10, fontWeight: 600, letterSpacing: '0.12em',
          color: 'rgba(245,236,217,0.95)', textTransform: 'uppercase',
          textShadow: '0 1px 3px rgba(0,0,0,0.7)',
        }}>{label}</div>
      )}
    </div>
  );
}

const mountStyleId = '__mountaineer_styles';
if (!document.getElementById(mountStyleId)) {
  const el = document.createElement('style');
  el.id = mountStyleId;
  el.textContent = `
    @keyframes mtnFade { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
    @keyframes mtnPulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
    @keyframes mtnShimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; } }
    .mtn-scrollbar::-webkit-scrollbar { width: 0; height: 0; }
  `;
  document.head.appendChild(el);
}

Object.assign(window, { WVU, DS, FlyingWV, WVUMark, WarmHero, WarmTile, hexA, applyTenantToDS });
