// Naviyell — A-19 プロフィール編集 screen

function A19ProfileEdit() {
  const nav = useNav();
  const { state, patch } = useAppState();
  const user = state.currentUser;
  const userId = user?.id || 'default';
  const displayName =
    user?.user_metadata?.public_username || user?.user_metadata?.full_name || user?.user_metadata?.name || user?.email?.split('@')[0] || '美咲';
  // Use app state for born type, fall back to calculation from birthday (consistent with MyPage)
  const bornType = state.bornType || bornTypeFromBirthday(state.birthMonth || 7, state.birthDay || 15);

  // Load persisted data from app state or localStorage
  const storedAvatar = state.avatarUrl || localStorage.getItem('naviyell_avatar_' + userId) || '';
  const storedLastName = state.lastName || localStorage.getItem('naviyell_lastName_' + userId) || user?.user_metadata?.last_name || '';
  const storedFirstName = state.firstName || localStorage.getItem('naviyell_firstName_' + userId) || user?.user_metadata?.first_name || '';
  const storedIntro = state.selfIntro || localStorage.getItem('naviyell_selfIntro_' + userId) || MOCK_USER.typeDesc || '';
  const storedTwitter = state.twitter || localStorage.getItem('naviyell_twitter_' + userId) || '';
  const storedInstagram = state.instagram || localStorage.getItem('naviyell_instagram_' + userId) || '';

  const [lastName, setLastName] = React.useState(storedLastName);
  const [firstName, setFirstName] = React.useState(storedFirstName);
  const [selfIntro, setSelfIntro] = React.useState(storedIntro);
  const [twitter, setTwitter] = React.useState(storedTwitter);
  const [instagram, setInstagram] = React.useState(storedInstagram);
  const [avatarUrl, setAvatarUrl] = React.useState(storedAvatar);
  const [avatarFile, setAvatarFile] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const fileInputRef = React.useRef(null);

  const handleFileSelect = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) return;

    // Store the file for later upload, and show a local preview
    setAvatarFile(file);
    const reader = new FileReader();
    reader.onload = (event) => {
      setAvatarUrl(event.target.result);
    };
    reader.readAsDataURL(file);
  };

  const handleSave = async () => {
    setLoading(true);
    setError('');

    try {
      let finalAvatarUrl = avatarUrl;

      // If a new file was selected, upload to Supabase Storage
      if (avatarFile && typeof _sb !== 'undefined' && _sb.storage) {
        const fileExt = avatarFile.name.split('.').pop();
        const filePath = `${userId}/avatar.${fileExt}`;

        // Upload to the 'avatars' bucket
        const { error: uploadError } = await _sb.storage
          .from('avatars')
          .upload(filePath, avatarFile, { upsert: true });

        if (uploadError) throw uploadError;

        // Get the public URL
        const { data: urlData } = _sb.storage
          .from('avatars')
          .getPublicUrl(filePath);

        finalAvatarUrl = urlData?.publicUrl || avatarUrl;
      } else if (avatarFile) {
        // No Supabase — store as data URL in localStorage
        localStorage.setItem('naviyell_avatar_' + userId, avatarUrl);
      }

      const fullName = `${lastName} ${firstName}`.trim();

      // Save profile fields via Supabase if available
      let profileSaved = false;
      if (typeof DB !== 'undefined' && DB.updateProfile) {
        try {
          await DB.updateProfile({
            first_name: firstName,
            last_name: lastName,
            display_name: fullName,
            public_username: fullName,
            self_intro: selfIntro,
            twitter,
            instagram,
            avatar_url: finalAvatarUrl,
          });
          profileSaved = true;
        } catch (err) {
          console.warn('[ProfileEdit] Supabase save failed, falling back to localStorage:', err.message);
        }
      }

      if (!profileSaved) {
        // Fallback: save to localStorage
        localStorage.setItem('naviyell_lastName_' + userId, lastName);
        localStorage.setItem('naviyell_firstName_' + userId, firstName);
        localStorage.setItem('naviyell_selfIntro_' + userId, selfIntro);
        localStorage.setItem('naviyell_twitter_' + userId, twitter);
        localStorage.setItem('naviyell_instagram_' + userId, instagram);
      }

      // Update app state so MyPage reflects changes immediately
      patch({
        avatarUrl: finalAvatarUrl,
        displayName: fullName,
        lastName,
        firstName,
        selfIntro,
        twitter,
        instagram,
      });

      nav.back('mypage');
    } catch (err) {
      console.error('[ProfileEdit]', err.message);
      setError(err.message || '保存に失敗しました。もう一度お試しください。');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteImage = async () => {
    setAvatarUrl('');
    setAvatarFile(null);

    // Try to remove from Supabase Storage
    if (typeof _sb !== 'undefined' && _sb.storage) {
      try {
        await _sb.storage.from('avatars').remove([`${userId}/avatar`]);
      } catch (_) {
        // Ignore storage errors on delete
      }
    }

    localStorage.removeItem('naviyell_avatar_' + userId);
  };

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={<ACBack onClick={() => nav.back('mypage')} />} title='プロフィール編集' />
      <div style={{ flex: 1, overflow: 'auto', padding: '16px 20px 20px' }} className='ac-scroll'>
        {/* Avatar + change button */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '16px 0 24px' }}>
          <div style={{ position: 'relative' }}>
            {avatarUrl ? (
              <div
                style={{
                  width: 80,
                  height: 80,
                  borderRadius: '50%',
                  background: `center/cover url(${avatarUrl})`,
                  border: `2px solid ${A.ink100}`,
                }}
              />
            ) : (
              <ACAvatar size={80} name={displayName.charAt(0)} color={A.ink700} />
            )}
            <button
              onClick={() => fileInputRef.current?.click()}
              style={{
                position: 'absolute',
                bottom: 0,
                right: -2,
                width: 28,
                height: 28,
                borderRadius: '50%',
                background: A.gold500,
                border: `2px solid ${A.paper}`,
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: 0,
              }}>
              <svg width='14' height='14' viewBox='0 0 24 24' fill='none' stroke={A.ink900} strokeWidth='2' strokeLinecap='round'>
                <path d='M17 3l4 4M14 6l-9 9v4h4l9-9M14 6l-4-2M7 9l-2 4' />
              </svg>
            </button>
            <input
              ref={fileInputRef}
              type='file'
              accept='image/*'
              style={{ display: 'none' }}
              onChange={handleFileSelect}
            />
          </div>
          {avatarUrl && (
            <button
              onClick={handleDeleteImage}
              style={{
                marginTop: 8,
                border: 'none',
                background: 'transparent',
                color: A.danger,
                fontSize: 12,
                fontWeight: 500,
                cursor: 'pointer',
                fontFamily: 'inherit',
              }}>
              画像を削除
            </button>
          )}
        </div>

        {/* Error message */}
        {error && (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              padding: '12px 16px',
              borderRadius: 12,
              background: '#F5DDD9',
              color: A.danger,
              fontSize: 13,
              fontWeight: 500,
              marginBottom: 16,
              animation: 'ac-fade-in 200ms ease both',
            }}>
            <svg width='16' height='16' viewBox='0 0 24 24' fill='none' stroke={A.danger} strokeWidth='2'>
              <circle cx='12' cy='12' r='10' />
              <path d='M12 8v4M12 16h0' strokeLinecap='round' />
            </svg>
            {error}
          </div>
        )}

        {/* Form fields */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <ACInput label='姓' value={lastName} onChange={setLastName} placeholder='山田' />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <ACInput label='名' value={firstName} onChange={setFirstName} placeholder='太郎' />
            </div>
          </div>

          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: A.ink500, marginBottom: 6 }}>自己紹介</div>
            <textarea
              value={selfIntro}
              onChange={(e) => setSelfIntro(e.target.value)}
              placeholder='自分のことや、悩んでいることなど'
              rows={5}
              style={{
                width: '100%',
                padding: '14px 16px',
                borderRadius: 12,
                background: A.white,
                border: `1.5px solid ${A.ink100}`,
                fontSize: 14,
                color: A.ink900,
                fontFamily: 'inherit',
                outline: 'none',
                resize: 'none',
                lineHeight: 1.7,
              }}
              onFocus={(e) => (e.target.style.borderColor = A.gold500)}
              onBlur={(e) => (e.target.style.borderColor = A.ink100)}
            />
          </div>

          {/* SNS links */}
          <ACInput label='X（Twitter）' value={twitter} onChange={setTwitter} placeholder='@username' />
          <ACInput label='Instagram' value={instagram} onChange={setInstagram} placeholder='@username' />

          {/* Born type info (read-only) */}
          <div
            style={{
              background: `${A.gold100}55`,
              borderRadius: 14,
              padding: 16,
              border: `1px solid ${A.gold100}`,
            }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: A.gold600, marginBottom: 8 }}>あなたのタイプ</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div
                style={{
                  width: 36,
                  height: 36,
                  borderRadius: 10,
                  background: (ELEMENTS[bornType] || {}).color || A.gold500,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: A.white,
                  fontSize: 16,
                  fontWeight: 600,
                }}>
                {(ELEMENTS[bornType] || {}).label || '風'}
              </div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: A.ink900 }}>{(ELEMENTS[bornType] || {}).label || '風'}のサイン</div>
                <div style={{ fontSize: 12, color: A.ink500, marginTop: 2, lineHeight: 1.5 }}>{(ELEMENTS[bornType] || {}).desc || ''}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Save button */}
      <ACStickyCTA>
        <ACButton size='lg' onClick={handleSave} disabled={loading}>
          {loading ? '保存中...' : '保存する'}
        </ACButton>
      </ACStickyCTA>
    </div>
  );
}

Object.assign(window, { A19ProfileEdit });