/* Vista previa tipo landing con arrastre para encuadre (object-position) */

const LANDING_AVISO_CARD_IMAGE_HEIGHT = 156;
const LANDING_AVISO_MODAL_IMAGE_HEIGHT = 248;

const clampFocus = (v) => Math.max(5, Math.min(95, Number(v) || 50));

const avisoPriorityColor = (theme, priority) => {
  const tag = String(priority || 'normal').toLowerCase();
  const colors = { urgente: theme.urgent, alta: theme.warning, normal: theme.info };
  return colors[tag] || theme.primary;
};

const useFocusDrag = (imageUrl, focusX, focusY, onFocusChange) => {
  const frameRef = React.useRef(null);
  const dragRef = React.useRef(null);
  const fx = clampFocus(focusX);
  const fy = clampFocus(focusY);

  const handlers = {
    onPointerDown: (e) => {
      if (!imageUrl || !onFocusChange) return;
      dragRef.current = { startX: e.clientX, startY: e.clientY, startFx: fx, startFy: fy };
      e.currentTarget.style.cursor = 'grabbing';
      e.currentTarget.setPointerCapture(e.pointerId);
    },
    onPointerMove: (e) => {
      const d = dragRef.current;
      if (!d || !frameRef.current || !onFocusChange) return;
      const rect = frameRef.current.getBoundingClientRect();
      const nx = clampFocus(d.startFx - ((e.clientX - d.startX) / rect.width) * 120);
      const ny = clampFocus(d.startFy - ((e.clientY - d.startY) / rect.height) * 120);
      onFocusChange(nx, ny);
    },
    onPointerUp: (e) => {
      dragRef.current = null;
      e.currentTarget.style.cursor = imageUrl && onFocusChange ? 'grab' : 'default';
      try { e.currentTarget.releasePointerCapture(e.pointerId); } catch { /* ignore */ }
    },
  };

  return { frameRef, fx, fy, handlers };
};

const FocusDraggableCover = ({
  theme, imageUrl, focusX, focusY, onFocusChange, height, aspectRatio, maxWidth,
  style = {}, badge, cornerIcon, label,
}) => {
  const { frameRef, fx, fy, handlers } = useFocusDrag(imageUrl, focusX, focusY, onFocusChange);
  const frameStyle = {
    background: `linear-gradient(180deg, ${theme.primary}28, ${theme.bgInput})`,
    position: 'relative',
    overflow: 'hidden',
    cursor: imageUrl && onFocusChange ? 'grab' : 'default',
    touchAction: 'none',
    userSelect: 'none',
    width: '100%',
    maxWidth: maxWidth || '100%',
    margin: '0 auto',
    ...style,
  };
  if (height != null) frameStyle.height = height;
  else frameStyle.aspectRatio = aspectRatio || '4/3';

  return (
    <div>
      {label && (
        <div style={{
          fontSize: 10, fontWeight: 700, color: theme.textMute, marginBottom: 6,
          fontFamily: 'Inter, sans-serif', letterSpacing: 0.6, textTransform: 'uppercase',
        }}>
          {label}
        </div>
      )}
      <div
        ref={frameRef}
        {...handlers}
        onPointerCancel={handlers.onPointerUp}
        style={frameStyle}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt=""
            draggable={false}
            style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: `${fx}% ${fy}%`, pointerEvents: 'none',
            }}
          />
        ) : (
          <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
            <Icon name="image" size={40} color={theme.textMute} />
          </div>
        )}
        {badge}
        {cornerIcon}
      </div>
    </div>
  );
};

const LandingFocusPhotoFrame = ({
  theme, imageUrl, focusX, focusY, onFocusChange, aspectRatio = '4/3', maxWidth = 220,
  badge, cornerIcon,
}) => (
  <FocusDraggableCover
    theme={theme}
    imageUrl={imageUrl}
    focusX={focusX}
    focusY={focusY}
    onFocusChange={onFocusChange}
    aspectRatio={aspectRatio}
    maxWidth={maxWidth}
    badge={badge}
    cornerIcon={cornerIcon}
  />
);

/** Réplica de tarjeta + modal del landing para encuadrar imagen al publicar avisos */
const AnnouncementLandingPreview = ({
  theme, imageUrl, focusX, focusY, onFocusChange, title, body, priority,
}) => {
  const color = avisoPriorityColor(theme, priority);
  const tag = String(priority || 'normal').toLowerCase();
  const tagLabel = tag === 'urgente' ? 'Urgente' : tag === 'alta' ? 'Alta' : 'Normal';
  const displayTitle = (title || '').trim() || 'Título del aviso';
  const excerpt = (body || '').trim().slice(0, 120) || 'Descripción del aviso…';

  return (
    <div style={{ marginTop: 14, display: 'grid', gap: 16 }}>
      <p style={{
        margin: 0, fontSize: 12, color: theme.textDim, fontFamily: 'Inter, sans-serif', lineHeight: 1.5,
      }}>
        Vista previa del landing. <strong style={{ color: theme.text }}>Arrastra la imagen</strong> en cada recuadro para encuadrarla (mismo ajuste en tarjeta y detalle).
      </p>

      <div>
        <div style={{
          fontSize: 11, fontWeight: 700, color: theme.textMute, marginBottom: 8,
          fontFamily: 'Inter, sans-serif', letterSpacing: 0.6, textTransform: 'uppercase',
        }}>
          Sección Avisos — tarjeta
        </div>
        <div style={{
          borderRadius: 12, overflow: 'hidden', position: 'relative',
          border: `1px solid ${color}44`, boxShadow: `0 4px 20px ${color}22`,
          background: theme.bgCard || theme.bg,
          maxWidth: 420,
        }}>
          <div style={{
            position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.07,
            background: `repeating-linear-gradient(-45deg, ${color}, ${color} 2px, transparent 2px, transparent 12px)`,
          }} />
          <div style={{
            position: 'absolute', top: 12, right: -32, transform: 'rotate(45deg)', zIndex: 2,
            background: color, color: '#fff', fontSize: 9, fontWeight: 800, letterSpacing: 1,
            padding: '4px 36px', fontFamily: 'Inter, sans-serif', textTransform: 'uppercase',
          }}>Aviso</div>
          <FocusDraggableCover
            theme={theme}
            imageUrl={imageUrl}
            focusX={focusX}
            focusY={focusY}
            onFocusChange={onFocusChange}
            height={LANDING_AVISO_CARD_IMAGE_HEIGHT}
            style={{ margin: 0, borderRadius: 0 }}
          />
          <div style={{ padding: '14px 16px 16px', position: 'relative' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 10 }}>
              <div style={{
                width: 42, height: 42, borderRadius: 10, background: `${color}22`, color,
                display: 'grid', placeItems: 'center', border: `1px solid ${color}44`,
              }}>
                <Icon name={tag === 'urgente' ? 'warning' : 'megaphone'} size={20} />
              </div>
              <span style={{
                fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 6,
                background: `${color}22`, color, fontFamily: 'Inter, sans-serif', textTransform: 'capitalize',
              }}>{tagLabel}</span>
            </div>
            <h4 style={{
              fontFamily: 'Bebas Neue, sans-serif', fontSize: 22, letterSpacing: 1,
              color: theme.text, margin: '0 0 6px', lineHeight: 1.1, fontWeight: 400,
            }}>{displayTitle}</h4>
            <p style={{
              color: theme.textDim, fontSize: 13, lineHeight: 1.45, margin: 0,
              fontFamily: 'Inter, sans-serif',
              display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
            }}>{excerpt}</p>
          </div>
        </div>
      </div>

      <div>
        <div style={{
          fontSize: 11, fontWeight: 700, color: theme.textMute, marginBottom: 8,
          fontFamily: 'Inter, sans-serif', letterSpacing: 0.6, textTransform: 'uppercase',
        }}>
          Al abrir el aviso — encabezado
        </div>
        <div style={{
          borderRadius: 12, overflow: 'hidden', maxWidth: 420,
          border: `1px solid ${theme.border}`, background: '#111',
        }}>
          <div style={{ position: 'relative', height: LANDING_AVISO_MODAL_IMAGE_HEIGHT, overflow: 'hidden' }}>
            <div style={{
              position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.12, zIndex: 1,
              background: `repeating-linear-gradient(-45deg, ${color}, ${color} 2px, transparent 2px, transparent 14px)`,
            }} />
            <FocusDraggableCover
              theme={theme}
              imageUrl={imageUrl}
              focusX={focusX}
              focusY={focusY}
              onFocusChange={onFocusChange}
              height={LANDING_AVISO_MODAL_IMAGE_HEIGHT}
              style={{ margin: 0, borderRadius: 0, maxWidth: '100%' }}
              badge={(
                <div style={{
                  position: 'absolute', top: 12, left: 12, zIndex: 2, padding: '4px 12px', borderRadius: 6,
                  background: color, color: '#fff', fontSize: 10, fontWeight: 800, letterSpacing: 1.2,
                  fontFamily: 'Inter, sans-serif', textTransform: 'uppercase',
                  boxShadow: `0 0 16px ${color}88`, pointerEvents: 'none',
                }}>Aviso oficial</div>
              )}
            />
            <div style={{
              position: 'absolute', bottom: 12, left: 16, right: 16, zIndex: 2, pointerEvents: 'none',
            }}>
              <span style={{
                fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 6,
                background: 'rgba(0,0,0,0.5)', color: '#fff', fontFamily: 'Inter, sans-serif',
              }}>{tagLabel}</span>
              <h4 style={{
                fontFamily: 'Bebas Neue, sans-serif', fontSize: 28, letterSpacing: 1, color: '#fff',
                margin: '6px 0 0', fontWeight: 400, textShadow: '0 2px 12px rgba(0,0,0,0.5)',
              }}>{displayTitle}</h4>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, {
  clampFocus,
  LandingFocusPhotoFrame,
  FocusDraggableCover,
  AnnouncementLandingPreview,
  LANDING_AVISO_CARD_IMAGE_HEIGHT,
  LANDING_AVISO_MODAL_IMAGE_HEIGHT,
  avisoPriorityColor,
});
