const { color: C, font: F, r: R, shadow: SH } = window.RAYA;

const CAT_TINT_DEFAULT = { soft: C.ink05, strong: C.ink };

function RayaLogo({ size = 26, color = C.brand, tagline = true, lang = 'en' }) {
  const isAr = lang === 'ar';
  const onDark = (color === '#FFFFFF' || color === 'white' || color === C.white);
  const bgFile = onDark ? 'blue' : 'white';

  if (isAr) {
    const src = tagline
      ? `raya/assets/ar-${bgFile}.png`
      : `raya/assets/ar-${bgFile}-mark.png`;
    return (
      <img src={src} alt="راية" style={{
        height: size * (tagline ? 2.4 : 1.5),
        width: 'auto',
        display: 'block',
        objectFit: 'contain',
      }}/>
    );
  }

  return (
    <div style={{ display: 'inline-flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1, gap: size * 0.22 }}>
      <img src={`raya/assets/en-${bgFile}-mark.png`} alt="Raya" style={{
        height: size * 1.4,
        width: 'auto',
        display: 'block',
        objectFit: 'contain',
      }}/>
      {tagline && (
        <div style={{
          fontFamily: F.bodyEn,
          fontSize: size * 0.38, fontWeight: 500,
          color, letterSpacing: 0.2,
          whiteSpace: 'nowrap',
        }}>Real estate investment</div>
      )}
    </div>
  );
}

function RButton({ children, variant = 'primary', size = 'md', full, onClick, lang = 'en', icon, disabled, type = 'button' }) {
  const paddings = { sm: '10px 16px', md: '14px 20px', lg: '16px 26px' };
  const fontsizes = { sm: 13, md: 15, lg: 16 };
  const variants = {
    primary: { bg: C.ink, fg: C.paper, border: 'none' },
    brand:   { bg: C.brand, fg: C.white, border: 'none' },
    outline: { bg: 'transparent', fg: C.ink, border: `1px solid ${C.ink20}` },
    ghost:   { bg: 'transparent', fg: C.ink, border: 'none' },
  };
  const v = variants[variant];
  return (
    <button
      onClick={onClick}
      type={type}
      disabled={disabled}
      className="raya-btn"
      style={{
        width: full ? '100%' : undefined,
        padding: paddings[size],
        borderRadius: R.pill,
        background: v.bg, color: v.fg, border: v.border,
        fontFamily: lang === 'ar' ? F.bodyAr : F.bodyEn,
        fontSize: fontsizes[size], fontWeight: 600,
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.5 : 1,
        display: 'inline-flex',
        alignItems: 'center', justifyContent: 'center', gap: 8,
        letterSpacing: lang === 'en' ? 0.2 : 0,
      }}
    >
      {icon}
      {children}
    </button>
  );
}

function RImage({ tone = 'sand', image, alt = '', label, children, style = {}, rounded = R.md }) {
  const bg = window.RAYA_DATA.placeholderImg(tone);
  const [loaded, setLoaded] = React.useState(false);
  const [failed, setFailed] = React.useState(false);
  const showImage = image && !failed;
  return (
    <div style={{
      background: bg, borderRadius: rounded,
      position: 'relative', overflow: 'hidden',
      ...style,
    }}>
      {showImage && (
        <img
          src={image}
          alt={alt}
          loading="lazy"
          onLoad={() => setLoaded(true)}
          onError={() => setFailed(true)}
          style={{
            position: 'absolute', inset: 0,
            width: '100%', height: '100%',
            objectFit: 'cover',
            opacity: loaded ? 1 : 0,
            transition: 'opacity 0.35s ease',
          }}
        />
      )}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(120% 60% at 50% 0%, rgba(255,255,255,0.18), transparent), radial-gradient(120% 80% at 50% 120%, rgba(0,0,0,0.22), transparent)',
        pointerEvents: 'none',
      }}/>
      {label && (
        <div style={{
          position: 'absolute', bottom: 10, left: 10,
          fontFamily: F.mono, fontSize: 9, color: 'rgba(255,255,255,0.9)',
          letterSpacing: 1, textTransform: 'uppercase',
          background: 'rgba(0,0,0,0.35)', padding: '3px 7px', borderRadius: 4,
          backdropFilter: 'blur(6px)',
        }}>{label}</div>
      )}
      {children}
    </div>
  );
}

function RatingChip({ rating, reviews, compact, lang = 'en' }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 3,
      fontFamily: lang === 'ar' ? F.bodyAr : F.bodyEn,
      fontSize: compact ? 11 : 13, fontWeight: 600, color: C.ink,
    }}>
      <RIcon name="starFill" size={compact ? 11 : 13} color={C.gold} />
      {rating}
      {reviews != null && !compact && (
        <span style={{ color: C.ink40, fontWeight: 400, marginLeft: 2 }}>({reviews})</span>
      )}
    </span>
  );
}

function HeartBtn({ active, onClick, size = 36, light }) {
  const [pulse, setPulse] = React.useState(false);
  return (
    <button
      onClick={(e) => { e.stopPropagation(); onClick?.(); setPulse(true); setTimeout(() => setPulse(false), 500); }}
      className="raya-btn"
      style={{
        width: size, height: size, borderRadius: R.pill, border: 'none',
        background: light ? 'rgba(255,255,255,0.95)' : C.white,
        boxShadow: '0 2px 8px rgba(10,22,40,0.12)',
        display: 'grid', placeItems: 'center', cursor: 'pointer',
      }}
    >
      <span className={pulse ? 'raya-heart-pulse' : ''} style={{ display: 'grid', placeItems: 'center' }}>
        <RIcon name={active ? 'heartFill' : 'heart'} size={size * 0.5} color={active ? C.danger : C.ink60} sw={1.9} />
      </span>
    </button>
  );
}

function CategoryTile({ cat, active, onClick, lang = 'en' }) {
  const tint = CAT_TINT_DEFAULT;
  return (
    <button
      onClick={onClick}
      className="raya-tap"
      style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
        padding: '10px 4px 6px', background: 'transparent',
        border: 'none', cursor: 'pointer', minWidth: 62,
        borderBottom: active ? `2px solid ${C.ink}` : '2px solid transparent',
      }}
    >
      <div style={{
        width: 54, height: 54, borderRadius: R.md,
        background: active ? tint.strong : tint.soft,
        display: 'grid', placeItems: 'center',
        boxShadow: active
          ? `0 2px 6px ${tint.strong}33, 0 8px 20px ${tint.strong}26`
          : '0 1px 2px rgba(10,22,40,0.03)',
        transition: 'background 0.2s, box-shadow 0.2s, transform 0.2s',
        transform: active ? 'translateY(-1px)' : 'translateY(0)',
      }}>
        <RIcon name={cat.icon} size={22} color={active ? C.paper : tint.strong} sw={1.7} />
      </div>
      <span style={{
        fontFamily: lang === 'ar' ? F.bodyAr : F.bodyEn,
        fontSize: 11, fontWeight: active ? 600 : 500,
        color: active ? C.ink : C.ink60, whiteSpace: 'nowrap',
        letterSpacing: lang === 'ar' ? 0 : -0.1,
      }}>
        {lang === 'ar' ? cat.ar : cat.en}
      </span>
    </button>
  );
}

function SectionHeader({ title, action, onAction, lang = 'en' }) {
  const isAr = lang === 'ar';
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
      padding: '0 20px', marginBottom: 12,
      flexDirection: isAr ? 'row-reverse' : 'row',
    }}>
      <h2 style={{
        margin: 0,
        fontFamily: isAr ? F.displayAr : F.displayEn,
        fontSize: isAr ? 20 : 22, fontWeight: isAr ? 700 : 500, color: C.ink,
        letterSpacing: isAr ? 0 : -0.4,
        lineHeight: isAr ? 1.3 : 1.2,
      }}>{title}</h2>
      {action && (
        <button onClick={onAction} className="raya-btn" style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: isAr ? F.bodyAr : F.bodyEn,
          fontSize: 13, color: C.brand, fontWeight: 500,
          display: 'inline-flex', alignItems: 'center', gap: 3, padding: 0,
        }}>
          {action}
          <RIcon name={isAr ? 'chevronLeft' : 'chevronRight'} size={14} color={C.brand} />
        </button>
      )}
    </div>
  );
}

Object.assign(window, { RayaLogo, RButton, RImage, RatingChip, HeartBtn, CategoryTile, SectionHeader });
