// ─────────────────────────────────────────────
// DO_Fields_Map.jsx
// MapField — renders an embedded Google Map
//
// Uses Google Maps Embed API (iframe, no JS SDK)
// Requires Maps Embed API enabled in Google Console
//
// Depends on: DO_Shared.jsx (S styles)
// Loaded before DO_DetailView.jsx in index.html
// ─────────────────────────────────────────────

function MapField({ obj, value, record, apiKeys }) {
  // ── Resolve API key ──────────────────────────
  const apiKey = apiKeys?.google_maps?.api_key || '';

  // ── Resolve address ──────────────────────────
  // Full mode: single linked field
  // Partial mode: combine up to 5 separate fields, skip empty ones
  let address = '';
  if ((obj.addressMode || 'full') === 'partial') {
    const parts = [
      obj.fieldAddress ? (record?.[obj.fieldAddress] || '') : '',
      obj.fieldCity    ? (record?.[obj.fieldCity]    || '') : '',
      obj.fieldState   ? (record?.[obj.fieldState]   || '') : '',
      obj.fieldZip     ? (record?.[obj.fieldZip]     || '') : '',
      obj.fieldCountry ? (record?.[obj.fieldCountry] || '') : '',
    ].map(v => v.trim()).filter(Boolean);
    address = parts.join(', ');
  } else {
    address = obj.linkedField ? (record?.[obj.linkedField] || '').trim() : '';
  }

  // ── Map settings from inspector ──────────────
  const zoom          = parseInt(obj.zoom)      || 12;
  const height        = parseInt(obj.mapHeight) || 300;
  const mapType       = obj.mapType             || 'roadmap';   // roadmap|satellite|hybrid|terrain

  // ── Label ────────────────────────────────────
  const labelPos      = obj.labelpos    || 'top';
  const labelAlign    = obj.labelalign  || 'left';
  const showLabel     = obj.label && obj.label.trim().length > 0;

  const labelStyle = {
    display:     'block',
    fontSize:    10,
    fontWeight:  700,
    textTransform: 'uppercase',
    letterSpacing: '0.07em',
    color:       '#64748b',
    marginBottom: labelPos === 'top'    ? 4  : 0,
    marginTop:    labelPos === 'bottom' ? 4  : 0,
    textAlign:    labelAlign,
  };

  // ── No API key ───────────────────────────────
  if (!apiKey) {
    return (
      <div style={SM.wrap}>
        {showLabel && labelPos === 'top' && <label style={labelStyle}>{obj.label}</label>}
        <div style={{ ...SM.noKey, height }}>
          <div style={SM.noKeyIcon}>🗺️</div>
          <div style={SM.noKeyTitle}>Google Maps</div>
          <div style={SM.noKeyText}>
            No Google Maps API key configured.<br />
            Add your key in the App → API tab.
          </div>
        </div>
        {showLabel && labelPos === 'bottom' && <label style={labelStyle}>{obj.label}</label>}
      </div>
    );
  }

  // ── No address ───────────────────────────────
  if (!address) {
    return (
      <div style={SM.wrap}>
        {showLabel && labelPos === 'top' && <label style={labelStyle}>{obj.label}</label>}
        <div style={{ ...SM.noAddress, height }}>
          <div style={SM.noKeyIcon}>📍</div>
          <div style={SM.noKeyTitle}>No address</div>
          <div style={SM.noKeyText}>
            {(obj.addressMode || 'full') === 'partial'
              ? 'No address fields have data for this record.'
              : obj.linkedField
                ? `Field "${obj.linkedField}" is empty for this record.`
                : 'No address field configured.'}
          </div>
        </div>
        {showLabel && labelPos === 'bottom' && <label style={labelStyle}>{obj.label}</label>}
      </div>
    );
  }

  // ── Build embed URL ───────────────────────────
  // Maps Embed API — place mode centers on the address query
  // Note: Embed API only supports roadmap/satellite/terrain (not hybrid)
  const VALID_MAPTYPES = ['roadmap', 'satellite']; // Embed API only supports these two
  const safeMapType = VALID_MAPTYPES.includes(mapType) ? mapType : 'roadmap';

  const params = new URLSearchParams({ key: apiKey, q: address, zoom });
  // Only add maptype when non-default — avoids any param validation edge cases
  if (safeMapType !== 'roadmap') params.set('maptype', safeMapType);

  const embedUrl = `https://www.google.com/maps/embed/v1/place?${params.toString()}`;

  return (
    <div style={SM.wrap}>
      {showLabel && labelPos === 'top' && <label style={labelStyle}>{obj.label}</label>}

      <div style={{ position: 'relative', width: '100%', height }}>
        <iframe
          key={embedUrl}
          title={obj.label || 'Map'}
          src={embedUrl}
          style={SM.iframe}
          allowFullScreen
          loading="lazy"
          referrerPolicy="no-referrer-when-downgrade"
        />
      </div>

      {showLabel && labelPos === 'bottom' && <label style={labelStyle}>{obj.label}</label>}

      {/* ── Address caption ── */}
      {obj.showAddress !== false && address && (
        <div style={SM.caption}>📍 {address}</div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────
// STYLES — prefix SM
// ─────────────────────────────────────────────
const SM = {
  wrap: {
    marginBottom: 4,
    width: '100%',
  },
  iframe: {
    width:        '100%',
    height:       '100%',
    border:       'none',
    borderRadius: 6,
    display:      'block',
  },
  noKey: {
    display:        'flex',
    flexDirection:  'column',
    alignItems:     'center',
    justifyContent: 'center',
    background:     '#f8fafc',
    border:         '1.5px dashed #cbd5e1',
    borderRadius:   6,
    gap:            6,
  },
  noAddress: {
    display:        'flex',
    flexDirection:  'column',
    alignItems:     'center',
    justifyContent: 'center',
    background:     '#f8fafc',
    border:         '1.5px dashed #cbd5e1',
    borderRadius:   6,
    gap:            6,
  },
  noKeyIcon: {
    fontSize: 28,
  },
  noKeyTitle: {
    fontSize:   14,
    fontWeight: 600,
    color:      '#374151',
  },
  noKeyText: {
    fontSize:   12,
    color:      '#94a3b8',
    textAlign:  'center',
    lineHeight: 1.5,
  },
  caption: {
    fontSize:   11,
    color:      '#64748b',
    marginTop:  4,
    paddingLeft: 2,
  },
};
