// Profile.jsx — Edit-account screen
//
// Data model (DB-ready). Maps 1:1 to a `users` row in Postgres.
//
// Provided by Google OAuth (basic scope) — pre-filled, mostly immutable:
//   id, googleId, email, createdAt, avatarUrl (initial), displayName (initial)
//
// NOT provided by Google → must be asked of the user post-signup:
//   phone               — SMS reminders, group communication
//   birthDate           — birthday recognition, age-aware ministries
//   role                — what they do at the church
//   church              — which LaVid campus they belong to
//   instrument          — for musicians / worship leaders
//   bio                 — short self-intro
//   language            — UI preference
//   timeZone            — IANA tz; auto-detected on first signup, editable
//   nationalId          — DNI/NIE (sensitive: encrypt at rest, needed for fiscal receipts)
//   emergencyContact    — contacted only during retreats / ministry trips
//   notifications       — granular opt-ins
//
// Real implementation will:
//   - Hydrate from `GET /me` on mount
//   - On first login, prompt user to fill required-but-empty fields (phone, birthDate)
//   - PATCH /me on save (only dirty fields)
//   - Sign out via /auth/logout (clears session cookie)

const ROLES = [
  { id: 'worship_leader', label: 'Líder de alabanza', short: 'Líder' },
  { id: 'musician',       label: 'Músico',             short: 'Músico' },
  { id: 'vocalist',       label: 'Vocalista',          short: 'Vocal' },
  { id: 'tech',           label: 'Técnico',            short: 'Técnico' },
  { id: 'member',         label: 'Miembro',            short: 'Miembro' },
];

const CHURCHES = [
  { id: 'lavid_valencia',   label: 'LaVid Valencia' },
  { id: 'lavid_torrevieja', label: 'LaVid Torrevieja' },
];

const LANGUAGES = [
  { id: 'es', label: 'Español' },
  { id: 'en', label: 'English' },
  { id: 'pt', label: 'Português' },
];

const TIMEZONES = [
  { id: 'Europe/Madrid',          label: 'Madrid (CET)' },
  { id: 'Atlantic/Canary',        label: 'Canarias (WET)' },
  { id: 'America/Mexico_City',    label: 'Ciudad de México' },
  { id: 'America/Bogota',         label: 'Bogotá' },
  { id: 'America/Lima',           label: 'Lima' },
  { id: 'America/Buenos_Aires',   label: 'Buenos Aires' },
  { id: 'America/Sao_Paulo',      label: 'São Paulo' },
];

const RELATIONSHIPS = [
  { id: 'spouse',  label: 'Esposo/a' },
  { id: 'parent',  label: 'Padre / Madre' },
  { id: 'sibling', label: 'Hermano/a' },
  { id: 'child',   label: 'Hijo/a' },
  { id: 'friend',  label: 'Amigo/a' },
  { id: 'other',   label: 'Otro' },
];

const MOCK_USER = {
  // From Google OAuth
  id: 'usr_01HXYZ',
  googleId: '108374561239847562930',
  email: 'lucas.morales@lavid.es',
  displayName: 'Lucas Morales',
  avatarUrl: null,                  // null → render initial
  createdAt: '2024-04-26T10:00:00Z',
  updatedAt: '2026-04-27T07:00:00Z',

  // Asked of user (not in Google scopes)
  phone: '+34 612 345 678',         // E.164-friendly; empty for fresh users
  birthDate: '1990-04-26',          // ISO date YYYY-MM-DD; empty for fresh users
  role: 'worship_leader',
  church: 'lavid_valencia',
  instrument: 'Guitarra acústica',
  bio: 'Liderando alabanza desde 2019. Padre de dos.',
  language: 'es',
  timeZone: 'Europe/Madrid',        // IANA; auto-detected at signup via Intl.DateTimeFormat()
  nationalId: '12345678Z',          // DNI/NIE; encrypt at rest, used for fiscal receipts
  emergencyContact: {
    name: 'María Morales',
    phone: '+34 678 123 456',
    relationship: 'spouse',
  },
  notifications: {
    setlistUpdates: true,
    newSongs: true,
    reminders: false,
  },
};

// -- Helpers --------------------------------------------------------------

function initialsOf(name) {
  return (name || '?').split(/\s+/).filter(Boolean).slice(0, 2).map(s => s[0]).join('').toUpperCase();
}

function formatJoinDate(iso) {
  const d = new Date(iso);
  return d.toLocaleDateString('es-ES', { month: 'short', year: 'numeric' });
}

// -- iOS-style toggle -----------------------------------------------------

function Toggle({ checked, onChange, label }) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      aria-label={label}
      onClick={() => onChange(!checked)}
      style={{
        width: 48, height: 28, borderRadius: 14, border: 'none',
        background: checked
          ? 'linear-gradient(135deg, #B45EFF, #7C3AED)'
          : 'rgba(255,255,255,0.12)',
        position: 'relative', cursor: 'pointer', padding: 0,
        transition: 'background 0.25s cubic-bezier(0.22, 1, 0.36, 1)',
        boxShadow: checked
          ? '0 4px 14px rgba(168,85,247,0.4), inset 0 1px 0 rgba(255,255,255,0.25)'
          : 'inset 0 1px 2px rgba(0,0,0,0.3)',
      }}>
      <div style={{
        position: 'absolute', top: 2, left: checked ? 22 : 2,
        width: 24, height: 24, borderRadius: '50%',
        background: '#fff',
        boxShadow: '0 2px 6px rgba(0,0,0,0.35)',
        transition: 'left 0.28s cubic-bezier(0.34, 1.56, 0.64, 1)',
      }} />
    </button>
  );
}

// -- Section primitives ---------------------------------------------------

function Section({ title, subtitle, children }) {
  return (
    <div style={{ marginTop: 28 }}>
      <div style={{
        fontFamily: 'var(--hl-font-mono)', fontSize: 10,
        color: 'rgba(255,255,255,0.55)', letterSpacing: 1.6,
        textTransform: 'uppercase', fontWeight: 500,
        marginBottom: 12, paddingLeft: 4,
      }}>{title}</div>
      <div style={{
        background: 'rgba(255,255,255,0.04)',
        border: '1px solid rgba(255,255,255,0.07)',
        borderRadius: 18,
        overflow: 'hidden',
      }}>{children}</div>
      {subtitle && (
        <div style={{
          marginTop: 8, paddingLeft: 16, paddingRight: 16,
          fontSize: 11, lineHeight: 1.45, color: 'rgba(255,255,255,0.4)',
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.1,
        }}>{subtitle}</div>
      )}
    </div>
  );
}

function Row({ label, children, last = false }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 16px',
      borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.05)',
      gap: 14,
    }}>
      <div style={{
        fontSize: 14, color: 'rgba(255,255,255,0.75)',
        fontWeight: 500, letterSpacing: -0.1,
        flexShrink: 0,
      }}>{label}</div>
      <div style={{ flex: 1, display: 'flex', justifyContent: 'flex-end', minWidth: 0 }}>
        {children}
      </div>
    </div>
  );
}

function InlineInput({ value, onChange, placeholder, type = 'text', readOnly = false, maxLength }) {
  return (
    <input
      type={type} value={value || ''}
      onChange={e => onChange && onChange(e.target.value)}
      placeholder={placeholder}
      readOnly={readOnly}
      maxLength={maxLength}
      style={{
        background: 'transparent', border: 'none', outline: 'none',
        textAlign: 'right', color: readOnly ? 'rgba(255,255,255,0.4)' : '#fff',
        fontSize: 15, fontFamily: 'var(--hl-font-ui)', fontWeight: 500,
        letterSpacing: -0.2, width: '100%', padding: 0,
        minWidth: 0,
      }}
    />
  );
}

function PickerRow({ label, value, options, onPick, last }) {
  const [open, setOpen] = React.useState(false);
  const current = options.find(o => o.id === value);

  return (
    <>
      <Row label={label} last={last}>
        <button type="button" onClick={() => setOpen(o => !o)} style={{
          background: 'transparent', border: 'none',
          color: 'var(--hl-accent-light)', fontSize: 15, fontWeight: 500,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
          padding: 0,
        }}>
          {current?.label}
          <svg width="10" height="10" viewBox="0 0 12 12" fill="none"
            style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 0.22s ease' }}>
            <path d="M2 4l4 4 4-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
      </Row>
      {open && (
        <div style={{
          padding: '8px 12px 16px',
          borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.05)',
          display: 'flex', flexWrap: 'wrap', gap: 8,
        }}>
          {options.map(o => (
            <button key={o.id} type="button"
              onClick={() => { onPick(o.id); setOpen(false); }}
              style={{
                padding: '8px 14px', borderRadius: 12,
                background: o.id === value ? 'linear-gradient(135deg, rgba(180,94,255,0.25), rgba(79,31,203,0.25))' : 'rgba(255,255,255,0.04)',
                border: o.id === value ? '1px solid rgba(192,132,252,0.5)' : '1px solid rgba(255,255,255,0.06)',
                color: o.id === value ? '#fff' : 'rgba(255,255,255,0.7)',
                fontSize: 13, fontWeight: 500, fontFamily: 'var(--hl-font-ui)',
                cursor: 'pointer', letterSpacing: -0.1,
                transition: 'all 0.18s ease',
              }}>
              {o.label}
            </button>
          ))}
        </div>
      )}
    </>
  );
}

// -- ProfileScreen --------------------------------------------------------

function ProfileScreen({ user = MOCK_USER, onBack, onSave, onLogout, onReplayTutorial }) {
  const [draft, setDraft] = React.useState(user);
  const [saving, setSaving] = React.useState(false);

  const dirty = React.useMemo(() => JSON.stringify(draft) !== JSON.stringify(user), [draft, user]);

  const set = (patch) => setDraft(d => ({ ...d, ...patch }));
  const setNotif = (key, v) => setDraft(d => ({ ...d, notifications: { ...d.notifications, [key]: v } }));
  const setEmergency = (key, v) => setDraft(d => ({
    ...d,
    emergencyContact: { ...(d.emergencyContact || {}), [key]: v },
  }));

  const handleSave = async () => {
    if (!dirty || saving) return;
    setSaving(true);
    // Real impl: PATCH /me with diff(draft, user). Prototype just simulates the spinner.
    await new Promise(r => setTimeout(r, 600));
    setSaving(false);
    onSave && onSave(draft);
  };

  return (
    <div style={{
      height: '100%', overflow: 'hidden', position: 'relative',
      background: 'linear-gradient(180deg, #0E0726 0%, #08051A 50%, #04020E 100%)',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* ambient orbs */}
      <div style={{
        position: 'absolute', top: -150, left: -100, width: 360, height: 360,
        borderRadius: '50%', filter: 'blur(110px)', opacity: 0.32, pointerEvents: 'none',
        background: 'radial-gradient(circle, #A855F7, transparent 65%)',
        animation: 'hldrift 16s ease-in-out infinite',
      }} />
      <div style={{
        position: 'absolute', top: '50%', right: -130, width: 320, height: 320,
        borderRadius: '50%', filter: 'blur(110px)', opacity: 0.22, pointerEvents: 'none',
        background: 'radial-gradient(circle, #4F1FCB, transparent 65%)',
        animation: 'hldrift 20s ease-in-out infinite reverse',
      }} />
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.05, pointerEvents: 'none',
        backgroundImage: 'radial-gradient(rgba(255,255,255,0.5) 1px, transparent 1px)',
        backgroundSize: '3px 3px',
      }} />

      {/* Nav bar */}
      <div style={{
        flexShrink: 0, paddingTop: 60, paddingBottom: 8,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '60px 16px 8px', position: 'relative', zIndex: 3,
        background: 'linear-gradient(180deg, rgba(14,7,38,0.95), rgba(14,7,38,0.7) 70%, transparent)',
        backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
      }}>
        <button type="button" onClick={onBack} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--hl-accent-light)', display: 'flex', alignItems: 'center', gap: 4,
          fontSize: 16, fontFamily: 'var(--hl-font-ui)', fontWeight: 500,
          padding: '8px 4px', letterSpacing: -0.2,
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
            stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="15 18 9 12 15 6" />
          </svg>
          Atrás
        </button>
        <div style={{
          fontFamily: 'var(--hl-font-display)', fontSize: 17,
          color: '#fff', fontWeight: 500, letterSpacing: -0.3,
        }}>Perfil</div>
        <button type="button" onClick={handleSave} disabled={!dirty || saving} style={{
          background: 'transparent', border: 'none',
          cursor: (!dirty || saving) ? 'default' : 'pointer',
          color: dirty ? 'var(--hl-accent-light)' : 'rgba(255,255,255,0.3)',
          fontSize: 16, fontFamily: 'var(--hl-font-ui)',
          fontWeight: dirty ? 600 : 500, letterSpacing: -0.2,
          padding: '8px 4px',
          transition: 'color 0.2s ease',
        }}>
          {saving ? 'Guardando…' : 'Guardar'}
        </button>
      </div>

      {/* Scrollable body */}
      <div style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        position: 'relative', zIndex: 2,
        padding: '8px 20px calc(40px + var(--safe-bottom, 16px))',
      }}>
        {/* Avatar hero */}
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          marginTop: 20, marginBottom: 8,
        }}>
          <div style={{ position: 'relative' }}>
            {/* halo */}
            <div style={{
              position: 'absolute', inset: -16, borderRadius: '50%',
              background: 'radial-gradient(circle, rgba(192,132,252,0.4), transparent 65%)',
              filter: 'blur(14px)',
              animation: 'hlbreathe 3.5s ease-in-out infinite',
            }} />
            <div style={{
              position: 'relative',
              width: 96, height: 96, borderRadius: '50%',
              background: draft.avatarUrl
                ? `url(${draft.avatarUrl}) center/cover`
                : 'linear-gradient(135deg, #B45EFF, #7C3AED 50%, #4F1FCB)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--hl-font-display)', fontStyle: 'italic',
              fontSize: 36, fontWeight: 400, color: '#fff',
              letterSpacing: -1, boxShadow: '0 16px 50px rgba(168,85,247,0.5), inset 0 1px 0 rgba(255,255,255,0.3)',
            }}>
              {!draft.avatarUrl && initialsOf(draft.displayName)}
            </div>
            {/* edit overlay */}
            <button type="button" aria-label="Cambiar foto" style={{
              position: 'absolute', right: -2, bottom: -2,
              width: 30, height: 30, borderRadius: '50%',
              background: 'rgba(14,7,38,0.95)',
              border: '2px solid rgba(192,132,252,0.7)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', padding: 0,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                <circle cx="12" cy="13" r="4"/>
              </svg>
            </button>
          </div>

          <div style={{
            marginTop: 18, fontFamily: 'var(--hl-font-display)',
            fontSize: 26, fontWeight: 400, color: '#fff',
            letterSpacing: -0.6, lineHeight: 1, fontStyle: 'italic',
          }}>{draft.displayName || 'Sin nombre'}</div>
          <div style={{
            marginTop: 6, fontSize: 13, color: 'rgba(255,255,255,0.55)',
            fontFamily: 'var(--hl-font-mono)', letterSpacing: -0.1,
          }}>{draft.email}</div>
        </div>

        <Section title="Información personal">
          <Row label="Nombre">
            <InlineInput
              value={draft.displayName}
              onChange={v => set({ displayName: v })}
              placeholder="Tu nombre"
              maxLength={60}
            />
          </Row>
          <Row label="Email">
            <InlineInput value={draft.email} readOnly />
          </Row>
          <Row label="Teléfono">
            <InlineInput
              type="tel"
              value={draft.phone}
              onChange={v => set({ phone: v })}
              placeholder="+34 600 000 000"
              maxLength={20}
            />
          </Row>
          <Row label="Fecha de nacimiento">
            <input
              type="date"
              value={draft.birthDate || ''}
              onChange={e => set({ birthDate: e.target.value })}
              max={new Date().toISOString().slice(0, 10)}
              min="1900-01-01"
              style={{
                background: 'transparent', border: 'none', outline: 'none',
                textAlign: 'right',
                color: draft.birthDate ? '#fff' : 'rgba(255,255,255,0.4)',
                fontSize: 15, fontFamily: 'var(--hl-font-ui)', fontWeight: 500,
                letterSpacing: -0.2, padding: 0,
                colorScheme: 'dark',
              }}
            />
          </Row>
          <PickerRow
            label="Rol"
            value={draft.role}
            options={ROLES}
            onPick={v => set({ role: v })}
          />
          {(draft.role === 'musician' || draft.role === 'worship_leader') && (
            <Row label="Instrumento" last>
              <InlineInput
                value={draft.instrument}
                onChange={v => set({ instrument: v })}
                placeholder="Guitarra, piano…"
                maxLength={40}
              />
            </Row>
          )}
        </Section>

        <Section title="Comunidad">
          <PickerRow
            label="Iglesia"
            value={draft.church}
            options={CHURCHES}
            onPick={v => set({ church: v })}
          />
          <PickerRow
            label="Idioma"
            value={draft.language}
            options={LANGUAGES}
            onPick={v => set({ language: v })}
          />
          <PickerRow
            label="Zona horaria"
            value={draft.timeZone}
            options={TIMEZONES}
            onPick={v => set({ timeZone: v })}
            last
          />
        </Section>

        <Section
          title="Documento de identidad"
          subtitle="Solo necesario para emitir recibos fiscales (Hacienda) y registros legales de la iglesia. Se almacena cifrado.">
          <Row label="DNI / NIE" last>
            <InlineInput
              value={draft.nationalId}
              onChange={v => set({ nationalId: v.toUpperCase() })}
              placeholder="12345678Z"
              maxLength={9}
            />
          </Row>
        </Section>

        <Section
          title="Contacto de emergencia"
          subtitle="Solo se usa en emergencias durante retiros, viajes ministeriales o eventos.">
          <Row label="Nombre">
            <InlineInput
              value={draft.emergencyContact?.name}
              onChange={v => setEmergency('name', v)}
              placeholder="Nombre completo"
              maxLength={60}
            />
          </Row>
          <Row label="Teléfono">
            <InlineInput
              type="tel"
              value={draft.emergencyContact?.phone}
              onChange={v => setEmergency('phone', v)}
              placeholder="+34 600 000 000"
              maxLength={20}
            />
          </Row>
          <PickerRow
            label="Relación"
            value={draft.emergencyContact?.relationship}
            options={RELATIONSHIPS}
            onPick={v => setEmergency('relationship', v)}
            last
          />
        </Section>

        <Section title="Notificaciones">
          <Row label="Cambios en setlist">
            <Toggle
              checked={draft.notifications.setlistUpdates}
              onChange={v => setNotif('setlistUpdates', v)}
              label="Cambios en setlist"
            />
          </Row>
          <Row label="Nuevas canciones">
            <Toggle
              checked={draft.notifications.newSongs}
              onChange={v => setNotif('newSongs', v)}
              label="Nuevas canciones"
            />
          </Row>
          <Row label="Recordatorios" last>
            <Toggle
              checked={draft.notifications.reminders}
              onChange={v => setNotif('reminders', v)}
              label="Recordatorios"
            />
          </Row>
        </Section>

        <Section title="Ayuda">
          <Row label="Ver tutorial otra vez" last>
            <button type="button" onClick={onReplayTutorial} style={{
              background: 'transparent', border: 'none',
              color: 'var(--vesper-glow, #DDD6FE)',
              fontSize: 15, fontWeight: 500,
              fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
              cursor: 'pointer', padding: 0,
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              Ver tutorial
              <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                <path d="M5 2l5 5-5 5" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
          </Row>
        </Section>

        <Section title="Sobre ti">
          <div style={{ padding: '14px 16px' }}>
            <textarea
              value={draft.bio || ''}
              onChange={e => set({ bio: e.target.value })}
              placeholder="Cuenta algo sobre ti, tu rol en la comunidad, lo que más disfrutas…"
              maxLength={240}
              rows={3}
              style={{
                width: '100%', minHeight: 70, resize: 'vertical',
                background: 'transparent', border: 'none', outline: 'none',
                color: '#fff', fontSize: 15, fontFamily: 'var(--hl-font-ui)',
                lineHeight: 1.5, letterSpacing: -0.2,
                padding: 0, boxSizing: 'border-box',
              }}
            />
            <div style={{
              textAlign: 'right', marginTop: 6, fontSize: 11,
              color: 'rgba(255,255,255,0.35)', fontFamily: 'var(--hl-font-mono)',
            }}>{(draft.bio || '').length} / 240</div>
          </div>
        </Section>

        {/* Logout */}
        <button type="button" onClick={onLogout} style={{
          marginTop: 32, width: '100%', height: 52, borderRadius: 16,
          background: 'rgba(244, 63, 94, 0.08)',
          border: '1px solid rgba(244, 63, 94, 0.25)',
          color: '#FB7185', fontSize: 15, fontWeight: 600,
          fontFamily: 'var(--hl-font-ui)', letterSpacing: -0.2,
          cursor: 'pointer',
          transition: 'background 0.18s ease',
        }}>Cerrar sesión</button>

        {/* Account meta */}
        <div style={{
          marginTop: 22, textAlign: 'center',
          fontSize: 11, color: 'rgba(255,255,255,0.35)',
          fontFamily: 'var(--hl-font-mono)', letterSpacing: 1.4,
          textTransform: 'uppercase',
        }}>
          Miembro desde {formatJoinDate(draft.createdAt)} ·{' '}
          {CHURCHES.find(c => c.id === draft.church)?.label}
        </div>
        <div style={{
          marginTop: 6, textAlign: 'center',
          fontSize: 10, color: 'rgba(255,255,255,0.25)',
          fontFamily: 'var(--hl-font-mono)', letterSpacing: 1,
        }}>id · {draft.id}</div>
      </div>
    </div>
  );
}

Object.assign(window, { ProfileScreen, MOCK_USER });
