// axios estate — image renderer + SVG fallbacks, map, icons

// Derive SMALL/LARGE counterpart URLs for the BBF Qubehub CDN. Three URL
// formats appear in our gallery — all support size variants by string swap:
//   - Qalle legacy: `SMALL_<uuid>` / `MEDIUM_<uuid>` / `LARGE_<uuid>` (same
//     uuid across sizes — empirically verified 2026-05-14).
//   - Qubehub named: `<prefix>_small.jpg` / `_medium.jpg` / `_large.jpg`
//   - Qubehub uuid+timestamp: `<uuid>_small_<ts>.jpg` / `_medium_` / `_large_`
// Returns identical small/large when no pattern matches (no progressive).
function deriveVariants(url) {
  if (!url) return { small: null, large: null };
  if (/(LARGE|MEDIUM|SMALL)_/.test(url)) {
    return {
      small: url.replace(/(LARGE|MEDIUM|SMALL)_/, 'SMALL_'),
      large: url.replace(/(LARGE|MEDIUM|SMALL)_/, 'LARGE_'),
    };
  }
  if (/_(small|medium|large)\.[a-z]+$/i.test(url)) {
    return {
      small: url.replace(/_(small|medium|large)\.([a-z]+)$/i, '_small.$2'),
      large: url.replace(/_(small|medium|large)\.([a-z]+)$/i, '_large.$2'),
    };
  }
  if (/_(small|medium|large)_/i.test(url)) {
    return {
      small: url.replace(/_(small|medium|large)_/i, '_small_'),
      large: url.replace(/_(small|medium|large)_/i, '_large_'),
    };
  }
  return { small: url, large: url };
}

// Project image: progressive blur-up. Renders SMALL underneath (blurred),
// fades in LARGE on load. Falls back to single-img when variants are identical
// (unknown URL format). SVG silhouette is the final fallback when src is null.
window.ProjectVisual = function ProjectVisual({ seed = 0, variant = 'tower', src = null, alt = '' }) {
  if (src) return <ProgressiveImage src={src} alt={alt} />;
  return <ProjectVisualSvg seed={seed} variant={variant} />;
};

function ProgressiveImage({ src, alt }) {
  const { small, large } = React.useMemo(() => deriveVariants(src), [src]);
  const progressive = small !== large;
  const [bigLoaded, setBigLoaded] = React.useState(!progressive);

  React.useEffect(() => {
    if (!progressive) return;
    setBigLoaded(false);
    const img = new Image();
    img.onload = () => setBigLoaded(true);
    img.onerror = () => setBigLoaded(true);
    img.src = large;
    return () => { img.onload = null; img.onerror = null; };
  }, [large, progressive]);

  if (!progressive) {
    return (
      <img
        src={src}
        alt={alt}
        loading="lazy"
        style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
      />
    );
  }

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden' }}>
      <img
        src={small}
        alt={alt}
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover',
          filter: bigLoaded ? 'none' : 'blur(14px)',
          transform: bigLoaded ? 'scale(1)' : 'scale(1.05)',
          transition: 'filter 0.45s ease-out, transform 0.45s ease-out',
        }}
      />
      <img
        src={large}
        alt=""
        aria-hidden="true"
        loading="lazy"
        onLoad={() => setBigLoaded(true)}
        style={{
          position: 'absolute', inset: 0, width: '100%', height: '100%',
          objectFit: 'cover',
          opacity: bigLoaded ? 1 : 0,
          transition: 'opacity 0.45s ease-out',
        }}
      />
    </div>
  );
}

function ProjectVisualSvg({ seed = 0, variant = 'tower' }) {
  // deterministic pseudo-random based on seed
  const r = (n) => {
    const x = Math.sin(seed * 9301 + n * 49297) * 233280;
    return Math.abs(x - Math.floor(x));
  };

  const variants = ['tower', 'cluster', 'villa', 'horizon'];
  const v = variants[seed % variants.length];

  return (
    <svg viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id={`sky-${seed}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#fafafa" />
          <stop offset="1" stopColor="#ebebeb" />
        </linearGradient>
        <pattern id={`grid-${seed}`} width="20" height="20" patternUnits="userSpaceOnUse">
          <path d="M 20 0 L 0 0 0 20" fill="none" stroke="#ebebeb" strokeWidth="0.5" />
        </pattern>
      </defs>
      <rect width="400" height="300" fill={`url(#sky-${seed})`} />
      <rect width="400" height="300" fill={`url(#grid-${seed})`} opacity="0.4" />
      {/* sun/moon disc */}
      <circle cx={80 + r(1) * 240} cy={50 + r(2) * 30} r="32" fill="#fff" stroke="#ebebeb" strokeWidth="1" />

      {v === 'tower' && (
        <g>
          {/* horizon */}
          <line x1="0" y1="240" x2="400" y2="240" stroke="#a8a8a8" strokeWidth="0.5" />
          {/* main tower */}
          <rect x="170" y="60" width="60" height="180" fill="#1e1e1e" />
          {/* tower windows grid */}
          {Array.from({ length: 12 }).map((_, i) =>
            Array.from({ length: 4 }).map((_, j) => (
              <rect key={`${i}-${j}`} x={178 + j * 12} y={70 + i * 14} width="6" height="6" fill="#fafafa" opacity={r(i * 4 + j) > 0.3 ? 0.9 : 0.3} />
            ))
          )}
          {/* side towers */}
          <rect x="100" y="140" width="50" height="100" fill="#737373" />
          <rect x="250" y="120" width="55" height="120" fill="#a8a8a8" />
          <rect x="320" y="170" width="50" height="70" fill="#737373" />
          <rect x="30" y="180" width="55" height="60" fill="#a8a8a8" />
          {/* sea reflection */}
          <rect x="0" y="240" width="400" height="60" fill="#f2f2f2" />
          <line x1="0" y1="260" x2="400" y2="260" stroke="#ebebeb" strokeWidth="0.5" strokeDasharray="2 4" />
        </g>
      )}

      {v === 'cluster' && (
        <g>
          <line x1="0" y1="220" x2="400" y2="220" stroke="#a8a8a8" strokeWidth="0.5" />
          {[
            [40, 130, 60, 90],
            [110, 100, 70, 120],
            [190, 80, 80, 140],
            [280, 110, 60, 110],
            [350, 140, 50, 80],
          ].map(([x, y, w, h], i) => (
            <g key={i}>
              <rect x={x} y={y} width={w} height={h} fill={i % 2 ? '#1e1e1e' : '#737373'} />
              {Array.from({ length: Math.floor(h / 16) }).map((_, k) =>
                Array.from({ length: Math.floor(w / 14) }).map((_, j) => (
                  <rect key={`${k}-${j}`} x={x + 5 + j * 14} y={y + 8 + k * 16} width="6" height="6" fill="#fafafa" opacity={r(i + k + j) > 0.4 ? 0.85 : 0.25} />
                ))
              )}
            </g>
          ))}
          <rect x="0" y="220" width="400" height="80" fill="#f2f2f2" />
        </g>
      )}

      {v === 'villa' && (
        <g>
          {/* hill */}
          <path d="M 0 240 Q 100 180 200 200 T 400 220 L 400 300 L 0 300 Z" fill="#ebebeb" />
          <path d="M 0 260 Q 150 210 280 230 T 400 250 L 400 300 L 0 300 Z" fill="#f2f2f2" />
          {/* villas */}
          {[[80, 200], [180, 180], [280, 195]].map(([x, y], i) => (
            <g key={i}>
              <rect x={x} y={y} width="64" height="36" fill="#1e1e1e" />
              <rect x={x + 50} y={y - 12} width="14" height="48" fill="#737373" />
              <rect x={x + 8} y={y + 10} width="10" height="10" fill="#fafafa" />
              <rect x={x + 26} y={y + 10} width="10" height="10" fill="#fafafa" opacity="0.5" />
              {/* pool */}
              <rect x={x + 8} y={y + 36} width="48" height="6" fill="#a8a8a8" />
            </g>
          ))}
          {/* trees */}
          {[40, 160, 260, 360].map((x, i) => (
            <g key={i}>
              <rect x={x - 1} y={185 + r(i) * 15} width="2" height="20" fill="#737373" />
              <circle cx={x} cy={180 + r(i) * 15} r="8" fill="#a8a8a8" />
            </g>
          ))}
        </g>
      )}

      {v === 'horizon' && (
        <g>
          {/* mediterranean horizon */}
          <line x1="0" y1="170" x2="400" y2="170" stroke="#a8a8a8" strokeWidth="0.5" />
          {/* distant city */}
          {Array.from({ length: 18 }).map((_, i) => {
            const h = 8 + r(i) * 28;
            return <rect key={i} x={i * 22 + r(i + 30) * 4} y={170 - h} width={14 + r(i + 50) * 6} height={h} fill="#a8a8a8" opacity="0.7" />;
          })}
          {/* sea */}
          <rect x="0" y="170" width="400" height="130" fill="#f2f2f2" />
          {/* foreground building */}
          <rect x="40" y="100" width="120" height="200" fill="#1e1e1e" />
          {Array.from({ length: 14 }).map((_, i) =>
            Array.from({ length: 7 }).map((_, j) => (
              <rect key={`${i}-${j}`} x={48 + j * 16} y={108 + i * 14} width="8" height="6" fill="#fafafa" opacity={r(i * 7 + j) > 0.35 ? 0.9 : 0.3} />
            ))
          )}
          {/* secondary */}
          <rect x="240" y="140" width="100" height="160" fill="#737373" />
          {/* sea texture */}
          {Array.from({ length: 10 }).map((_, i) => (
            <line key={i} x1="0" y1={185 + i * 12} x2="400" y2={185 + i * 12} stroke="#ebebeb" strokeWidth="0.5" strokeDasharray={`${4 + r(i) * 4} ${6 + r(i + 1) * 6}`} />
          ))}
        </g>
      )}
    </svg>
  );
};

// Hero composition — real photo if `src` provided, else SVG silhouette fallback.
window.HeroVisual = function HeroVisual({ src = null, alt = 'Лимасол, Кипр' } = {}) {
  if (src) return <ProgressiveImage src={src} alt={alt} />;
  return (
    <svg viewBox="0 0 600 750" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%' }}>
      <defs>
        <linearGradient id="hero-sky" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#ffffff" />
          <stop offset="0.7" stopColor="#fafafa" />
          <stop offset="1" stopColor="#f2f2f2" />
        </linearGradient>
      </defs>
      <rect width="600" height="750" fill="url(#hero-sky)" />
      {/* moon */}
      <circle cx="460" cy="120" r="48" fill="#fff" stroke="#ebebeb" strokeWidth="1" />
      {/* distant range */}
      <path d="M 0 480 L 60 440 L 140 460 L 220 420 L 300 450 L 400 410 L 500 440 L 600 420 L 600 500 L 0 500 Z" fill="#ebebeb" />
      {/* main tower (kean-like) */}
      <rect x="240" y="180" width="100" height="380" fill="#1e1e1e" />
      {Array.from({ length: 28 }).map((_, i) =>
        Array.from({ length: 6 }).map((_, j) => {
          const seed = i * 6 + j;
          const lit = (Math.sin(seed * 12.9898) * 43758.5453 % 1) > 0.4;
          return <rect key={`${i}-${j}`} x={250 + j * 14} y={192 + i * 13} width="8" height="6" fill="#fafafa" opacity={lit ? 0.92 : 0.28} />;
        })
      )}
      {/* secondary tower */}
      <rect x="360" y="280" width="80" height="280" fill="#737373" />
      {Array.from({ length: 18 }).map((_, i) =>
        Array.from({ length: 5 }).map((_, j) => (
          <rect key={`s-${i}-${j}`} x={368 + j * 14} y={290 + i * 14} width="8" height="6" fill="#fafafa" opacity="0.45" />
        ))
      )}
      {/* third */}
      <rect x="100" y="340" width="120" height="220" fill="#a8a8a8" />
      {Array.from({ length: 14 }).map((_, i) =>
        Array.from({ length: 7 }).map((_, j) => (
          <rect key={`t-${i}-${j}`} x={108 + j * 16} y={350 + i * 14} width="8" height="6" fill="#fafafa" opacity="0.5" />
        ))
      )}
      {/* low building */}
      <rect x="450" y="420" width="140" height="140" fill="#737373" />
      {/* foreground sea */}
      <rect x="0" y="560" width="600" height="190" fill="#fafafa" />
      <line x1="0" y1="560" x2="600" y2="560" stroke="#ebebeb" strokeWidth="1" />
      {/* sea waves */}
      {Array.from({ length: 12 }).map((_, i) => (
        <line
          key={`w-${i}`}
          x1="0"
          y1={580 + i * 14}
          x2="600"
          y2={580 + i * 14}
          stroke="#ebebeb"
          strokeWidth="0.5"
          strokeDasharray={`${3 + (i % 3) * 4} ${5 + ((i + 1) % 4) * 5}`}
        />
      ))}
      {/* bottom-left meta */}
      <text x="32" y="710" fontFamily="JetBrains Mono, monospace" fontSize="11" fill="#737373" letterSpacing="0.04em">34°41′N · 33°02′E · LIMASSOL</text>
      <text x="32" y="730" fontFamily="JetBrains Mono, monospace" fontSize="11" fill="#a8a8a8">PROJECT RENDER · PLACEHOLDER</text>
    </svg>
  );
};

// Cyprus map outline
window.CyprusMap = function CyprusMap({ children }) {
  return (
    <svg viewBox="0 0 1000 560" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet" style={{ width: '100%', height: '100%' }}>
      <defs>
        <pattern id="map-grid" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M 40 0 L 0 0 0 40" fill="none" stroke="#ebebeb" strokeWidth="0.5" />
        </pattern>
      </defs>
      <rect width="1000" height="560" fill="#fafafa" />
      <rect width="1000" height="560" fill="url(#map-grid)" />
      {/* simplified cyprus shape (silhouette only — not geographic perfection) */}
      <path
        d="M 90 320 Q 70 290 110 270 Q 150 250 200 260 Q 260 230 320 240 Q 380 220 440 230 Q 510 220 580 240 Q 660 220 740 240 Q 820 250 870 280 Q 920 300 900 340 Q 880 380 820 380 Q 760 400 690 380 Q 620 410 560 390 Q 500 410 430 390 Q 360 400 300 380 Q 240 400 180 370 Q 120 360 90 320 Z"
        fill="#fff"
        stroke="#1e1e1e"
        strokeWidth="1"
      />
      {/* karpas peninsula */}
      <path
        d="M 870 280 Q 920 260 950 240 Q 960 250 940 270 Q 920 285 880 290 Z"
        fill="#fff"
        stroke="#1e1e1e"
        strokeWidth="1"
      />
      {/* coordinate ticks */}
      <text x="20" y="40" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#a8a8a8">34°N</text>
      <text x="20" y="540" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#a8a8a8">35°N</text>
      <text x="940" y="540" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="#a8a8a8" textAnchor="end">35°E</text>
    </svg>
  );
};

// Simple icon set
window.Icon = function Icon({ name, size = 16 }) {
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', strokeLinejoin: 'round' };
  switch (name) {
    case 'phone':
      return <svg {...props}><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/></svg>;
    case 'message':
      return <svg {...props}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>;
    case 'arrow-right':
      return <svg {...props}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>;
    case 'arrow-up-right':
      return <svg {...props}><line x1="7" y1="17" x2="17" y2="7"/><polyline points="7 7 17 7 17 17"/></svg>;
    case 'close':
      return <svg {...props}><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>;
    case 'download':
      return <svg {...props}><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>;
    case 'plane':
      return <svg {...props}><path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z"/></svg>;
    default: return null;
  }
};
