/* global React, MAHANA_APPS, APPS_BY_ID, AppIcon */
// ─────────────────────────────────────────────────────────────
// AppsHome — the mobile Apps tab home screen.
// Composes: AppIcon (for each tile) + SuggestionCard (Mastermind note).
//
// Anatomy:
//   [TopBar]  "Apps" · "N connected"
//   [Grid]    4-col squircle grid of AppIcon tiles with labels under
//   [SuggestionCard] one proactive Mastermind note in a glass card
//
// Props:
//   apps          Array<App>   — defaults to MAHANA_APPS
//   connected     number|null  — override the count in subtitle; null hides
//   columns       number       — grid columns (default 4)
//   tileSize      number       — icon size in px (default 56)
//   suggestion    ReactNode    — body of the suggestion card; null hides
//   suggestionCta string       — optional CTA text
//   onOpenApp     (id) => void
//   variant       'mobile'|'desktop'  default mobile
//   width         number       — explicit container width (for previews)
//   height        number       — explicit container height
// ─────────────────────────────────────────────────────────────

function AppsHomeTopBar({ title, subtitle }) {
  return (
    <div style={{
      padding: '52px 16px 10px',
      display: 'flex', alignItems: 'center', gap: 10,
      position: 'relative',
      flexShrink: 0,
    }}>
      <span style={{ width: 36 }} />
      <div style={{ flex: 1, minWidth: 0, textAlign: 'center' }}>
        <div style={{
          fontFamily: window.MM_FONT, fontSize: 16, fontWeight: 700, color: '#1A1A1A',
          letterSpacing: '-0.015em',
        }}>{title}</div>
        {subtitle && (
          <div style={{
            fontFamily: window.MM_FONT, fontSize: 11, color: 'rgba(0,0,0,0.5)',
            marginTop: 1,
          }}>{subtitle}</div>
        )}
      </div>
      <span style={{ width: 36 }} />
    </div>
  );
}

function SuggestionCard({ body, cta, onClick }) {
  return (
    <div
      onClick={onClick}
      style={{
        padding: '14px 16px',
        background: 'rgba(255,255,255,0.72)',
        backdropFilter: 'blur(14px)',
        WebkitBackdropFilter: 'blur(14px)',
        borderRadius: 16,
        border: '1px solid rgba(0,0,0,0.06)',
        cursor: onClick ? 'pointer' : 'default',
        fontFamily: window.MM_FONT,
      }}
    >
      <div style={{
        fontSize: 10, fontWeight: 700, color: 'rgba(0,0,0,0.5)',
        textTransform: 'uppercase', letterSpacing: '0.08em',
        marginBottom: 8,
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <span style={{
          display: 'inline-block', width: 6, height: 6, borderRadius: '50%',
          background: 'linear-gradient(135deg, #FF7A29, #FF2DB4)',
        }} />
        Suggestion
      </div>
      <div style={{ fontSize: 13, color: '#1A1A1A', lineHeight: 1.4 }}>
        {body}
        {cta && (
          <span style={{ color: '#B5168A', fontWeight: 600, marginLeft: 4 }}>
            {cta} →
          </span>
        )}
      </div>
    </div>
  );
}

function AppsGrid({ apps = MAHANA_APPS, columns = 4, tileSize = 56, onOpenApp, showLabels = true, shape = 'circle' }) {
  // Square tiles have labels baked in — don't render our own label twice.
  const effectiveShowLabels = shape === 'square' ? false : showLabels;
  // Square tiles need more breathing room because the PNG already includes a border + padding.
  const gapRow = shape === 'square' ? 12 : 16;
  const gapCol = shape === 'square' ? 10 : 14;
  // Square tiles render slightly larger — the glyph inside the PNG is proportionally smaller.
  const effectiveSize = shape === 'square' ? Math.round(tileSize * 1.2) : tileSize;
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${columns}, 1fr)`,
      gap: `${gapRow}px ${gapCol}px`,
      marginTop: 6,
    }}>
      {apps.map(app => (
        <button
          key={app.id}
          onClick={() => onOpenApp?.(app.id)}
          style={{
            display: 'flex', flexDirection: 'column', alignItems: 'center',
            gap: 6, padding: 0, border: 'none', background: 'transparent',
            cursor: onOpenApp ? 'pointer' : 'default',
            fontFamily: window.MM_FONT,
          }}
        >
          <AppIcon app={app} size={effectiveSize} shape={shape} />
          {effectiveShowLabels && (
            <div style={{
              fontSize: 11, fontWeight: 500, color: '#1A1A1A',
              textAlign: 'center', maxWidth: 70, lineHeight: 1.2,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>
              {app.label}
            </div>
          )}
        </button>
      ))}
    </div>
  );
}

function AppsHome({
  apps = MAHANA_APPS,
  connected,
  columns = 4,
  tileSize = 56,
  suggestion,
  suggestionCta,
  onOpenApp,
  onOpenSuggestion,
  variant = 'mobile',
  width,
  height,
  showTopBar = true,
  showLabels = true,
  shape = 'circle',
}) {
  const count = connected != null ? connected : apps.length;
  const subtitle = count > 0 ? `${count} connected` : 'None connected yet';

  const isDesktop = variant === 'desktop';
  const cols = columns || (isDesktop ? 6 : 4);
  const tile = tileSize || (isDesktop ? 64 : 56);

  // Mobile: full-screen bg with rainbow gradient; desktop: flat paper
  const bg = isDesktop
    ? 'transparent'
    : `
      radial-gradient(ellipse at 50% 0%, rgba(255, 122, 41, 0.12), transparent 55%),
      radial-gradient(ellipse at 85% 20%, rgba(255, 45, 180, 0.14), transparent 50%),
      radial-gradient(ellipse at 10% 35%, rgba(155, 92, 255, 0.12), transparent 50%),
      radial-gradient(ellipse at 50% 90%, rgba(0, 212, 255, 0.10), transparent 55%),
      #FBF8F5
    `;

  return (
    <div style={{
      width: width || (isDesktop ? 640 : 390),
      height: height || (isDesktop ? 560 : 700),
      background: bg,
      display: 'flex', flexDirection: 'column',
      fontFamily: window.MM_FONT,
      borderRadius: isDesktop ? 0 : 32,
      overflow: 'hidden',
      position: 'relative',
      border: isDesktop ? 'none' : '1px solid rgba(0,0,0,0.06)',
    }}>
      {showTopBar && <AppsHomeTopBar title="Apps" subtitle={subtitle} />}
      <div style={{
        flex: 1, overflow: 'auto', WebkitOverflowScrolling: 'touch',
        padding: '8px 18px 24px',
      }}>
        <AppsGrid
          apps={apps}
          columns={cols}
          tileSize={tile}
          onOpenApp={onOpenApp}
          showLabels={showLabels}
          shape={shape}
        />
        {suggestion && (
          <div style={{ marginTop: 28 }}>
            <SuggestionCard body={suggestion} cta={suggestionCta} onClick={onOpenSuggestion} />
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AppsHome, AppsGrid, SuggestionCard, AppsHomeTopBar });
