/* ===== Troyamarin — Interactive 3D Terrain ===== */
const { useRef, useState, useEffect } = React;

// Layered topographic island (beach -> olive peak), navy sea around it.
const TERRAIN_LAYERS = [
  { z: 0,  s: 1.00, c: '#D7C7A1' },
  { z: 9,  s: 0.93, c: '#CDBD90' },
  { z: 19, s: 0.85, c: '#BCC084' },
  { z: 30, s: 0.76, c: '#A4B26A' },
  { z: 42, s: 0.67, c: '#8BA257' },
  { z: 55, s: 0.57, c: '#74904A' },
  { z: 68, s: 0.47, c: '#5F7E3E' },
  { z: 82, s: 0.37, c: '#4E6B33' },
  { z: 96, s: 0.26, c: '#3D5727' },
];

function Terrain3D({ parcels, selected, onSelect }) {
  const pivotRef = useRef(null);
  const spin = useRef(-18);
  const dragging = useRef(false);
  const last = useRef(0);
  const auto = useRef(true);
  const tilt = 58;

  useEffect(() => {
    let raf;
    const tick = () => {
      if (auto.current && !dragging.current) spin.current += 0.12;
      if (pivotRef.current)
        pivotRef.current.style.transform =
          `rotateX(${tilt}deg) rotateZ(${spin.current}deg)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const down = (e) => {
    dragging.current = true;
    auto.current = false;
    last.current = (e.touches ? e.touches[0].clientX : e.clientX);
    e.currentTarget.classList.add('grab');
  };
  const move = (e) => {
    if (!dragging.current) return;
    const x = (e.touches ? e.touches[0].clientX : e.clientX);
    spin.current += (x - last.current) * 0.45;
    last.current = x;
  };
  const up = (e) => {
    dragging.current = false;
    if (e.currentTarget && e.currentTarget.classList) e.currentTarget.classList.remove('grab');
    setTimeout(() => { auto.current = true; }, 2600);
  };

  return (
    <div className="terrain-stage">
      <div
        className="tt"
        onMouseDown={down} onMouseMove={move} onMouseUp={up} onMouseLeave={up}
        onTouchStart={down} onTouchMove={move} onTouchEnd={up}
      >
        <div className="tt-pivot" ref={pivotRef} style={{ transform: 'rotateX(58deg) rotateZ(-18deg)' }}>
          <div className="water" />
          {TERRAIN_LAYERS.map((l, i) => (
            <div key={i} className="layer" style={{
              '--lc': l.c,
              transform: `translateZ(${l.z}px) scale(${l.s})`,
              filter: `brightness(${1 + i * 0.012})`,
            }} />
          ))}
          {parcels.map((p) => (
            <div key={p.id} className="pin" style={{ left: p.x, top: p.y }}>
              <div className="pin-stem" style={{
                height: p.h,
                transformOrigin: '50% 100%',
                transform: 'translate(-50%,-100%) rotateX(-90deg)',
              }} />
              <div
                className={'pin-dot' + (selected === p.id ? ' sel' : '')}
                style={{ transform: `translate(-50%,-50%) translateZ(${p.h}px)` }}
                onMouseDown={(e) => e.stopPropagation()}
                onClick={(e) => { e.stopPropagation(); onSelect(p.id); }}
              />
            </div>
          ))}
        </div>
      </div>

      <div className="terrain-ui">
        <span className="t-hint"><span className="ring" />Döndürmek için sürükleyin</span>
      </div>

      <ParcelCard parcel={parcels.find((p) => p.id === selected) || parcels[0]} />
    </div>
  );
}

function ParcelCard({ parcel }) {
  if (!parcel) return null;
  return (
    <div className="parcel-bar" key={parcel.id}>
      <div className="pb-l">
        <div className="pc-tag">{parcel.tag}</div>
        <h4>{parcel.title}</h4>
        <div className="pc-loc">{parcel.loc}</div>
      </div>
      <div className="pb-r">
        <div className="pb-spec"><small>ALAN</small><b>{parcel.area}</b></div>
        <div className="pb-spec"><small>İMAR</small><b>{parcel.zoning}</b></div>
        <div className="pb-price">{parcel.price}</div>
      </div>
    </div>
  );
}

Object.assign(window, { Terrain3D });
