// Texture renderer — desenha cada revestimento via SVG procedural usando a paleta do produto.

const Texture = ({ product, w = 400, h = 400, seed = 0, density = 1 }) => {
  const p = product;
  const [pal0, pal1, pal2, pal3] = [p.paleta[0], p.paleta[1] || p.paleta[0], p.paleta[2] || p.paleta[0], p.paleta[3] || p.paleta[1]];

  // tiny seeded rng
  const rng = (() => {
    let s = seed * 9301 + 49297;
    return () => {
      s = (s * 1103515245 + 12345) & 0x7fffffff;
      return (s % 10000) / 10000;
    };
  })();
  const pick = (arr) => arr[Math.floor(rng() * arr.length)];

  let body;
  if (p.pattern === "grid") {
    // grid of small tiles, slightly varied color
    const tile = 26 / density;
    const cols = Math.ceil(w / tile) + 1;
    const rows = Math.ceil(h / tile) + 1;
    const tiles = [];
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        const color = pick(p.paleta);
        // sometimes merge 2 tiles horizontally (rectangle)
        const wide = rng() < 0.18 ? 2 : 1;
        if (wide === 2 && c < cols - 1) {
          tiles.push(<rect key={r+'-'+c} x={c*tile} y={r*tile} width={tile*2 - 1.5} height={tile - 1.5} fill={color} />);
        } else {
          tiles.push(<rect key={r+'-'+c} x={c*tile} y={r*tile} width={tile - 1.5} height={tile - 1.5} fill={color} />);
        }
      }
    }
    body = tiles;
  } else if (p.pattern === "mosaic") {
    const tile = 14 / density;
    const cols = Math.ceil(w / tile) + 1;
    const rows = Math.ceil(h / tile) + 1;
    const tiles = [];
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        tiles.push(<rect key={r+'-'+c} x={c*tile} y={r*tile} width={tile - 1} height={tile - 1} fill={pick(p.paleta)} />);
      }
    }
    body = tiles;
  } else if (p.pattern === "stripes") {
    // horizontal filetes — long thin strips
    const stripes = [];
    let y = 0;
    let key = 0;
    while (y < h) {
      const sh = 6 + rng() * 14;
      stripes.push(<rect key={key++} x={-2} y={y} width={w+4} height={sh - 0.8} fill={pick(p.paleta)} />);
      y += sh;
    }
    body = stripes;
  } else if (p.pattern === "filetes") {
    // irregular filetes (Arenito Talhado)
    const stripes = [];
    let y = 0, key = 0;
    while (y < h) {
      const sh = 5 + rng() * 18;
      // segment the stripe into pieces
      let x = 0;
      while (x < w) {
        const sw = 30 + rng() * 70;
        stripes.push(<rect key={key++} x={x} y={y} width={sw - 0.8} height={sh - 0.8} fill={pick(p.paleta)} />);
        x += sw;
      }
      y += sh;
    }
    body = stripes;
  } else if (p.pattern === "brick") {
    // staggered brick: ~brick aspect 2.2:1
    const bw = 80 / density;
    const bh = bw * 0.42;
    const rows = Math.ceil(h / bh) + 1;
    const cols = Math.ceil(w / bw) + 1;
    const tiles = [];
    for (let r = 0; r < rows; r++) {
      const offset = (r % 2) * (bw / 2);
      for (let c = -1; c < cols; c++) {
        tiles.push(<rect key={r+'-'+c} x={c*bw + offset} y={r*bh} width={bw - 1.2} height={bh - 1.2} fill={pick(p.paleta)} rx={0.5} />);
      }
    }
    body = tiles;
  } else if (p.pattern === "rockface") {
    // brick with shadow strokes (3D relief)
    const bw = 90 / density;
    const bh = bw * 0.42;
    const rows = Math.ceil(h / bh) + 1;
    const cols = Math.ceil(w / bw) + 1;
    const tiles = [];
    for (let r = 0; r < rows; r++) {
      const offset = (r % 2) * (bw / 2);
      for (let c = -1; c < cols; c++) {
        const fill = pick(p.paleta);
        const x = c*bw + offset;
        const y = r*bh;
        tiles.push(
          <g key={r+'-'+c}>
            <rect x={x} y={y} width={bw - 1.2} height={bh - 1.2} fill={fill} />
            <rect x={x} y={y} width={bw - 1.2} height={2} fill="#fff" opacity={0.2} />
            <rect x={x} y={y + bh - 3.2} width={bw - 1.2} height={2} fill="#000" opacity={0.25} />
          </g>
        );
      }
    }
    body = tiles;
  } else if (p.pattern === "organic") {
    // organic cuts — voronoi-like polygons
    const points = [];
    const cells = Math.floor(18 * density);
    for (let i = 0; i < cells; i++) {
      points.push([rng() * w, rng() * h]);
    }
    // For each pixel-ish grid, find nearest point and color cell
    const polys = points.map((pt, i) => {
      // approximate cell as a jittered polygon around the point
      const sides = 5 + Math.floor(rng() * 3);
      const radius = 30 + rng() * 50;
      const points2 = [];
      for (let s = 0; s < sides; s++) {
        const a = (s / sides) * Math.PI * 2 + rng() * 0.4;
        const r = radius * (0.6 + rng() * 0.5);
        points2.push(`${pt[0] + Math.cos(a) * r},${pt[1] + Math.sin(a) * r}`);
      }
      return <polygon key={i} points={points2.join(' ')} fill={p.paleta[i % p.paleta.length]} />;
    });
    body = polys;
  } else {
    body = <rect width={w} height={h} fill={pal0} />;
  }

  // subtle grain overlay
  const grain = (
    <g opacity={0.08}>
      {Array.from({length: 60}).map((_, i) => {
        const x = rng() * w, y = rng() * h, r = 0.4 + rng() * 1.4;
        return <circle key={i} cx={x} cy={y} r={r} fill={rng() < 0.5 ? "#000" : "#fff"} />;
      })}
    </g>
  );

  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{display:'block'}}>
      <rect width={w} height={h} fill={pal0} />
      {body}
      {grain}
      {/* warm vignette */}
      <rect width={w} height={h} fill="url(#vig)" />
      <defs>
        <radialGradient id="vig" cx="50%" cy="50%" r="75%">
          <stop offset="60%" stopColor="#000" stopOpacity="0" />
          <stop offset="100%" stopColor="#000" stopOpacity="0.22" />
        </radialGradient>
      </defs>
    </svg>
  );
};

// Ambient framing — shows the texture as a "wall" in a stylized room
const AmbientShot = ({ product, variant = 0 }) => {
  const variants = [
    { wall: 0.62, floor: 0.38, floorColor: "#e8e0d2", accent: "#2d2823", item: "sofa" },
    { wall: 0.55, floor: 0.45, floorColor: "#3a342c", accent: "#c4a474", item: "chair" },
    { wall: 0.7, floor: 0.3, floorColor: "#d4c8b4", accent: "#1a1612", item: "plant" },
  ];
  const v = variants[variant % variants.length];
  const wallH = 100 * v.wall;
  return (
    <div style={{position:'relative', width:'100%', height:'100%', overflow:'hidden', background: v.floorColor}}>
      <div style={{position:'absolute', top:0, left:0, right:0, height: wallH + '%'}}>
        <Texture product={product} w={500} h={500} seed={variant + 7} density={1.1} />
      </div>
      <div style={{position:'absolute', bottom:0, left:0, right:0, height: (100 - wallH) + '%', background: `linear-gradient(180deg, ${v.floorColor} 0%, ${v.floorColor} 60%, rgba(0,0,0,0.12) 100%)`}} />
      {/* floor lines */}
      <svg viewBox="0 0 100 40" preserveAspectRatio="none" style={{position:'absolute', bottom:0, left:0, width:'100%', height: (100 - wallH) + '%', opacity:0.18}}>
        <line x1="0" y1="0" x2="100" y2="0" stroke="#000" strokeWidth="0.2" />
        <line x1="0" y1="14" x2="100" y2="14" stroke="#000" strokeWidth="0.15" />
        <line x1="0" y1="28" x2="100" y2="28" stroke="#000" strokeWidth="0.1" />
      </svg>
      {/* ambient prop - silhouette */}
      {v.item === "sofa" && (
        <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYEnd meet" style={{position:'absolute', bottom: (100-wallH)*0.2 + '%', left: '12%', width:'52%', height:'42%'}}>
          <rect x="6" y="52" width="78" height="22" rx="4" fill={v.accent} opacity="0.85"/>
          <rect x="8" y="48" width="22" height="10" rx="3" fill={v.accent} opacity="0.95"/>
          <rect x="34" y="48" width="22" height="10" rx="3" fill={v.accent} opacity="0.95"/>
          <rect x="60" y="48" width="22" height="10" rx="3" fill={v.accent} opacity="0.95"/>
          <rect x="6" y="74" width="6" height="6" fill={v.accent} opacity="0.6"/>
          <rect x="78" y="74" width="6" height="6" fill={v.accent} opacity="0.6"/>
        </svg>
      )}
      {v.item === "chair" && (
        <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYEnd meet" style={{position:'absolute', bottom: (100-wallH)*0.1 + '%', right: '14%', width:'24%', height:'58%'}}>
          <rect x="34" y="22" width="32" height="48" rx="6" fill={v.accent} opacity="0.85"/>
          <rect x="34" y="66" width="32" height="8" fill={v.accent} opacity="0.95"/>
          <rect x="36" y="74" width="3" height="18" fill={v.accent} opacity="0.8"/>
          <rect x="61" y="74" width="3" height="18" fill={v.accent} opacity="0.8"/>
        </svg>
      )}
      {v.item === "plant" && (
        <svg viewBox="0 0 100 100" preserveAspectRatio="xMidYEnd meet" style={{position:'absolute', bottom: (100-wallH)*0.05 + '%', right: '10%', width:'22%', height:'62%'}}>
          {/* vase */}
          <path d="M40 70 L40 88 Q40 92 44 92 L56 92 Q60 92 60 88 L60 70 Z" fill={v.accent} opacity="0.85"/>
          {/* leaves */}
          <ellipse cx="50" cy="44" rx="4" ry="28" fill="#3d5a3a" opacity="0.9" transform="rotate(-15 50 44)"/>
          <ellipse cx="50" cy="38" rx="3.5" ry="32" fill="#4a6e46" opacity="0.85" transform="rotate(8 50 38)"/>
          <ellipse cx="50" cy="46" rx="4.5" ry="25" fill="#2f4a2d" opacity="0.95" transform="rotate(28 50 46)"/>
        </svg>
      )}
    </div>
  );
};

Object.assign(window, { Texture, AmbientShot });
