// poster.jsx — Poster artifact with map-dominant layout and minimal text.
// The pin (heart / home / pin) is rendered as a screen-space overlay over
// the map area and is draggable so the user can place it exactly on their
// house. Pin is always present — anti-piracy by construction.

const { useRef: usePR, useState: usePS } = React;

function Poster({
  design, setDesign, width = 360, withWatermark = true, frameId = 'white',
  draggable = false, interactive = true,
}) {
  const style = (window.MAP_STYLES || []).find(s => s.id === design.style) || window.MAP_STYLES[0];
  const themeClass = `theme-${style.posterTheme}`;
  const pc = design.pinCoords || design.coords;
  const coords = window.formatCoords(pc[0], pc[1]);
  const headlineSize = Math.round(width * 0.066);
  const pinSize = Math.max(18, Math.round(width * 0.082));
  // Poster shape = aspect ratio of the chosen print size (WYSIWYG).
  const posterAspect = window.sizeAspectCss(design.size || '30x40');

  const mapAreaRef = usePR(null);
  const mapObjRef = usePR(null);
  const pinElRef = usePR(null);
  // Latest values, readable from imperative map-event handlers (no stale closures).
  const pcRef = usePR(null);
  pcRef.current = design.pinCoords || design.coords;
  const placedRef = usePR(false);
  placedRef.current = !!design.pinPlaced;

  // Position the pin. Once "placed" (dragged, or exact coords typed) the pin is
  // GLUED to its geographic location — it projects to the right spot on every
  // zoom/pan, so it stays on the building. Before that it sits at the map centre
  // and follows it (so you can pan/search to find your area).
  function placePin() {
    const el = pinElRef.current, map = mapObjRef.current;
    if (!el) return;
    if (!placedRef.current || !map) { el.style.left = '50%'; el.style.top = '50%'; return; }
    try {
      const p = map.project(pcRef.current);
      const area = mapAreaRef.current;
      const W = area ? area.clientWidth : 0, H = area ? area.clientHeight : 0;
      // Clamp to the map bounds so the pin sticks to the edge instead of vanishing.
      el.style.left = Math.max(0, Math.min(W, p.x)) + 'px';
      el.style.top = Math.max(0, Math.min(H, p.y)) + 'px';
    } catch (e) {}
  }
  // Re-place after every render (covers external coord/search changes).
  React.useEffect(() => { placePin(); });

  function onPinDown(e) {
    if (!draggable || !setDesign) return;
    e.preventDefault(); e.stopPropagation();
    const map = mapObjRef.current;
    const rect = mapAreaRef.current.getBoundingClientRect();
    let coords = pcRef.current;
    const move = (ev) => {
      const p = ev.touches ? ev.touches[0] : ev;
      const x = Math.max(0, Math.min(rect.width, p.clientX - rect.left));
      const y = Math.max(0, Math.min(rect.height, p.clientY - rect.top));
      if (pinElRef.current) { pinElRef.current.style.left = x + 'px'; pinElRef.current.style.top = y + 'px'; }
      if (map) { try { const ll = map.unproject([x, y]); coords = [ll.lng, ll.lat]; pcRef.current = coords; } catch (er) {} }
    };
    const up = () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseup', up);
      window.removeEventListener('touchmove', move);
      window.removeEventListener('touchend', up);
      // From now on the pin is fixed to this exact geographic point.
      setDesign(d => ({ ...d, pinPlaced: true, pinCoords: coords }));
    };
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move, { passive: false });
    window.addEventListener('touchend', up);
  }

  return (
    <div className={`poster-frame-wrap frame-${frameId}`}>
      <div
        className={`poster ${themeClass}`}
        style={{
          '--poster-width': `${width}px`,
          '--p-headline-size': `${headlineSize}px`,
          aspectRatio: posterAspect,
        }}
      >
        <div className="poster-map-area" ref={mapAreaRef}>
          <MapPreview
            styleId={design.style}
            center={design.coords}
            zoom={design.zoom}
            is3D={style.is3D}
            pitch={design.pitch}
            bearing={design.bearing}
            interactive={interactive}
            onMap={m => {
              mapObjRef.current = m;
              m.on('move', placePin);
              m.on('load', placePin);
              m.on('idle', placePin);
              placePin();
            }}
            onMoveEnd={interactive && setDesign ? (s) => {
              // A placed pin stays glued to its coordinate; otherwise it follows the centre.
              setDesign(d => d.pinPlaced
                ? { ...d, coords: s.center, zoom: s.zoom }
                : { ...d, coords: s.center, zoom: s.zoom, pinCoords: s.center });
            } : null}
          />

          {/* Pin — locked when not draggable, otherwise grab/drag */}
          <div
            className="poster-pin"
            ref={pinElRef}
            style={{
              cursor: draggable ? 'grab' : 'default',
              pointerEvents: draggable ? 'auto' : 'none',
            }}
            onMouseDown={onPinDown}
            onTouchStart={onPinDown}
          >
            <PinSvg type={design.pinIcon || 'pin'} color={design.pinColor || '#c9694e'} size={pinSize} />
          </div>

          {withWatermark && (
            <div className="poster-watermark"><span>WISMAPS</span></div>
          )}
        </div>

        <div className="poster-labels">
          <h1 className={`poster-headline ${design.headlineCase === 'normal' ? 'case-normal' : ''}`}>
            {design.headline || 'Tu Mapa'}
          </h1>

          {design.showCoords && (
            <div className="poster-coords">
              <span>{coords.lat}</span>
              <span className="poster-coords-sep">·</span>
              <span>{coords.lng}</span>
            </div>
          )}

          {design.tagline && (
            <div className="poster-tagline">— {design.tagline} —</div>
          )}
        </div>

        <div className="poster-brand">WISMAPS</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Pin icons — 3 options
function PinSvg({ type = 'pin', color = '#c9694e', size = 32 }) {
  const h = Math.round(size * 1.28);
  if (type === 'heart') {
    const hs = Math.round(size * 1.28); // match the visual footprint of pin/home
    return (
      <svg width={hs} height={hs} viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
        <path d="M16 28 C 3 19, 0 11, 4.5 6.5 C 9 2, 14 5, 16 9 C 18 5, 23 2, 27.5 6.5 C 32 11, 29 19, 16 28 Z" fill={color}/>
        <circle cx="16" cy="13" r="2.4" fill="#fff" opacity="0.95"/>
      </svg>
    );
  }
  if (type === 'home') {
    return (
      <svg width={size} height={h} viewBox="0 0 32 40" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
        <path d="M16 0 C 7 0, 0 7, 0 16 C 0 26, 16 40, 16 40 C 16 40, 32 26, 32 16 C 32 7, 25 0, 16 0 Z" fill={color}/>
        <path d="M9 19 L16 12 L23 19 L23 25 L19 25 L19 21 L13 21 L13 25 L9 25 Z" fill="#fff"/>
      </svg>
    );
  }
  // default pin
  return (
    <svg width={size} height={h} viewBox="0 0 28 36" xmlns="http://www.w3.org/2000/svg" style={{ display: 'block' }}>
      <path
        d="M14 0 C 6.27 0 0 6.27 0 14 c 0 9.5 12.6 21.1 13.2 21.6 c 0.45 0.45 1.15 0.45 1.6 0 C 15.4 35.1 28 23.5 28 14 28 6.27 21.73 0 14 0 Z"
        fill={color}
      />
      <circle cx="14" cy="14" r="5" fill="#ffffff" />
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────────────────
// Photorealistic wall mockup — based on user reference (plant + wood shelf)
function WallMockup({ design, frameId = 'white' }) {
  return (
    <div className="wall-photo-scene">
      {/* wall */}
      <div className="wall-photo-wall" />
      {/* shelf */}
      <div className="wall-photo-shelf" />
      {/* poster */}
      <div className="wall-photo-poster">
        <Poster design={design} width={240} frameId={frameId} withWatermark={true} />
      </div>
      {/* plant */}
      <svg className="wall-photo-plant" viewBox="0 0 220 320" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
        {/* shadow under vase */}
        <ellipse cx="105" cy="300" rx="70" ry="10" fill="rgba(0,0,0,0.25)" />
        {/* glass vase */}
        <defs>
          <linearGradient id="glass" x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%"  stopColor="#fff" stopOpacity="0.85"/>
            <stop offset="35%" stopColor="#eef6f3" stopOpacity="0.55"/>
            <stop offset="65%" stopColor="#cad9d2" stopOpacity="0.45"/>
            <stop offset="100%" stopColor="#fff" stopOpacity="0.85"/>
          </linearGradient>
          <linearGradient id="water" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"  stopColor="#e6e0c0" stopOpacity="0.7"/>
            <stop offset="100%" stopColor="#bcb487" stopOpacity="0.8"/>
          </linearGradient>
          <linearGradient id="leafDark" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#3a5a3e"/>
            <stop offset="100%" stopColor="#2b4530"/>
          </linearGradient>
          <linearGradient id="leafLight" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#6b8f5b"/>
            <stop offset="100%" stopColor="#4d7048"/>
          </linearGradient>
        </defs>
        {/* vase body */}
        <path d="M60 220 Q 50 240 60 260 Q 70 280 105 296 Q 140 280 150 260 Q 160 240 150 220 Q 140 215 105 215 Q 70 215 60 220 Z" fill="url(#glass)" stroke="rgba(0,0,0,0.15)" strokeWidth="1"/>
        <path d="M75 240 Q 70 250 78 265 Q 95 285 105 290 Q 115 285 132 265 Q 140 250 135 240 Q 110 248 75 240 Z" fill="url(#water)" opacity="0.85"/>
        {/* vase neck */}
        <ellipse cx="105" cy="218" rx="40" ry="6" fill="rgba(255,255,255,0.9)" stroke="rgba(0,0,0,0.1)" strokeWidth="0.6"/>
        <ellipse cx="105" cy="218" rx="36" ry="4" fill="rgba(0,0,0,0.15)"/>
        {/* stems going into water */}
        <g stroke="#4a5c3a" strokeWidth="1.2" opacity="0.6">
          <path d="M95 218 L 90 285"/>
          <path d="M110 218 L 115 285"/>
          <path d="M100 218 L 102 285"/>
        </g>
        {/* leaves — big tropical (like reference image) */}
        <g>
          <ellipse cx="60" cy="120" rx="35" ry="80" transform="rotate(-35 60 120)" fill="url(#leafLight)"/>
          <ellipse cx="85" cy="90" rx="32" ry="85" transform="rotate(-18 85 90)" fill="url(#leafDark)"/>
          <ellipse cx="115" cy="70" rx="34" ry="92" transform="rotate(8 115 70)" fill="url(#leafLight)"/>
          <ellipse cx="145" cy="95" rx="33" ry="88" transform="rotate(24 145 95)" fill="url(#leafDark)"/>
          <ellipse cx="170" cy="130" rx="30" ry="75" transform="rotate(42 170 130)" fill="url(#leafLight)"/>
          <ellipse cx="100" cy="160" rx="28" ry="65" transform="rotate(-8 100 160)" fill="url(#leafDark)"/>
          <ellipse cx="135" cy="170" rx="26" ry="60" transform="rotate(18 135 170)" fill="url(#leafLight)"/>
          {/* highlights */}
          <ellipse cx="60" cy="120" rx="12" ry="50" transform="rotate(-35 60 120)" fill="rgba(255,255,255,0.12)"/>
          <ellipse cx="115" cy="70" rx="11" ry="55" transform="rotate(8 115 70)" fill="rgba(255,255,255,0.15)"/>
          <ellipse cx="170" cy="130" rx="10" ry="42" transform="rotate(42 170 130)" fill="rgba(255,255,255,0.10)"/>
        </g>
        {/* central vein on a leaf */}
        <g stroke="rgba(0,0,0,0.15)" strokeWidth="0.7" fill="none">
          <path d="M115 25 Q 115 70 115 160" />
          <path d="M85 175 Q 85 130 80 90 Z" />
          <path d="M145 180 Q 145 130 150 90" />
        </g>
      </svg>
    </div>
  );
}

Object.assign(window, { Poster, WallMockup, PinSvg });
