/* global React */
/* ============================================================
   Beem Card — photographic asset renderer.
   The earlier SVG implementation was rejected per the master
   prompt (docs/card-system-master-prompt.md §0.4). This file
   now ONLY composes the real PNG references; no synthetic art.

   Components:
     BeemPhotoCard   — single side (front | back), responsive
     BeemPhotoIso    — pre-rendered iso pair (front + back)
     BeemPhotoTwoUp  — two iso pairs side-by-side (Explorer + Legend
                       by default — i.e. one prepaid, one premium)
     BitidPass       — digital pass tile (NOT a card). Preserved.
   ============================================================ */

const { useState: bcUseState, useRef: bcUseRef, useEffect: bcUseEffect } = React;

/* The six tiers per master prompt §2 */
const BEEM_TIERS = {
  explorer: { name: 'Explorer', color: '#FF6A00', label: 'Neon Sunset',     pct: 15,  product: 'World Debit Prepaid' },
  expert:   { name: 'Expert',   color: '#FFF200', label: 'Electric Yellow', pct: 30,  product: 'World Debit Prepaid' },
  elite:    { name: 'Elite',    color: '#00FF9F', label: 'Laser Mint',      pct: 50,  product: 'World Elite' },
  legend:   { name: 'Legend',   color: '#BFFF00', label: 'Acid Lime',       pct: 70,  product: 'World Elite' },
  titan:    { name: 'Titan',    color: '#00E5FF', label: 'Cyber Cyan',      pct: 88,  product: 'World Elite' },
  icon:     { name: 'Icon',     color: '#BD00FF', label: 'Hyper Purple',    pct: 100, product: 'World Elite', pending: true },
};

/* Which tiers actually have art on disk today */
const HAS_FRONT = { explorer: false, expert: true, elite: true, legend: true, titan: true, icon: false };
const HAS_BACK  = { explorer: true,  expert: true, elite: true, legend: true, titan: true, icon: false };
const HAS_ISO   = { explorer: true,  expert: true, elite: true, legend: true, titan: true, icon: false };

/* ============================================================
   BeemPhotoCard — render a single side of one tier as PNG.
   Falls back to a placeholder card when art is missing.
   props:
     tier:       'explorer' | 'expert' | 'elite' | 'legend' | 'titan' | 'icon'
     side:       'front' | 'back'                           (default 'front')
     interactive:'flip' | 'static'                          (default 'flip')
     width:      number  (CSS px; height auto from ISO ratio)
   ============================================================ */
function BeemPhotoCard({
  tier = 'legend',
  side = 'front',
  interactive = 'flip',
  width = 360,
  className = '',
}) {
  const T = BEEM_TIERS[tier] || BEEM_TIERS.legend;
  const [flipped, setFlipped] = bcUseState(side === 'back');
  const flippable = interactive === 'flip';

  // ISO ID-1 ratio — taller than wide (1.586:1)
  const height = Math.round(width * 1.586);

  const onClick = () => { if (flippable) setFlipped(f => !f); };
  const onKey = (e) => {
    if (flippable && (e.key === 'Enter' || e.key === ' ')) {
      e.preventDefault();
      setFlipped(f => !f);
    }
  };

  return (
    <div
      className={`bpc ${flippable ? 'bpc-flippable' : ''} ${flipped ? 'is-flipped' : ''} bpc-tier-${tier} ${className}`}
      style={{ width, height }}
      onClick={onClick}
      onKeyDown={onKey}
      role={flippable ? 'button' : 'img'}
      tabIndex={flippable ? 0 : -1}
      aria-label={`Beem ${T.product} card · ${T.name} tier${flippable ? ' · click to flip' : ''}`}
    >
      <div className="bpc-flip">
        <div className="bpc-face bpc-front" aria-hidden={flipped}>
          <BPCSide tier={tier} side="front" />
        </div>
        <div className="bpc-face bpc-back" aria-hidden={!flipped}>
          <BPCSide tier={tier} side="back" />
        </div>
      </div>
    </div>
  );
}

/* One side of a card — either a photographic PNG, or a clearly-labeled
   placeholder when the asset is pending generation. */
function BPCSide({ tier, side }) {
  const T = BEEM_TIERS[tier];
  const has = side === 'front' ? HAS_FRONT[tier] : HAS_BACK[tier];

  if (has) {
    return (
      <img
        src={`assets/cards/front-back/${tier}-${side}.png`}
        alt={`Beem ${T.product} card · ${T.name} tier · ${side}`}
        className="bpc-img"
        loading="lazy"
        decoding="async"
      />
    );
  }

  // Placeholder — solid tier color w/ explicit "asset pending" label
  return (
    <div className="bpc-placeholder" style={{ background: T.color, color: T.color === '#FFF200' || T.color === '#00FF9F' || T.color === '#BFFF00' ? '#0A0A0B' : '#0A0A0B' }}>
      <div className="bpc-ph-corner bpc-ph-corner-tl">BEEM</div>
      <div className="bpc-ph-corner bpc-ph-corner-br">{side}</div>
      <div className="bpc-ph-mid">
        <div className="bpc-ph-tier">{T.name.toUpperCase()}</div>
        <div className="bpc-ph-color">{T.label}</div>
        <div className="bpc-ph-status">Photo asset pending</div>
        <div className="bpc-ph-hex">{T.color}</div>
      </div>
    </div>
  );
}

/* ============================================================
   BeemPhotoIso — the pre-rendered iso PNG showing front + back together.
   Use this anywhere a "hero" representation of a card is wanted.
   props:
     tier:    one of the six
     width:   px (height auto from ~1.32:1)
   ============================================================ */
function BeemPhotoIso({ tier = 'legend', width = 720, className = '' }) {
  const T = BEEM_TIERS[tier] || BEEM_TIERS.legend;
  const has = HAS_ISO[tier];
  const height = Math.round(width / 1.32);

  if (has) {
    return (
      <div className={`bpi ${className}`} style={{ width, height }}>
        <img
          src={`assets/cards/iso/${tier}.png`}
          alt={`Beem ${T.product} card · ${T.name} tier · isometric pair`}
          className="bpi-img"
          loading="lazy"
          decoding="async"
        />
      </div>
    );
  }

  // Placeholder iso pair — two stacked card silhouettes in tier color
  return (
    <div className={`bpi bpi-placeholder ${className}`} style={{ width, height }}>
      <div className="bpi-ph-card bpi-ph-back" style={{ background: T.color }} />
      <div className="bpi-ph-card bpi-ph-front" style={{ background: T.color }}>
        <div className="bpi-ph-label">
          <div className="bpi-ph-tier">{T.name}</div>
          <div className="bpi-ph-status">Iso render pending</div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   BeemPhotoTwoUp — convenience: two iso pairs.
   Defaults to one prepaid (Explorer) + one premium (Legend).
   ============================================================ */
function BeemPhotoTwoUp({ left = 'explorer', right = 'legend' }) {
  const L = BEEM_TIERS[left];
  const R = BEEM_TIERS[right];
  return (
    <div className="bpc-twoup">
      <div className="bpc-twoup-col">
        <BeemPhotoIso tier={left} width={620} />
        <div className="bpc-twoup-meta">
          <span className="bpc-twoup-product">{L.product}</span>
          <span className="bpc-twoup-tier" style={{ color: L.color }}>· {L.name}</span>
        </div>
      </div>
      <div className="bpc-twoup-col">
        <BeemPhotoIso tier={right} width={620} />
        <div className="bpc-twoup-meta">
          <span className="bpc-twoup-product">{R.product}</span>
          <span className="bpc-twoup-tier" style={{ color: R.color }}>· {R.name}</span>
        </div>
      </div>
    </div>
  );
}

/* Backwards-compatibility shim. Old call sites pass product='debit-prepaid' or
   product='world-elite'. Map those to canonical tiers. */
function BeemCard({ product, tier, interactive = 'flip', size = 'lg', className }) {
  // explicit tier wins
  let resolvedTier = tier;
  if (!resolvedTier) {
    if (product === 'world-elite') resolvedTier = 'legend';
    else resolvedTier = 'explorer';
  }
  const widthBySize = { lg: 380, md: 300, sm: 220 };
  const w = widthBySize[size] || widthBySize.lg;
  return (
    <BeemPhotoCard
      tier={resolvedTier}
      side="front"
      interactive={interactive === 'static' ? 'static' : 'flip'}
      width={w}
      className={className}
    />
  );
}

function BeemCardTwoUp() {
  // Old shim — Beem section now uses iso pair from one prepaid + one premium.
  return <BeemPhotoTwoUp left="explorer" right="legend" />;
}

/* ============================================================
   BitID glyph (kept inline so other components can reuse it)
   ============================================================ */
function BCGlyph({ size = 24, color = 'currentColor' }) {
  return (
    <svg width={Math.round(size * 1.1)} height={size} viewBox="0 0 1100 1000" aria-hidden="true">
      <g transform="translate(550 500) skewX(-13) translate(-550 -500)" fill={color}>
        <rect x="280" y="146" width="168" height="708" />
        <rect x="540" y="146" width="168" height="708" />
        <path d="M 708 150 A 350 350 0 0 1 708 850 L 708 682 A 182 182 0 0 0 708 318 Z" />
      </g>
    </svg>
  );
}

/* ============================================================
   BitidPass — digital pass tile (NOT a Mastercard).
   Used in the tier ladder. Updated to use the canonical six-tier color set.
   ============================================================ */
function BitidPass({ tier = 'expert', size = 'md' }) {
  // Accept both old uppercase tier names and new lowercase canonical ones.
  const tierKey = String(tier).toLowerCase();
  const remap = {
    verified: 'explorer', trusted: 'expert', anchored: 'elite',
    sovereign: 'legend',
  };
  const T = BEEM_TIERS[remap[tierKey] || tierKey] || BEEM_TIERS.expert;

  const fgIsDark = ['#FFF200', '#00FF9F', '#BFFF00', '#00E5FF'].includes(T.color);
  const fg = fgIsDark ? '#0A0A0B' : '#FAFAF7';

  const SZ = size === 'sm' ? { w: 280, h: 175 } : { w: 320, h: 200 };

  return (
    <div className="bp" style={{ width: SZ.w, height: SZ.h, background: T.color, color: fg }}
         role="img" aria-label={`${T.name} BitID pass`}>
      <div className="bp-grid" aria-hidden="true" style={{ color: fg }} />

      <div className="bp-top">
        <div className="bp-brand">
          <BCGlyph size={18} color={fg} />
          <span className="bp-wordmark">Beem</span>
        </div>
        <div className="bp-tier-meta">
          <div className="bp-k">TIER</div>
          <div className="bp-tier-name">{T.name.toUpperCase()}</div>
        </div>
      </div>

      <div className="bp-center">{T.name}</div>

      <div className="bp-bottom">
        <div>
          <div className="bp-k">IDENTITY</div>
          <div className="bp-v">bid:••••••3F7A</div>
        </div>
        <div>
          <div className="bp-k">SINCE</div>
          <div className="bp-v">2022</div>
        </div>
      </div>

      <div className="bp-prog">
        <div className="bp-prog-track" style={{ background: fg }} />
        <div className="bp-prog-fill"  style={{ background: fg, width: `${T.pct}%` }} />
        <div className="bp-prog-pct"   style={{ color: fg }}>{T.pct}%</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  BeemPhotoCard, BeemPhotoIso, BeemPhotoTwoUp,
  BeemCard, BeemCardTwoUp,
  BitidPass, BCGlyph,
  BEEM_TIERS,
});
