/* Atlas Pill Components — 1:1 SwiftUI port
   Maps MapPillViews.swift + MapDetailViews.swift → React + SVG */

// ── GuillochePattern ─ 45° cross-hatch (SwiftUI Canvas port) ──────────
function GuillochePattern({ color = '#8C4DFF', opacity = 0.14, spacing = 10, w = 200, h = 100, strokeWidth = 0.5 }) {
  const sc = 0.7071067811865476;
  const diag = Math.max(w, h) * 1.5;
  const cx = w / 2, cy = h / 2;
  const p1 = [], p2 = [];
  for (let d = -diag; d < diag; d += spacing) {
    p1.push(`M${cx + sc*diag - sc*d},${cy + sc*diag + sc*d} L${cx - sc*diag - sc*d},${cy - sc*diag + sc*d}`);
    p2.push(`M${cx + sc*diag + sc*d},${cy - sc*diag + sc*d} L${cx - sc*diag + sc*d},${cy + sc*diag + sc*d}`);
  }
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none"
         style={{ position:'absolute', inset:0, width:'100%', height:'100%', pointerEvents:'none' }}>
      <path d={p1.join(' ')} stroke={color} strokeOpacity={opacity} strokeWidth={strokeWidth} fill="none"/>
      <path d={p2.join(' ')} stroke={color} strokeOpacity={opacity} strokeWidth={strokeWidth} fill="none"/>
    </svg>
  );
}

// ── PassportStamp ─ top-right concentric ring + 4 dots ─────────────────
function PassportStamp({ color = '#8C4DFF', opacity = 0.22, radius = 14 }) {
  const innerR = radius > 12 ? radius - 3 : radius - 2.5;
  const lineInset = radius > 12 ? radius - 5 : radius - 3;
  const strokeW = radius > 12 ? 1.5 : 1.2;
  const innerW = radius > 12 ? 0.8 : 0.6;
  const lineW = radius > 12 ? 0.8 : 0.6;
  // 4 corner dots at 45°, 135°, 225°, 315°
  const dotR = innerR - 1;
  const dots = [0,1,2,3].map(i => {
    const a = i * Math.PI / 2 + Math.PI / 4;
    return { x: Math.cos(a) * dotR, y: Math.sin(a) * dotR };
  });
  const offset = radius + 8;
  return (
    <svg style={{ position:'absolute', top:0, right:0, width: offset*2+4, height: offset*2+4, pointerEvents:'none' }}>
      <g transform={`translate(${4}, ${offset})`}>
        <circle cx="0" cy="0" r={radius} fill="none" stroke={color} strokeOpacity={opacity} strokeWidth={strokeW}/>
        <circle cx="0" cy="0" r={innerR} fill="none" stroke={color} strokeOpacity={opacity} strokeWidth={innerW} strokeDasharray="2 2"/>
        <line x1={-lineInset} y1="0" x2={lineInset} y2="0" stroke={color} strokeOpacity={opacity} strokeWidth={lineW}/>
        {dots.map((d,i)=>(
          <circle key={i} cx={d.x} cy={d.y} r="1" fill={color} fillOpacity={opacity}/>
        ))}
      </g>
    </svg>
  );
}

// ── UVRevealOverlay ─ rainbow guilloche + city name + corner stars ────
const UV_SPECTRUM = ['#8C00F2','#4033FF','#00B3E6','#00D966','#E6D900','#FF8000','#F23380','#8C00F2'];
function UVRevealOverlay({ label='İSTANBUL', topText='', bottomText='', spacing = 8, w = 200, h = 120, cornerRadius = 12 }) {
  const sc = 0.7071067811865476;
  const diag = Math.max(w, h) * 1.5;
  const cx = w / 2, cy = h / 2;
  const totalLines = Math.floor(diag * 2 / spacing);
  const spec = UV_SPECTRUM.length;
  const lines = [];
  for (let i = 0; i < totalLines; i++) {
    const d = -diag + i * spacing;
    const t = (i / Math.max(totalLines - 1, 1));
    const colorIndex = t * (spec - 1);
    const idx = Math.min(Math.floor(colorIndex), spec - 2);
    const frac = colorIndex - idx;
    const lineColor = frac > 0.5 ? UV_SPECTRUM[idx+1] : UV_SPECTRUM[idx];
    lines.push(
      <g key={i}>
        <line x1={cx + sc*diag - sc*d} y1={cy + sc*diag + sc*d}
              x2={cx - sc*diag - sc*d} y2={cy - sc*diag + sc*d}
              stroke={lineColor} strokeOpacity="0.28" strokeWidth="0.6"/>
        <line x1={cx + sc*diag + sc*d} y1={cy - sc*diag + sc*d}
              x2={cx - sc*diag + sc*d} y2={cy + sc*diag + sc*d}
              stroke={lineColor} strokeOpacity="0.20" strokeWidth="0.4"/>
      </g>
    );
  }
  const rings = [];
  for (let r = 14; r < 90; r += 16) {
    rings.push(<circle key={r} cx={cx} cy={cy} r={r} fill="none" stroke="#8C4DFF" strokeOpacity="0.10" strokeWidth="0.5"/>);
  }
  const stars = [
    [10, 10],[w-10, 10],[10, h-10],[w-10, h-10]
  ];
  return (
    <div className="atl-uv" style={{ position:'absolute', inset:0, borderRadius:'inherit', overflow:'hidden', pointerEvents:'none' }}>
      <div style={{ position:'absolute', inset:0,
        background:'radial-gradient(circle at center, rgba(89,38,217,0.18) 0%, rgba(51,13,153,0.08) 35%, transparent 75%)' }}/>
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none"
           style={{ position:'absolute', inset:0, width:'100%', height:'100%' }}>
        {lines}
        {rings}
        <g transform={`translate(${cx} ${cy}) rotate(-15)`}>
          <text textAnchor="middle" dominantBaseline="middle"
                fontSize="14" fontWeight="900" fill="#8C4DFF" fillOpacity="0.5">{label}</text>
        </g>
        <text x={cx} y="14" textAnchor="middle" fontSize="7" fontWeight="700"
              fontFamily="monospace" fill="#8C4DFF" fillOpacity="0.35">{topText}</text>
        <text x={cx} y={h-8} textAnchor="middle" fontSize="7" fontWeight="600"
              fontFamily="monospace" fill="#8C4DFF" fillOpacity="0.3">{bottomText}</text>
        {stars.map(([x,y],i)=>(
          <polygon key={i} points={`${x},${y-3} ${x+0.9},${y-0.9} ${x+3},${y} ${x+0.9},${y+0.9} ${x},${y+3} ${x-0.9},${y+0.9} ${x-3},${y} ${x-0.9},${y-0.9}`}
                   fill="#8C4DFF" fillOpacity="0.45"/>
        ))}
        <rect x="5" y="5" width={w-10} height={h-10} rx="7" ry="7"
              fill="none" stroke="#8C4DFF" strokeOpacity="0.2" strokeWidth="0.8" strokeDasharray="3 2"/>
      </svg>
    </div>
  );
}

// ── DistrictPill ──────────────────────────────────────────────────────
function DistrictPill({ name, icon='◆', color='#D4A574', placeUnlocked=0, placeTotal=0, nbhdUnlocked=0, nbhdTotal=0, gemUnlocked=0, gemTotal=0, completion=0, size='district' }) {
  const [hovered, setHovered] = React.useState(false);
  const isComplete = completion >= 1;
  const pct = Math.round(completion * 100);
  const sizeClass = size === 'nbhd' ? 'sz-nbhd' : 'sz-district';
  const gSpacing = size === 'nbhd' ? 8 : 10;
  const stampRadius = size === 'nbhd' ? 10 : 14;
  const uvSpacing = size === 'nbhd' ? 8 : 10;
  return (
    <div
      className={`atl-pill ${sizeClass} ${isComplete ? 'is-complete' : ''} ${hovered ? 'is-revealed' : ''}`}
      style={{ '--c': color }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <div className="atl-layer atl-layer-guilloche">
        <GuillochePattern color={color} opacity={0.14} spacing={gSpacing}/>
      </div>
      <div className="atl-layer atl-layer-outer"/>
      <div className="atl-layer atl-layer-inner"/>
      <div className="atl-layer atl-layer-stamp">
        <PassportStamp color={color} opacity={0.22} radius={stampRadius}/>
      </div>
      <div className="atl-icon">{icon}</div>
      <div className="atl-name">{name}</div>
      <div className="atl-stats">
        <span className="atl-stat"><span className="atl-dot-ic">●</span>{placeUnlocked}/{placeTotal}</span>
        {nbhdTotal > 0 && (
          <span className="atl-stat"><span className="atl-dot-ic">▢</span>{nbhdUnlocked}/{nbhdTotal}</span>
        )}
      </div>
      {gemTotal > 0 && (
        <div className="atl-stats"><span className="atl-stat gem-count">💎 {gemUnlocked}/{gemTotal}</span></div>
      )}
      <div className="atl-progress"><i style={{ width: `${Math.min(pct,100)}%` }}/></div>
      <div className="atl-pct">%{pct}</div>
      <UVRevealOverlay label="İSTANBUL" topText={name.toUpperCase()}
        bottomText={window.__locale === 'tr' ? `${placeUnlocked}/${placeTotal} MEKAN • %${pct}` : `${placeUnlocked}/${placeTotal} PLACES • ${pct}%`} spacing={uvSpacing}/>
    </div>
  );
}

// ── NeighborhoodPill ──────────────────────────────────────────────────
function NeighborhoodPill({ name, icon='◆', color='#00BCD4', placeUnlocked=0, placeTotal=0, gemUnlocked=0, gemTotal=0, completion=0, locked=false, spotlight=false, topRarity=null }) {
  const [hovered, setHovered] = React.useState(false);
  const isComplete = completion >= 1;
  const pct = Math.round(completion * 100);
  const hasProgress = !locked && placeUnlocked > 0;
  const rarityColor = topRarity?.color;
  return (
    <div
      className={`atl-pill sz-nbhd ${isComplete ? 'is-complete' : ''} ${hovered ? 'is-revealed' : ''}`}
      style={{ '--c': color, filter: hasProgress ? 'none' : 'grayscale(0.35)' }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      <div className="atl-layer atl-layer-guilloche">
        <GuillochePattern color={color} opacity={0.12} spacing={8}/>
      </div>
      <div className="atl-layer atl-layer-outer"/>
      <div className="atl-layer atl-layer-inner"/>
      <div className="atl-layer atl-layer-stamp">
        <PassportStamp color={color} opacity={0.20} radius={10}/>
      </div>
      {!hasProgress && <div className="atl-lock-badge">🔒</div>}
      {hasProgress && spotlight && <div className="atl-season-badge">✦</div>}
      {topRarity && hasProgress && (
        <div className="atl-rarity-badge" style={{ '--rr': rarityColor }}>
          {topRarity.key === 'legendary' ? '✦' : '◆'}
        </div>
      )}
      <div className="atl-icon">{icon}</div>
      <div className="atl-name">{name}</div>
      <div className="atl-stats">
        <span className="atl-stat"><span className="atl-dot-ic">●</span>{placeUnlocked}/{placeTotal}</span>
        {gemTotal > 0 && (
          <span className="atl-stat gem-count">💎 {gemUnlocked}/{gemTotal}</span>
        )}
      </div>
      <div className="atl-progress"><i style={{ width: `${Math.min(pct,100)}%` }}/></div>
      <div className="atl-pct">%{pct}</div>
      <UVRevealOverlay label="İSTANBUL" topText={name.toUpperCase()}
        bottomText={window.__locale === 'tr' ? `${placeUnlocked}/${placeTotal} MEKAN • %${pct}` : `${placeUnlocked}/${placeTotal} PLACES • ${pct}%`} spacing={8}/>
    </div>
  );
}

// ── PlaceDetailPill — mirrors PlaceDetailCard ──────────────────────────
const RARITY_COLORS = (window.__locale === 'tr') ? {
  common:   { color:'#9AA5B1', name:'Yaygın',   icon:'◆' },
  uncommon: { color:'#4ADE80', name:'Nadir',    icon:'◆' },
  rare:     { color:'#3B82F6', name:'Ender',    icon:'◆' },
  epic:     { color:'#A855F7', name:'Destansı', icon:'◆' },
  legendary:{ color:'#F5B301', name:'Efsanevi', icon:'✦' },
} : {
  common:   { color:'#9AA5B1', name:'Common',    icon:'◆' },
  uncommon: { color:'#4ADE80', name:'Uncommon',  icon:'◆' },
  rare:     { color:'#3B82F6', name:'Rare',      icon:'◆' },
  epic:     { color:'#A855F7', name:'Epic',      icon:'◆' },
  legendary:{ color:'#F5B301', name:'Legendary', icon:'✦' },
};
function PlaceDetailPill({ name, district, neighborhood, description, xp=100, rarity='legendary', categoryIcon='🕌', unlocked=false }) {
  const r = RARITY_COLORS[rarity] || RARITY_COLORS.legendary;
  return (
    <div className="atl-place" style={{ '--c': r.color }}>
      <div className="atl-layer-outer"/>
      <div className="atl-layer-inner"/>
      <div className="atl-place-hd">
        <div className="ic">{categoryIcon}</div>
        <div className="meta">
          <div className="nm">{name}</div>
          <div className="loc">{district}{neighborhood ? ` · ${neighborhood}` : ''}</div>
        </div>
        <button className="x" aria-label="close">×</button>
      </div>
      {description && <p className="atl-place-desc">{description}</p>}
      <div className="atl-place-stats">
        <span className="st xp"><span className="star">★</span> {xp} XP</span>
        <span className="st rar">{r.icon} {r.name}</span>
        <span className="sp"/>
        <span className={`status ${unlocked ? 'unl' : 'loc'}`}>{unlocked ? (window.__locale === 'tr' ? '✓ Keşfedildi' : '✓ Discovered') : (window.__locale === 'tr' ? '🔒 Keşfedilmedi' : '🔒 Not discovered')}</span>
      </div>
      <div className="atl-place-div"/>
      <div className="atl-place-actions">
        {!unlocked && <button className="btn discover">{window.__locale === 'tr' ? '⌖ Keşfet' : '⌖ Discover'}</button>}
        <button className="btn dir">{window.__locale === 'tr' ? '↗ Yol Tarifi' : '↗ Directions'}</button>
        <button className="btn share">{window.__locale === 'tr' ? '⇪ Paylaş' : '⇪ Share'}</button>
      </div>
      <div className="atl-place-secondary">
        <button className="btn">{window.__locale === 'tr' ? '👥 Grup' : '👥 Group'}</button>
        <button className="btn">{window.__locale === 'tr' ? '♡ Favori' : '♡ Favorite'}</button>
        <button className="btn gem">{window.__locale === 'tr' ? '💎 Öner' : '💎 Suggest'}</button>
      </div>
    </div>
  );
}

// Export to window for cross-script access
Object.assign(window, {
  GuillochePattern, PassportStamp, UVRevealOverlay,
  DistrictPill, NeighborhoodPill, PlaceDetailPill,
  ATLAS_RARITY: RARITY_COLORS,
});
