// primitives.jsx — reusable visual building blocks
// Loaded as Babel script; exports to window

const INK = '#0A0A0A';
const INK2 = '#1A1A1A';
const DIM = '#737373';
const LINE = '#D4D4D4';
const PAPER = '#FAFAFA';
const WHITE = '#FFFFFF';
const CORAL = '#FF5A5F';
const YELLOW = '#FFD84D';
const GREEN = '#22A879';
const MONO = "'JetBrains Mono', ui-monospace, monospace";
const SANS = "'Inter', -apple-system, system-ui, sans-serif";
const SERIF = "'Instrument Serif', 'Times New Roman', serif";

// ── Eyebrow tag (matching existing landing) ───────────────────────────────
function Eyebrow({ text, color = CORAL, x, y, size = 16 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '8px 16px',
      border: `1px solid ${color}`,
      borderRadius: 999,
      fontFamily: SANS, fontSize: size, fontWeight: 700,
      letterSpacing: '0.12em', textTransform: 'uppercase',
      color, background: 'rgba(255,90,95,0.06)',
    }}>
      <span style={{
        width: 8, height: 8, borderRadius: 99,
        background: color,
        boxShadow: `0 0 0 4px ${color}33`,
      }}/>
      {text}
    </div>
  );
}

// ── Tax / compliance badge (auto-clearance indicator) ─────────────────────
function ComplianceBadge({ label, sub, x, y, color = GREEN }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '12px 18px',
      background: '#0c0a08',
      border: `1px solid ${color}66`,
      borderRadius: 14,
      boxShadow: `0 12px 32px rgba(0,0,0,0.4)`,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8,
        background: `${color}22`,
        border: `1px solid ${color}66`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
          <path d="M2 7L6 11L12 3" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </div>
      <div>
        <div style={{
          fontFamily: MONO, fontSize: 11, fontWeight: 700,
          letterSpacing: '0.14em', textTransform: 'uppercase',
          color,
        }}>{label}</div>
        <div style={{
          fontFamily: SANS, fontSize: 15, fontWeight: 700,
          color: WHITE, letterSpacing: '-0.2px', marginTop: 2,
        }}>{sub}</div>
      </div>
    </div>
  );
}

// ── Package (cardboard box, isometric-ish) ────────────────────────────────
function Package({ x, y, size = 120, rotation = 0, shadow = true, label = 'SEMORE' }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width: size, height: size,
      transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
    }}>
      {shadow && (
        <div style={{
          position: 'absolute',
          left: '10%', bottom: -8,
          width: '80%', height: 14,
          borderRadius: '50%',
          background: 'radial-gradient(ellipse, rgba(0,0,0,0.35), transparent 70%)',
          filter: 'blur(4px)',
        }}/>
      )}
      <svg viewBox="0 0 120 120" style={{ width: '100%', height: '100%', display: 'block' }}>
        {/* box body */}
        <rect x="12" y="24" width="96" height="80" fill="#D6B88A" stroke="#8A6F47" strokeWidth="1.5"/>
        {/* top flap */}
        <polygon points="12,24 60,10 108,24 60,38" fill="#E8CFA3" stroke="#8A6F47" strokeWidth="1.5"/>
        {/* center seam */}
        <line x1="60" y1="38" x2="60" y2="104" stroke="#8A6F47" strokeWidth="1.5"/>
        {/* tape */}
        <rect x="52" y="24" width="16" height="80" fill="#F5E6C9" opacity="0.85"/>
        <line x1="52" y1="24" x2="52" y2="104" stroke="#8A6F47" strokeWidth="0.6" opacity="0.6"/>
        <line x1="68" y1="24" x2="68" y2="104" stroke="#8A6F47" strokeWidth="0.6" opacity="0.6"/>
        {/* label */}
        <rect x="22" y="56" width="28" height="18" fill="#FFFFFF" stroke="#8A6F47" strokeWidth="0.6"/>
        <text x="36" y="67" fill={CORAL} fontSize="7" fontFamily={MONO} fontWeight="700" textAnchor="middle" letterSpacing="0.5">{label}</text>
        <rect x="22" y="78" width="28" height="3" fill="#333"/>
        <rect x="22" y="83" width="22" height="2" fill="#333"/>
        <rect x="22" y="87" width="26" height="2" fill="#333"/>
        {/* fragile arrow */}
        <path d="M 78 62 L 86 62 M 84 60 L 86 62 L 84 64" stroke={CORAL} strokeWidth="1.2" fill="none" strokeLinecap="round"/>
        <path d="M 78 70 L 86 70 M 84 68 L 86 70 L 84 72" stroke={CORAL} strokeWidth="1.2" fill="none" strokeLinecap="round"/>
      </svg>
    </div>
  );
}

// ── Apartment door / stoop (destination) ──────────────────────────────────
function Doorway({ x, y, width = 320, height = 420, variant = 'berlin' }) {
  const palettes = {
    berlin:  { wall: '#D4C5A8', door: '#4A3728', frame: '#2A1F15', accent: '#8B6B3D', trim: '#E8D9BD' },
    tokyo:   { wall: '#E8E4DC', door: '#1A1A1A', frame: '#0A0A0A', accent: '#C94A4F', trim: '#F5F1E8' },
    newyork: { wall: '#8B5A3C', door: '#1C1510', frame: '#0D0906', accent: '#D4A574', trim: '#A06B45' },
  };
  const p = palettes[variant] || palettes.berlin;

  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width, height,
    }}>
      <svg viewBox="0 0 320 420" style={{ width: '100%', height: '100%', display: 'block' }}>
        {/* wall */}
        <rect x="0" y="0" width="320" height="420" fill={p.wall}/>
        {/* subtle texture lines (siding / brickwork) */}
        {variant === 'newyork' && Array.from({length: 14}).map((_, i) => (
          <g key={i}>
            {Array.from({length: 6}).map((_, j) => (
              <rect key={j}
                x={(j * 55) + (i % 2 ? 28 : 0) - 30}
                y={i * 30}
                width="50" height="26"
                fill="none" stroke="#6B4028" strokeWidth="0.8" opacity="0.55"/>
            ))}
          </g>
        ))}
        {variant === 'berlin' && Array.from({length: 18}).map((_, i) => (
          <line key={i} x1="0" y1={i * 24} x2="320" y2={i * 24} stroke="#B09775" strokeWidth="0.5" opacity="0.4"/>
        ))}
        {variant === 'tokyo' && (
          <>
            <line x1="0" y1="140" x2="320" y2="140" stroke="#C9C4B8" strokeWidth="1"/>
            <line x1="0" y1="280" x2="320" y2="280" stroke="#C9C4B8" strokeWidth="1"/>
          </>
        )}
        {/* door frame */}
        <rect x="80" y="60" width="160" height="340" fill={p.frame}/>
        <rect x="88" y="68" width="144" height="324" fill={p.trim}/>
        {/* door */}
        <rect x="96" y="76" width="128" height="316" fill={p.door}/>
        {/* door panels */}
        <rect x="108" y="96" width="104" height="90" fill="none" stroke={p.accent} strokeWidth="1.5" opacity="0.45"/>
        <rect x="108" y="200" width="104" height="120" fill="none" stroke={p.accent} strokeWidth="1.5" opacity="0.45"/>
        {/* handle */}
        <circle cx="204" cy="240" r="4" fill={p.accent}/>
        {/* number plate */}
        <rect x="136" y="115" width="48" height="36" fill={p.trim} stroke={p.frame} strokeWidth="1"/>
        <text x="160" y="142"
          textAnchor="middle"
          fontSize="22" fontWeight="800"
          fontFamily={SERIF} fontStyle="italic"
          fill={p.frame}>
          {variant === 'berlin' ? '47' : variant === 'tokyo' ? '03' : '221'}
        </text>
        {/* step */}
        <rect x="60" y="400" width="200" height="20" fill={p.frame} opacity="0.3"/>
        <rect x="80" y="392" width="160" height="10" fill={p.accent} opacity="0.5"/>
      </svg>
    </div>
  );
}

// ── Boarding-pass card (matching landing's .bp) ───────────────────────────
function BoardingPass({ x, y, width = 420, lane, from, to, fromCity, toCity, meta, progress = 1, rotation = 0 }) {
  // progress: 0..1 — plane travels across line
  const planeX = 120 + progress * 130;
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width,
      transform: `rotate(${rotation}deg)`,
      transformOrigin: 'center',
    }}>
      <div style={{
        background: WHITE,
        borderRadius: 18,
        border: `1px solid ${LINE}`,
        boxShadow: '0 20px 50px -10px rgba(0,0,0,0.25)',
        overflow: 'hidden',
        padding: '18px 22px 20px',
        fontFamily: SANS,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          fontFamily: MONO, fontSize: 11, fontWeight: 700, color: DIM,
          letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 22 }}>
          <span>Semore · Lane {lane}</span>
          <span style={{ color: CORAL }}>EMS</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 8 }}>
          <div>
            <div style={{ fontSize: 42, fontWeight: 800, letterSpacing: '-1.5px', color: INK, lineHeight: 1 }}>{from}</div>
            <div style={{ fontSize: 11, color: DIM, marginTop: 6, letterSpacing: '0.02em' }}>{fromCity}</div>
          </div>
          <div style={{ width: 150, position: 'relative', height: 22 }}>
            <svg viewBox="0 0 150 22" style={{ width: '100%', height: '100%' }}>
              <line x1="6" y1="11" x2="120" y2="11" stroke={CORAL} strokeWidth="1.2"
                strokeLinecap="round" strokeDasharray="3 4" opacity="0.45"/>
              <g transform={`translate(${planeX - 14}, 0)`}>
                <path d="M 14 11 L 0 5 L 4 11 L 0 17 Z" fill={CORAL}/>
              </g>
            </svg>
          </div>
          <div>
            <div style={{ fontSize: 42, fontWeight: 800, letterSpacing: '-1.5px', color: CORAL, lineHeight: 1 }}>{to}</div>
            <div style={{ fontSize: 11, color: DIM, marginTop: 6, letterSpacing: '0.02em' }}>{toCity}</div>
          </div>
        </div>
        <div style={{
          borderTop: `1px dashed ${LINE}`,
          marginTop: 20, paddingTop: 16,
          display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
          fontFamily: MONO, fontSize: 12,
        }}>
          {meta.map((m, i) => (
            <div key={i}>
              <div style={{ fontSize: 9, color: DIM, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 600 }}>{m.label}</div>
              <div style={{ color: INK, fontWeight: 600, marginTop: 4 }}>{m.value}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ── Mini world map with routes ────────────────────────────────────────────
// Simple stylized continents, ICN → BER/HND/JFK arcs
function WorldMap({ x, y, width = 900, height = 500, progress = [0, 0, 0] }) {
  // Approximate positions on a 900x500 equirectangular-ish canvas
  const ICN = { x: 695, y: 205 };
  const BER = { x: 468, y: 160 };
  const HND = { x: 720, y: 210 };
  const JFK = { x: 275, y: 195 };

  const arcPath = (a, b, lift = 80) => {
    const mx = (a.x + b.x) / 2;
    const my = (a.y + b.y) / 2 - lift;
    return `M ${a.x} ${a.y} Q ${mx} ${my} ${b.x} ${b.y}`;
  };

  const routes = [
    { to: BER, label: 'BER', lift: 100, prog: progress[0] },
    { to: HND, label: 'HND', lift: 40, prog: progress[1] },
    { to: JFK, label: 'JFK', lift: 140, prog: progress[2] },
  ];

  return (
    <div style={{ position: 'absolute', left: x, top: y, width, height }}>
      <svg viewBox="0 0 900 500" style={{ width: '100%', height: '100%' }}>
        {/* graticule */}
        <g opacity="0.08">
          {Array.from({length: 9}).map((_, i) => (
            <line key={`v${i}`} x1={i * 112.5} y1="0" x2={i * 112.5} y2="500" stroke={WHITE} strokeWidth="0.5"/>
          ))}
          {Array.from({length: 6}).map((_, i) => (
            <line key={`h${i}`} x1="0" y1={i * 100} x2="900" y2={i * 100} stroke={WHITE} strokeWidth="0.5"/>
          ))}
        </g>
        {/* stylized continents — dotted landmass */}
        <Continents />

        {/* arcs */}
        {routes.map((r, i) => {
          const path = arcPath(ICN, r.to, r.lift);
          return (
            <g key={i}>
              <path d={path} fill="none" stroke={`${CORAL}33`} strokeWidth="1.5" strokeDasharray="3 4"/>
              <path d={path} fill="none" stroke={CORAL} strokeWidth="2"
                strokeLinecap="round"
                pathLength="1"
                strokeDasharray={`${r.prog} 1`}/>
            </g>
          );
        })}

        {/* origin pulse */}
        <g>
          <circle cx={ICN.x} cy={ICN.y} r="14" fill={CORAL} opacity="0.18">
            <animate attributeName="r" values="10;22;10" dur="2s" repeatCount="indefinite"/>
            <animate attributeName="opacity" values="0.3;0;0.3" dur="2s" repeatCount="indefinite"/>
          </circle>
          <circle cx={ICN.x} cy={ICN.y} r="6" fill={CORAL}/>
          <circle cx={ICN.x} cy={ICN.y} r="2.5" fill={WHITE}/>
          <text x={ICN.x + 14} y={ICN.y + 4} fill={WHITE} fontSize="11" fontWeight="700" fontFamily={MONO} letterSpacing="1">ICN</text>
        </g>

        {/* destinations — appear when arc reaches them */}
        {routes.map((r, i) => r.prog > 0.95 && (
          <g key={`d${i}`}>
            <circle cx={r.to.x} cy={r.to.y} r="5" fill={CORAL}/>
            <circle cx={r.to.x} cy={r.to.y} r="2" fill={WHITE}/>
            <text x={r.to.x + 10} y={r.to.y - 6} fill={WHITE} fontSize="11" fontWeight="700" fontFamily={MONO} letterSpacing="1">{r.label}</text>
          </g>
        ))}
      </svg>
    </div>
  );
}

// Dotted continents (abstract) — rough silhouettes via dot grid masked by SVG paths
function Continents() {
  // Very rough continent outlines for 900x500 equirectangular-ish view
  const paths = [
    // North America
    "M 80 110 Q 110 90 160 95 L 210 110 L 260 130 L 280 170 L 260 220 L 220 240 L 180 230 L 140 210 L 110 180 L 90 150 Z",
    // South America
    "M 240 250 L 270 260 L 280 310 L 275 370 L 260 410 L 240 400 L 225 360 L 220 310 Z",
    // Europe
    "M 420 130 L 470 120 L 500 140 L 490 170 L 460 180 L 430 175 L 420 155 Z",
    // Africa
    "M 440 190 L 490 190 L 520 230 L 520 290 L 490 340 L 460 340 L 440 300 L 435 240 Z",
    // Asia
    "M 510 110 L 580 100 L 680 115 L 740 130 L 760 170 L 740 210 L 700 225 L 640 220 L 580 200 L 530 175 L 510 150 Z",
    // SE Asia / Indonesia
    "M 680 240 L 760 245 L 780 265 L 760 280 L 700 275 L 680 260 Z",
    // Japan
    "M 740 170 L 760 175 L 765 195 L 755 210 L 740 205 L 735 190 Z",
    // Australia
    "M 740 320 L 810 320 L 830 355 L 800 380 L 740 370 Z",
  ];
  return (
    <g>
      {paths.map((d, i) => (
        <path key={i} d={d} fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.18)" strokeWidth="0.8"/>
      ))}
      {/* dot pattern overlay on continents */}
      <defs>
        <pattern id="dots" x="0" y="0" width="6" height="6" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="0.8" fill="rgba(255,255,255,0.35)"/>
        </pattern>
        <mask id="landmask">
          {paths.map((d, i) => (
            <path key={i} d={d} fill="white"/>
          ))}
        </mask>
      </defs>
      <rect x="0" y="0" width="900" height="500" fill="url(#dots)" mask="url(#landmask)"/>
    </g>
  );
}

// ── City skyline silhouette ───────────────────────────────────────────────
function Skyline({ variant, width, height, color = '#1a1a1a' }) {
  // Simple procedural skylines, distinct per city
  const skylines = {
    seoul: [40, 80, 55, 120, 75, 200, 90, 160, 70, 140, 95, 180, 60, 110, 85],
    berlin: [45, 60, 50, 70, 65, 90, 60, 160, 55, 85, 70, 95, 50, 65, 55],
    tokyo: [55, 90, 70, 180, 85, 140, 95, 220, 80, 150, 75, 200, 90, 130, 75],
    newyork: [65, 150, 85, 200, 105, 260, 95, 220, 110, 280, 85, 180, 100, 240, 90],
  };
  const heights = skylines[variant] || skylines.seoul;
  const w = width / heights.length;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} style={{ width: '100%', height: '100%', display: 'block' }}>
      {heights.map((h, i) => (
        <rect key={i}
          x={i * w} y={height - h}
          width={w - 2} height={h}
          fill={color}/>
      ))}
      {/* scattered windows */}
      {heights.map((h, i) =>
        Array.from({length: Math.floor(h / 18)}).map((_, j) => (
          <rect key={`w${i}-${j}`}
            x={i * w + 6 + (j % 2) * 8}
            y={height - h + 10 + j * 16}
            width="3" height="4"
            fill={YELLOW} opacity={Math.random() > 0.3 ? 0.8 : 0}/>
        ))
      )}
    </svg>
  );
}

// ── Split divider (center vertical line with city labels) ─────────────────
function SplitDivider({ height, topLabel, bottomLabel }) {
  return (
    <div style={{
      position: 'absolute',
      left: '50%', top: 0, height,
      transform: 'translateX(-50%)',
      width: 1, background: 'rgba(255,255,255,0.18)',
    }}>
      <div style={{
        position: 'absolute', left: -30, top: 40,
        transform: 'rotate(-90deg)', transformOrigin: 'left top',
        fontFamily: MONO, fontSize: 11, fontWeight: 700,
        letterSpacing: '0.2em', textTransform: 'uppercase',
        color: 'rgba(255,255,255,0.55)', whiteSpace: 'nowrap',
      }}>{topLabel}</div>
      <div style={{
        position: 'absolute', left: 30, bottom: 40,
        transform: 'rotate(-90deg)', transformOrigin: 'left bottom',
        fontFamily: MONO, fontSize: 11, fontWeight: 700,
        letterSpacing: '0.2em', textTransform: 'uppercase',
        color: 'rgba(255,255,255,0.55)', whiteSpace: 'nowrap',
      }}>{bottomLabel}</div>
    </div>
  );
}

// ── Scanner line (for progress/shipping feel) ─────────────────────────────
function ScanLine({ x, y, width, height = 2, progress = 0, color = CORAL }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      width, height,
      background: `linear-gradient(90deg, ${color} 0%, ${color} ${progress * 100}%, transparent ${progress * 100}%)`,
      boxShadow: `0 0 12px ${color}`,
    }}/>
  );
}

Object.assign(window, {
  Eyebrow, ComplianceBadge, Package, Doorway, BoardingPass,
  WorldMap, Skyline, SplitDivider, ScanLine,
  INK, INK2, DIM, LINE, PAPER, WHITE, CORAL, YELLOW, GREEN,
  MONO, SANS, SERIF,
});
